猿问

在Python中计算均值和方差

当您输入一组数字时,我有这段代码来计算平均值和方差,但我的方差偏离了应有的值。我的方差公式是否以某种方式关闭,或者我的代码中可能存在一些错误?


我的输出:


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)


holdtom
浏览 105回答 2
2回答

DIEA

你的方差公式是错误的。你可以在这里找到公式以便更好地理解,我这里就不解释了。mean = 0variance = 0x = 0n = 0while 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: 1mean is  1.0 variance is  0Input a positive number: 2mean is  1.5 variance is  0.5Input a positive number: 3mean is  2.0 variance is  1.0Input a positive number: 4mean is  2.5 variance is  1.6666666666666665你给出了一个错误的测试用例,Input a positive number: 3mean is  2.0 variance is  0.1在这里,方差将1 not 0.1。您可以使用在线计算器轻松检查样本方差。

慕田峪9158850

您可以使用列表来存储所有输入。x = 0data = []&nbsp;while x >= 0:&nbsp; &nbsp; x = float(input('Input a positive number: '))&nbsp; # user input for code&nbsp; &nbsp; if x < 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break&nbsp; &nbsp; data.append(x)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; N = len(data)&nbsp; &nbsp; mean = sum(data) / N&nbsp; &nbsp; var = 0&nbsp; &nbsp; if N > 1:&nbsp; &nbsp; &nbsp; &nbsp; a = [x - mean for x in data]&nbsp; &nbsp; &nbsp; &nbsp; a = [x**2 for x in a]&nbsp; &nbsp; &nbsp; &nbsp; var = sum( a) / (N-1)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; print( "mean is ", mean, " variance is ", var)
随时随地看视频慕课网APP

相关分类

Python
我要回答