3

你好假设我有一组数字,我想快速计算一些均匀度。我知道方差是最明显的答案,但恐怕天真的算法的复杂性太高了有人有什么建议吗?

4

1 回答 1

6

用于计算方差的“直观”算法通常会遇到以下一种或两种情况:

  1. 使用两个循环(一个用于计算平均值,另一个用于方差)
  2. 数值不稳定

一个好的算法,只有一个循环并且数值稳定是由于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 回答