简体   繁体   中英

Calculating variance in python

I have this code to calculate mean and variance as you input a set of numbers, but my variance is off from what it should be. Is my variance formula off somehow or is it possibly some error in my code?

My output:

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

Correct output:

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  0.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)

If you're comfortable using a standard library function, Python 3.4+ has one . It also does validations required for variance calculations over the number list.

from statistics import variance

sample1 = (1, 2, 5, 4, 8, 9, 12) 
print(variance(sample1))

Output: 15.80952380952381

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM