Python标准偏差检查

我写了一个python代码来计算一个数字列表的标准偏差。 我检查了我的答案在Excel中,它似乎是closures的。 我不知道我是否错过了一个步骤,或者我应该担心,但是如果有人有时间审查代码,看看他们是否注意到错误,请告诉我。 谢谢。

city_population = [2123,1284,7031,30788,147,2217,10000] mean = sum(city_population,0.0)/len(city_population) def stdev(city_population): length = len(city_population) total_sum = 0 for i in range(length): total_sum += pow((city_population[i]-mean),2) result = (total_sum/(length-1)) return sqrt(result) stan_dev = stdev(city_population) print "The standard deviation is",(stan_dev) 

输出: The standard deviation is 9443.71609738

excel: 9986.83890663

你的问题主要是由于你的循环内的代码来计算总和。 在这个循环中,你也计算每次迭代的结果,然后从函数返回。 这意味着循环只有一个迭代运行。

在运行你的代码时,我得到的结果是2258.72114877,这是从第一个值计算出来的。 通过将代码更改为以下内容,将生成正确的样本标准偏差:

 city_population = [2123,1284,7031,30788,147,2217,10000] mean = sum(city_population,0.0)/len(city_population) def stdev(city_population): length = len(city_population) total_sum = 0 for i in range(length): total_sum += pow((city_population[i]-mean),2) # total_sum is 698158659.4285713 result = (total_sum/(length-1)) # result is 116359776.57142855 # sqrt(result) is 10787.01889177119 return sqrt(result) stan_dev = stdev(city_population) print "The standard deviation is",(stan_dev) 

这个新的结果与Excel的值不同的原因是Excel正在返回总体标准偏差。 作为快速参考,以下页面可能对您有用:

https://statistics.laerd.com/statistical-guides/measures-of-spread-standard-deviation.php

如果不需要从头开始编写代码,那么我build议使用Numpy来避免重新发明轮子: http : //www.numpy.org/ 。 有了这个,你的代码变成:

 import numpy city_population = [2123,1284,7031,30788,147,2217,10000] numpy.std(city_population, ddof=1) 

还有一些提示:为了避免将来的混淆和潜在的问题,尽量避免将函数参数命名为全局variables。 并且尽量不要依赖以前在一个函数中设置的variables(就像你在这里用“mean”所做的那样)。

问题是,你有循环内的回报!

以下应该工作:

 def stdev(city_population): length = len(city_population) total_sum = 0 for i in range(length): total_sum += pow((city_population[i]-mean),2) result = (total_sum/(length)) return sqrt(result) 

而不是标准偏差,你需要除以长度不是长度-1(这将是如果你有一个样本,而不是整个人口)。