如何确定一组值的标准偏差(stddev)?

我需要知道一个与一组数字相比的数字是否在均值之外的1个stddev之外。



肥皂起泡泡
浏览 1326回答 3
3回答

哆啦的时光机

虽然平方和算法在大多数情况下都可以正常工作,但是如果您要处理非常大的数字,可能会造成很大的麻烦。您基本上可能最终会得到负方差...另外,永远不要永远将a ^ 2计算为pow(a,2),几乎可以肯定a * a更快。到目前为止,计算标准差的最佳方法是韦尔福德方法。我的C非常生锈,但是看起来可能像这样:public static double StandardDeviation(List<double> valueList){&nbsp; &nbsp; double M = 0.0;&nbsp; &nbsp; double S = 0.0;&nbsp; &nbsp; int k = 1;&nbsp; &nbsp; foreach (double value in valueList)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; double tmpM = M;&nbsp; &nbsp; &nbsp; &nbsp; M += (value - tmpM) / k;&nbsp; &nbsp; &nbsp; &nbsp; S += (value - tmpM) * (value - M);&nbsp; &nbsp; &nbsp; &nbsp; k++;&nbsp; &nbsp; }&nbsp; &nbsp; return Math.Sqrt(S / (k-2));}如果您拥有全部人口(而不是样本人口),请使用return Math.Sqrt(S / (k-1));。编辑:我已经根据杰森的言论更新了代码...编辑:我还根据亚历克斯的言论更新了代码...

开心每一天1111

解决方案比Jaime的解决方案快10倍,但是请注意,正如Jaime指出的那样:“虽然平方和算法在大多数情况下都可以正常工作,但是如果要处理非常大的数字,可能会造成很大的麻烦。基本上,您最终可能会得到负方差”如果您认为要处理的是非常大的数字或数量非常大的数字,则应使用两种方法进行计算,如果结果相等,则可以确定可以使用“我的”方法。&nbsp; &nbsp; public static double StandardDeviation(double[] data)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; double stdDev = 0;&nbsp; &nbsp; &nbsp; &nbsp; double sumAll = 0;&nbsp; &nbsp; &nbsp; &nbsp; double sumAllQ = 0;&nbsp; &nbsp; &nbsp; &nbsp; //Sum of x and sum of x²&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < data.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; double x = data[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sumAll += x;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sumAllQ += x * x;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //Mean (not used here)&nbsp; &nbsp; &nbsp; &nbsp; //double mean = 0;&nbsp; &nbsp; &nbsp; &nbsp; //mean = sumAll / (double)data.Length;&nbsp; &nbsp; &nbsp; &nbsp; //Standard deviation&nbsp; &nbsp; &nbsp; &nbsp; stdDev = System.Math.Sqrt(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (sumAllQ -&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (sumAll * sumAll) / data.Length) *&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (1.0d / (data.Length - 1))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; return stdDev;&nbsp; &nbsp; }

慕森王

Jaime接受的答案很好,除了您需要在最后一行除以k-2(您需要除以“ number_of_elements-1”)。更好的是,将k从0开始:public static double StandardDeviation(List<double> valueList){&nbsp; &nbsp; double M = 0.0;&nbsp; &nbsp; double S = 0.0;&nbsp; &nbsp; int k = 0;&nbsp; &nbsp; foreach (double value in valueList)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; k++;&nbsp; &nbsp; &nbsp; &nbsp; double tmpM = M;&nbsp; &nbsp; &nbsp; &nbsp; M += (value - tmpM) / k;&nbsp; &nbsp; &nbsp; &nbsp; S += (value - tmpM) * (value - M);&nbsp; &nbsp; }&nbsp; &nbsp; return Math.Sqrt(S / (k-1));}
打开App,查看更多内容
随时随地看视频慕课网APP