from math import sqrt
a = range(0,20000)
def sdevs(a):
sds = [0]
n = 1
sum_x = a[0]
sum_x_squared = a[0]**2
for x in a[1:]:
sum_x += x
sum_x_squared += x**2
n += 1
# as noted by @Andrey Tyukin, statistics.stdev returns
# the unbiased estimator, hence the n/(n-1)
sd = sqrt(n/(n-1)*(sum_x_squared/n - (sum_x/n)**2))
sds.append(sd)
return sds
sds = sdevs(a)
print(sds[10000])
# 2887.184355042123
看起来您需要一个扩展的标准偏差,为此我将使用pandas库和pandas.Series.expanding方法:
如果需要,可以轻松地将第一个元素切片并转换为列表:
^{pr2}$虽然Series是一种比list更有用的数据类型,但肯定更具性能:
您可以跟踪值和平方值的总和:
在一台有10年历史的电脑上,这需要24毫秒
相关问题 更多 >
编程相关推荐