LINQ中的标准偏差
LINQ模型集合SQL函数STDDEV()
(标准差)?
如果不是,那么计算最简单/最佳实践的方法是什么?
例:
SELECT test_id, AVERAGE(result) avg, STDDEV(result) std FROM tests GROUP BY test_id
你可以让自己的扩展计算它
public static class Extensions { public static double StdDev(this IEnumerable<double> values) { double ret = 0; int count = values.Count(); if (count > 1) { //Compute the Average double avg = values.Average(); //Perform the Sum of (value-avg)^2 double sum = values.Sum(d => (d - avg) * (d - avg)); //Put it all together ret = Math.Sqrt(sum / count); } return ret; } }
如果你有一个样本的人口,而不是整个人口,那么你应该使用ret = Math.Sqrt(sum / (count - 1));
。
由Chris Bennett将“添加标准偏差”转化为“ LINQ” 。
Dynami的答案有效,但通过数据多次传递以获得结果。 这是计算样本标准偏差的单程法:
public static double StdDev(this IEnumerable<double> 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; }
这是样本标准差,因为它除以n - 1
。 对于正常的标准偏差,你需要用n
除以代替。
这就使用了与Average(x^2)-Average(x)^2
方法相比具有更高数值精度的Welford方法。
这将David Clarke的答案转换成与其他集合LINQ函数(如Average)相同的扩展。
用法是: var stdev = data.StdDev(o => o.number)
public static class Extensions { public static double StdDev<T>(this IEnumerable<T> list, Func<T, double> values) { // ref: https://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; } }
var stddev = Math.Sqrt(data.Average(z=>z*z)-Math.Pow(data.Average(),2));
public static double StdDev(this IEnumerable<int> values, bool as_sample = false) { var count = values.Count(); if (count > 0) // check for divide by zero // Get the mean. double mean = values.Sum() / count; // Get the sum of the squares of the differences // between the values and the mean. var squares_query = from int value in values select (value - mean) * (value - mean); double sum_of_squares = squares_query.Sum(); return Math.Sqrt(sum_of_squares / (count - (as_sample ? 1 : 0))) }