Variance


#1



Hi, the result of my function is always a little bit off (less than 1)

I would appreciate some help


def grades_sum(scores):
    total = 0
    for score in scores: 
        total += score
    return total
    
def grades_average(scores):
    sum_of_grades = grades_sum(scores)
    average = sum_of_grades / len(scores)
    return average

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

print(grades_variance(grades))


#2

Hi, @luluwutz ,

When something such as this occurs, you should check your functions individually to determine whether one or more of them computes a result that is a little off. For example, you can pass some small example lists of numbers to your grades_average function, and print the results.

a_list = [1, 4, 2, 3] 
print(grades_average(a_list))

Output ...

2

Oops, it should be 2.5.

What happened there? It appears that we received back an int that is the result of truncating the float that should have been returned.


#3

Ah i see. Thank you!

Changing the second line in grades_average() function into the following made the code working.

average = sum_of_grades / float(len(scores))

#4

Yes, that works. At the risk of being picky, I would opt for this instead, because technically the denominator for computing an average is an int, representing a count ...

average = float(sum_of_grades) / len(scores)

#5

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