Sunday, April 24, 2016
public static double StdDev<T>(this IEnumerable<T> list, Func<T, double> values)
{
// ref: http://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation
// ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/
var mean = 0.0;
var sum = 0.0;
var stdDev = 0.0;
var n = 0;
foreach (var value in list.Select(values))
{
n++;
var delta = value - mean;
mean += delta / n;
sum += delta * (value - mean);
}
if (1 < n)
stdDev = Math.Sqrt(sum / (n - 1));
return stdDev;
}
Or
public static double StdDev(this IEnumerable values)
{
// ref: http://warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/
double mean = 0.0;
double sum = 0.0;
double stdDev = 0.0;
int n = 0;
foreach (double val in values)
{
n++;
double delta = val - mean;
mean += delta / n;
sum += delta * (val - mean);
}
if (1 < n)
stdDev = Math.Sqrt(sum / (n - 1));
return stdDev;
}
ref: http://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation
1 Comment:
-
- Duc Nguyen said...
April 24, 2016 at 5:25 PMhttp://csharphelper.com/blog/2015/12/make-an-extension-method-that-calculates-standard-deviation-in-c/
Subscribe to:
Post Comments (Atom)