Logo

Programming-Idioms

  • Go
  • Python
  • Ruby

Idiom #203 Calculate mean and standard deviation

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

m  = data.sum / data.length.to_f
sd = Math.sqrt data.sum { |n| (m-n)**2 } / data.length.to_f 

.to_f forces floating point
import "github.com/gonum/stat"
m, s := stat.MeanStdDev(data, nil)

github.com/gonum/stat is a third party package, but well established.
import statistics
m = statistics.mean(data)
sd = statistics.stdev(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