Related Ads Link

How to do Standard Deviation in Python Easily

How to do Standard Deviation in Python Easily

Hello, Programmers, Welcome to Codinglio. Today we are gonna talk about How to do Standard Deviation in Python Easily. Probably a script can be useful for you. I will provide a script for this, that will surely help you do that.

How to do Standard Deviation in Python Easily

Here is a really quick Script for doing standard Deviation in Python. If you can improve it, comment down your suggestions.

from math import sqrt

def standard_deviation(lst, population=True):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)

# Note: it would be better to return a value and then print it outside
# the function, but this is just a quick way to print out the values along
# the way.
if population is True:
print('This is POPULATION standard deviation.')
variance = ssd / num_items
else:
print('This is SAMPLE standard deviation.')
variance = ssd / (num_items - 1)
sd = sqrt(variance)
# You could `return sd` here.

print('The mean of {} is {}.'.format(lst, mean))
print('The differences are {}.'.format(differences))
print('The sum of squared differences is {}.'.format(ssd))
print('The variance is {}.'.format(variance))
print('The standard deviation is {}.'.format(sd))
print('--------------------------')

s = [98, 127, 133, 147, 170, 197, 201, 211, 255]
standard_deviation(s)
standard_deviation(s, population=False)

And here is the output:

This is POPULATION standard deviation.
The mean of [98, 127, 133, 147, 170, 197, 201, 211, 255] is 171.0.
The differences are [-73.0, -44.0, -38.0, -24.0, -1.0, 26.0, 30.0, 40.0, 84.0].
The sum of squared differences is 19518.0.
The variance is 2168.6666666666665.
The standard deviation is 46.56894530335282.

This is SAMPLE standard deviation.
The mean of [98, 127, 133, 147, 170, 197, 201, 211, 255] is 171.0.
The differences are [-73.0, -44.0, -38.0, -24.0, -1.0, 26.0, 30.0, 40.0, 84.0].
The sum of squared differences is 19518.0.
The variance is 2439.75.
The standard deviation is 49.393825525059306.

if you found these somehow useful, share it by clicking the buttons below or check the related posts in the blog. You can also join our free Programmers community to solve others problem regarding Programming. We appreciate your visit. We love solving your problems.Thanks for being here cheers.!!



A Programmer by Passion and a Passionate Blogger by Heart <3 . CodingLio was my Dream Idea, I wanted To Create a Medium where, Geeks can actually Learn Something.


Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: