Pythonic way to calculate Standard Deviation

If you are familiar with  basic statistics, I think you know what is Standard Deviation, if you dont know what is Standard Deviation you can check wiki for details.

And if it seems yet hard to wrap the idea into your brain,check this thread. Hope you understand it now. Standard deviation is an efficient when you want to understand a set of data and widely used in different industries. I was working with an algorithm couple of months ago where I had to calculated standard deviation of  a series of data. And the sets of data is large.

After coding couple of versions I code a small python class which calculates standard deviation of data. Check it out

from __future__ import division
from math import sqrt, pow
class StandardDeviation(object):
def do_round(self, data):
data = "%.3f" % round(data, 3)
return float(data)
def do_diff(self, n, mean):
return pow((nmean), 2)
def standDev(self, data_list):
mean = sum(data_list)/len(data_list)
result = sqrt(sum([self.do_diff(s, mean) for s in \
data_list] )/len(data_list))
return float(self.do_round(result))
if __name__=='__main__':
data_list = [2, 4, 4, 4, 5, 5, 7, 9 ]
std = StandardDeviation()
print std.standDev(data_list)

Happy Coding!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.