본문 바로가기
파이썬

파이썬에서 평균과 분산 계산

by º기록 2020. 9. 13.
반응형

일련의 숫자를 입력 할 때 평균과 분산을 계산하는이 코드가 있지만 내 분산이 있어야하는 것과 다릅니다. 내 분산 공식이 어떻게 든 꺼져 있습니까? 아니면 내 코드에 오류가 있습니까?

내 출력 :

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)

 

해결 방법

 


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


 

참조 페이지 https://stackoverflow.com/questions/63758621

 

 

반응형

댓글