标准偏差计算错误

Standard Deviation calculation error

我想弄清楚为什么这个过程给我一个错误的答案。

对于 [1,2,3,4,5] 我得到 1.2 而不是 1.414

def standard_deviation(number_list):
  average = sum(number_list) / float(len(number_list))
  stdev = 0
  for value in number_list:
      stdev += math.sqrt((average - value)**2) / float(len(number_list))
  return stdev

standard_deviation([1,2,3,4,5])

您错误地实现了公式。

定义为"The standard deviation is the square root of the average of the squared deviations from the mean."This numpy page explains it well (see the Notes section).

代码math.sqrt((average - value)**2)不符合您的要求; sqrt 和 **2 相互抵消,所以结果只是 abs(average-value).

numpy 页面简洁地将实现描述为 std = sqrt(mean(abs(x - x.mean())**2))

对您的代码进行以下更正会更好:

def standard_deviation(number_list):
  average = sum(number_list) / float(len(number_list))
  sqdev = 0
  for value in number_list:
      sqdev += (average-value)**2
  sqdev = sqdev / float(len(number_list))
  return math.sqrt(sqdev)