find the standard deviation of a list of numbers in csharp

Here's a simple code block to calculate the standard deviation of a list of numbers in C#:

main.cs
public double CalculateStandardDeviation(List<double> numbers)
{
    double mean = numbers.Sum() / (double)numbers.Count;
    double variance = numbers.Sum(x => Math.Pow(x - mean, 2)) / (double)numbers.Count;
    double standardDeviation = Math.Sqrt(variance);
    return standardDeviation;
}
293 chars
8 lines

Here, we first calculate the mean of the list of numbers by dividing the sum of all the numbers by the count of the numbers in the list. Then, we calculate the variance by summing up the squares of the differences between each number and the mean, and dividing it by the count of the numbers. Finally, we take the square root of the variance to get the standard deviation.

You can call this method by passing in a list of double numbers:

main.cs
List<double> numbers = new List<double> { 2.0, 4.0, 6.0, 8.0 };
double standardDeviation = CalculateStandardDeviation(numbers);
Console.WriteLine("The standard deviation of {0} is {1}.", string.Join(",", numbers), standardDeviation);
234 chars
4 lines

This will output the following to the console:

main.cs
The standard deviation of 2,4,6,8 is 2.23606797749979.
55 chars
2 lines

gistlibby LogSnag