你好假设我有一组数字,我想快速计算一些均匀度。我知道方差是最明显的答案,但恐怕天真的算法的复杂性太高了有人有什么建议吗?
问问题
1464 次
1 回答
6
用于计算方差的“直观”算法通常会遇到以下一种或两种情况:
- 使用两个循环(一个用于计算平均值,另一个用于方差)
- 数值不稳定
一个好的算法,只有一个循环并且数值稳定是由于D. Knuth(一如既往)。
n = 0
mean = 0
M2 = 0
def calculate_online_variance(x):
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x - mean) # This expression uses the new value of mean
variance_n = M2/n
variance = M2/(n - 1) #note on the first pass with n=1 this will fail (should return Inf)
return variance
您应该为每个点调用 calculate_online_variance(x),它会返回到目前为止计算的方差。
于 2010-11-23T18:56:33.950 回答