使用 for 循环计算数组的方差,Python

Calculate variance of an array using for-loops, Python

我刚刚开始学习 Python,现在我必须使用 for 循环计算数组中的均值和方差。

目前,我得到一个不正确的方差值,我不确定为什么。

numbers = [7, 16, 0.3, 0, 15, -4, 5, 3, 15]

sum = 0

for value in range(0, len(numbers)):
    sum = sum + numbers[value]
    mean_value = sum / len(numbers)

print(mean_value)

n = len(numbers)
sum_squares = 0
for value in range(0, len(numbers)):
    sum_squares = sum_squares + (value - mean_value) ** 2
    var_value = sum_squares / n

print(var_value)

根据在线计算器,我应该得到方差 = 55.035,而我得到的方差为 12.267

如有任何帮助,我将不胜感激。

K

编辑: 我刚刚意识到将第二部分更改为此有效:

for value in numbers:
    sum_squares = sum_squares + ((value - mean_value) ** 2)
    var_value = sum_squares / n

不确定“for value in numbers:”和“for value in range(0, len(numbers)):”之间的确切区别是什么,但这就是帮助。

方差除以 (n-1)

numbers = [7, 16, 0.3, 0, 15, -4, 5, 3, 15]
sum = 0
count = 0
sum_squares = 0

for value in numbers:
  sum = sum + value
  count = count + 1
  
mean_value = (sum / count)

for value in numbers:
    sum_squares = sum_squares + ((value - mean_value)** 2)
    var_value = sum_squares / (count-1)

print (mean_value)
print (var_value)

输出:
6.366666666666666
55.035