Tuesday, September 06, 2005

Variance calculation in c#

I found this algorithm a little tricky to get right, so I thought I should post it.

It calculates the variance for a set of input data using the formula Excel uses

private double CalculateVariance(double[] input)
{
double sumOfSquares = 0.0;
double total = 0.0;
foreach(double d in input)
{
total+=d;
sumOfSquares += Math.Pow(d, 2);
}
int n = input.Length;
return ((n * sumOfSquares) - Math.Pow(total, 2)) / (n * (n - 1));
}

2 comments:

Ritesh Desale said...

Thanks It really help me

Simon said...

you're welcome!