Question

Trying to figure out how to get the standard deviation from a list. Ive looked up examples and for some reason i cannot get them to work. Total, Median, and mean do fine, its the standard deviation that is giving errors and not sure how to get it to print.

This is a code that I have created, yes I know it can be shortened. But its my first go around.

I currently get the following error

AttributeError: 'module' object has no attribute 'stdev'                

This is a code that I have created, yes I know it can be shortened. But its my first go around.

num1 = int(input("Insert first number"))
num2 = int(input("Insert Next number"))
num3 = int(input("Insert Next number"))
num4 = int(input("Insert Next number"))
num5 = int(input("Insert Next number"))
num6 = int(input("Insert Next number"))
num7 = int(input("Insert Next number"))
num8 = int(input("Insert Next number"))
num9 = int(input("Insert Next number"))
num10 = int(input("Insert Last number"))

x = ([num1, num2, num3, num4, num5, num6, num7, num8, num9, num10])

total = sum(x)
print (total)

mean = total / 10
print (mean)

median = sorted(x)[len(x)//2]
print (int(median))

import stat
stdeviation = stat.stdev(x)
print (stdeviation)
Was it helpful?

Solution

Sorry, module stat is related to the POSIX system call stat not statistics. Anyway standard deviation is the square root of the average squared difference from the mean. You can do that directly. Well, actually you want to compute the "sample" standard deviation which uses "Bessel's correction": not the average squared difference (dividing by the number of samples), but rather the squared difference divided by one less than the number of samples.

To put it briefly: sample standard deviation, which Python 3 calls statistics.stdev, is just this:

math.sqrt(sum([(val - mean)**2 for val in x])/(len(x) - 1))

OTHER TIPS

In Python 2 the numpy module offers the functionality to compute a standard deviation. If you have a list you can convert it to an array which offers the standard deviation as a member function:

import numpy
lst = [1, 4, 2, 5, 2, 2.5]
print numpy.array(lst).std()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top