Calculate Variance
using System;
using System.Collections.Generic;
public static class MathUtil
{
public static double CalculateVariance<T>(IEnumerable<T> data, Func<T, double> extractNumber)
{
var sumOfSquared = 0.0;
var sum = 0.0;
var length = 0;
foreach (var variable in data)
{
var number = extractNumber(variable);
sumOfSquared += (number * number);
sum += number;
length++;
}
if (length <= 1) return 0;
return CalculateVariance(sumOfSquared, sum, length);
}
public static double CalculateStandardDeviation<T>(IEnumerable<T> data, Func<T, double> extractNumber)
{
var variance = CalculateVariance(data, extractNumber);
if (variance <= 1) return 0;
return Math.Sqrt(variance);
}
public static double CalculateVariance(double sumOfSquared, double sum, int length)
{
if (length <= 0)
{
throw new ArgumentException("CalculateVariance cannot accept length equal to or less than one", "length");
}
return (sumOfSquared - ((sum * sum) / length)) / (length - 1);
}
public static double CalculateStandardDeviation(double sumOfSquared, double sum, int length)
{
var variance = CalculateVariance(sumOfSquared, sum, length);
return Math.Sqrt(variance);
}
}
Related examples in the same category