Logo

Programming-Idioms

  • Clojure
  • Java

Idiom #203 Calculate mean and standard deviation

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

import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static java.util.stream.DoubleStream.of;
int n = data.length;
double m = of(data).sum() / n,
       s = of(data).map(x -> pow(x - m, 2)).sum();
s = sqrt(s / n);
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