Wednesday, April 30, 2008

Linq Goodies 2 - Calculating Standard Deviation

Check out the following function, which calculates the Standard Deviation of a given list of values:

private static double calcStdev(IEnumerable<double> values)
{
double avg = values.Average();
return Math.Sqrt( (values.Sum(d => Math.Pow(d - avg, 2))) / (values.Count() - 1) );
}



Extra sweet...



Note that I could have replaced (d - avg) with (d - values.Average()) , hence resulting in a single line instead of 2, but the performance hit isn't worth it.



It may not look very readable looking at it as a programmer, but if you look at the mathematical formula of standard deviation, the above code is much closer to it than anything I've previously seen in C*.

No comments: