Average, variance & standard deviation in Python

Here is a quick python script which calculates average, variance and standard deviation. This is also part of codeacademy work. I must say last time I worked with variance and standard deviation it was more than 10 years ago in statistics course. Hence a bit of reminder here for me too: (Some are from wikipedia and mathsisfun.com)

Average: In mathematics and statistics, it is called arithmetic mean according to wikipedia but simply it is the sum of a list of numbers divided by the number of numbers in the list.

Variance: The average of the squared differences from the mean. Here is the formula which we will use in our python code.

\displaystyle \sigma^2 = \frac{\displaystyle\sum_{i=1}^{n}(x_i - \mu)^2} {n}

Standard deviation: Square root of the variance is the standard deviation which just means how far we are from the normal(mean)

\displaystyle  \sigma = \sqrt{\frac{\displaystyle\sum_{i=1}^{n}(x_i - \mu)^2} {n}}

Now here is the code which calculates given the number of scores of students we calculate the average,variance and standard deviation.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

#First print the grades
def print_grades(grades):
    for grade in grades:
        print grade

#calculate the sum
def grades_sum(grades):
    total = 0
    for grade in grades: 
        total += grade
    return total

#Take the average by adding up each grade    
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average

#Here we calculate the variance given the formula above 
#by subtracting each score from the average and then taking square and rolling the sum. 
def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance = variance + (average - score) ** 2
    
    return variance/len(scores)

print grades_variance(grades)

#And here the standard deviation comes by taking square root of the variance
def grades_std_deviation(variance):
    return variance ** 0.5
variance = grades_variance(grades)
    
print grades_std_deviation(variance)

See:
http://www.mathsisfun.com/data/standard-deviation.html

About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN // JNCIE-SEC #223 / RHCE / PCNSE


One thought on “Average, variance & standard deviation in Python”

You have a feedback?

Discover more from RtoDto.net

Subscribe now to keep reading and get access to the full archive.

Continue reading