Pages

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)));
}