Pages

Showing posts with label Financial Statistics. Show all posts
Showing posts with label Financial Statistics. Show all posts

Friday, November 11, 2011

How to calculate the Linest of given numbers


Linest function in excel returns a table of statistics for a straight line that best fits a data set.

The C# code for getting the linest of numbers is given below:

public static double CalculateLinest(double[] y, double[] x)
{
   double linest = 0;
   if (y.Length == x.Length)
   {
      double avgY = y.Average();
      double avgX = x.Average();
      double[] dividend = new double[y.Length];
      double[] divisor = new double[y.Length];
      for (int i = 0; i < y.Length; i++)
      {
         dividend[i] = (x[i] - avgX) * (y[i] - avgY);
         divisor[i] = Math.Pow((x[i] - avgX), 2);
      }
      linest = dividend.Sum() / divisor.Sum();
   }
   return linest;
}

Wednesday, May 25, 2011

How to calculate standard deviation of given numbers

The standard deviation of numbers is calculated as below:





The C# code to calculate the standard deviation is given below:

public double CalculateStandardDeviation(double?[] numbers)
{
   // select only non null numbers from the input array
   numbers = numbers.Where(n => n.HasValue).ToArray(); 

   // square of sum of numbers
   double sqrOfSum = Math.Pow(numbers.Sum().Value,2); 

   // sum of squares of numbers
   double sumOfSqrs = numbers.Sum(n => Math.Pow(n.Value, 2));

   // number of values in set
   double count = (double)numbers.Length; 

   // calculates the dividend part of formula
   double dividend = (count * sumOfSqrs) - sqrOfSum; 

   // returns standard deviation
   return Math.Sqrt(dividend / (count * (count - 1)));
}