In Variance, how does my FLOAT become an INT?


def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += ((average - score) ** 2)
    result = variance // float(len(scores))
    return result

Gives me the following error:

Oops, try again. gradesvariance([2, 6, 8]) returned 6.0 instead of the expected: 6.2222222222

So my guess is that my variable "result" is being stored as an integer and losing part of it's identity in the process...

How do I fix this?


This is floor division. The result is an integer written as a float if the numerator is a float.

>>> 12.5 // 3

Use normal division instead, expecting variance to be a float already.

 variance / len(scores)

This is the place to declare the float. It will exist throughout the remaining functions. Keeping things as simple as possible...

def grades_average(grades):
    return float(grades_sum(grades)) / len(grades)

It may be just me but I find converting a counting number to a float to be misleading. A natural number should be left as is. That's why the float is applied to the numerator. It reads more accurately in terms of semantics. A minor detail in the grand scheme...


Actually, since you have grades_sum(), that would be the place to set the float.

def grades_sum(grades):
    total = float(0)
    for grade in grades:
        total += grade
    return total


in this case ... i think so its not necessary make total with the float because the sum in total is already going to be a float

def grades_sum(grades):
    #total = float(0)  << i think
    total = 0
    for i in grades:
        total += i
    return total


In this case, only because the data set contains one float (50.5), so it results in a float. Make that number an integer and the result will be an integer. We should shy away from implicitly defining data types. Explicit declaration comes with no mystery or surprises.

In the above, grades_sum() returns a float which carries through all the other calculations in the program.


thinking about this you have reason... rs


I Found it,

I had t change my code from:

result = variance // float(len(scores))


result = variance / len(scores)

Now the output is a FLOAT as expected.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.