user3221556
user3221556

Reputation: 11

My variance equation is giving me a crazy output in Python

The point of this program is to take a random list and find the mean and variance of that list without the use of functions. My variance equation is giving me an output that is off by a few decimal places.

    variance = (mean - r)**2.0 + variance

An example of the output I'm getting is 8784462.44 when it should be 87844.6244. I have no idea what is going wrong in my code.

Upvotes: 1

Views: 170

Answers (2)

Martin Dinov
Martin Dinov

Reputation: 8825

This line is not correct:

variance = (mean - r)**2.0 + variance

You say you are calculating the numerator of the variance, and then printing that same variance variable without dividing by the number of numbers you are summing through (100 in your case). To get the variance (assuming you are treating the numbers as a "population"), you want:

variance = ((mean - r)**2.0)/100

from the equation for the population variance:

enter image description here

That accounts for your decimal point being off by 2 places in your example.

Upvotes: 1

Robert Dodier
Robert Dodier

Reputation: 17576

Variance = (1/n) times (sum of (x - mean(x))^2) -- you have only the summation; you forgot to multiply by 1/n.

Sometimes variance is defined as (1/(n - 1)) times (sum ...) -- I don't know what definition you are working with.

Upvotes: 6

Related Questions