To calculate the standard deviation of a List of numbers in C#, we can solve it it essentially four steps. Each of them are listed by color below:
- Finding the average of a list of number.
- Square the value of every number together, and add them together.
- Take the result from Step 2 and divide by the number of values in the list.
- Take the result from Step 3 and subtract by the square of the average. Because this is the result, we also return the value here.
Below, we have the actual function that performs the operation. The colors coordinate with the steps previously mentioned above.
private double getStandardDeviation(List<double> doubleList)
{
double average = doubleList.Average();
double sumOfDerivation = 0;
foreach (double value in doubleList)
{
sumOfDerivation += (value) * (value);
}
double sumOfDerivationAverage = sumOfDerivation / doubleList.Count;
return Math.Sqrt(sumOfDerivationAverage - (average*average));
}
RSS Feed
Posted in
Tags: 

Victor:
double average = doubleList.Average(); Error here?
Thanks
You need to be using at least version 3 of dotnet. I guess you are using version 2.
Using a lambda expression and the Math library…
private double getStandardDeviation(List doubleList)
{
double average = doubleList.Average();
double sumOfDerivation = 0;
doubleList.ForEach(v => sumOfDerivation += Math.Pow(v, 2));
double sumOfDerivationAverage = sumOfDerivation / doubleList.Count;
return Math.Sqrt(sumOfDerivationAverage – Math.Pow(average, 2));
}
Also, you want to check that your ‘List doubleList’ is not empty before trying the ‘.Average()’ method on it.
Altough you’re toplisted for standard deviation in C# the code is wrong.
You can double check this in Excel if you like. The problem I think is that you first average all the numbers, then average them and then substract the squared average. While instead you should square the number-average.
The correct code (double checked with excel)
[code]
///
///Calculates standard deviation of numbers in an ArrayList
///
public static double StandardDeviation(List num)
{
double SumOfSqrs = 0;
double avg = num.Average();
for (int i = 0; i < num.Count; i++)
{
SumOfSqrs += Math.Pow(((double)num[i] - avg), 2);
}
double n = (double)num.Count;
return Math.Sqrt(SumOfSqrs / (n - 1));
}
[/]
(adapted from: http://www.codekeep.net/snippets/37c89007-18f2-4a11-9f51-5c622d5a7813.aspx )