1

我必须使用列表的循环计算标准偏差。这就是我所拥有的:

elif user_option == 2:
  stdev= 0
  average = 0
  for val in scores_list:
    diffsquared= (val - average)**2
    sum_diffsquared= diffsquared + val
    stdev= ((sum_diffsquared)/num_scores)**(1/2)
    print(stdev)

我一直打错号码。

4

1 回答 1

2

您的代码中有几个问题。首先,“sum_diffsquared”是在循环之外计算的。其次,您将平均值声明为 0。您需要先计算平均值。

import numpy
import scipy

stddev = 0
average = 0
scores = [0,1,2,3,4]
average = numpy.mean(scores) #or calculate it yourself
diffsquared = 0
sum_diffsquared = 0
for val in scores:
  diffsquared = (val-average)**2
  sum_diffsquared = diffsquared + sum_diffsquared
stddev = ((sum_diffsquared)/len(scores))**(1/2) # corrected
print(stddev)
print(numpy.sqrt(numpy.var(scores)))

输出是:

1.41421356237
1.41421356237

表明现在计算是正确的。

于 2013-09-29T20:09:57.610 回答