2 回答
TA贡献1820条经验 获得超2个赞
你的方差公式是错误的。你可以在这里找到公式以便更好地理解,我这里就不解释了。
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) + (((x-mean)*(x-pre_mean))/(n-1)) # formula for calculating variance
print('mean is ', mean, 'variance is ', variance)
pre_mean = mean
输出:
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.0
Input a positive number: 4
mean is 2.5 variance is 1.6666666666666665
你给出了一个错误的测试用例,
Input a positive number: 3
mean is 2.0 variance is 0.1
在这里,方差将1 not 0.1。您可以使用在线计算器轻松检查样本方差。
TA贡献1794条经验 获得超7个赞
您可以使用列表来存储所有输入。
x = 0
data = []
while x >= 0:
x = float(input('Input a positive number: ')) # user input for code
if x < 0:
break
data.append(x)
N = len(data)
mean = sum(data) / N
var = 0
if N > 1:
a = [x - mean for x in data]
a = [x**2 for x in a]
var = sum( a) / (N-1)
print( "mean is ", mean, " variance is ", var)
添加回答
举报