当您输入一组数字时,我有这段代码来计算平均值和方差,但我的方差偏离了应有的值。我的方差公式是否以某种方式关闭,或者我的代码中可能存在一些错误?
我的输出:
Input a positive number: 1
mean is 1.0 variance is 0
Input a positive number: 2
mean is 1.5 variance is 0.125
Input a positive number: 3
mean is 2.0 variance is 0.3958333333333333
正确输出:
Input a positive number: 1
mean is 1.0 variance is 0
Input a positive number: 2
mean is 1.5 variance is 0.5
Input a positive number: 3
mean is 2.0 variance is 1
mean = 0
variance = 0
x = 0
n = 0
while x >= 0:
x = float(input('Input a positive number: ')) # user input for code
n += 1
if x < 0:
break
if n == 1: # Added this if statement to avoid dividing by 0
mean = x
print('mean is ', mean, 'variance is ', variance)
else:
mean = mean + ((x-mean)/n) # formula for calculating mean
variance = (((n-2)/(n-1)) * variance) + (((mean-x)**2)/n) # formula for calculating variance
print('mean is ', mean, 'variance is ', variance)
DIEA
慕田峪9158850
相关分类