Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #203 Calculate mean and standard deviation

Calculate the mean m and the standard deviation s of the list of floating point values data.

using System.Linq;
using System.Collections.Generic;
var m = data.Average();
var s = CalculateStdDev(data);

float CalculateStdDev(IEnumerable<float> values)
{
	double ret = 0;

	if (values.Count() > 0)
	{
		double avg = values.Average();
	      	double sum = values.Sum(d => Math.Pow(d - avg, 2));
	      	ret = Math.Sqrt((sum) / values.Count()-1);
	}
	return (float)ret;
}

New implementation...
< >
Bart