A program that demonstrates calculating the (sample) standard deviation of a list of numbers in #python. Standard deviation measures the amount of deviation in a set of numbers (the spready-out-iness of the numbers, to coin a phrase). If you want to find the standard deviation of the whole population, remove the '-1' highlighted in red.
# Finds the mean, sum of squares and standard deviation for a list of numbers
# T Street
# 2015-10-20
def mean( alist ):
""" Returns the mean of a list of numbers """
total = 0
for i in alist:
total += i
return (total / len(alist))
def sumSquares( alist, mymean ):
""" Returns the variance of a list of numbers """
sumSquares = 0
for i in alist:
sumSquares += ( (i - mymean)**2 )
return sumSquares
def standardDeviation( alist ):
""" Returns the standard deviation of a list of numbers """
return (sumSquares(alist, mean(alist)) / (len(alist)-1))**0.5
# Test program
numbers = [ 5, 3, 5, 23, 8, 6, 7, 6 ]
print("Standard deviation\t",( standardDeviation( numbers ) ) )
print("Mean\t\t\t",( mean( numbers ) ) )
print("sum Squares\t\t",( sumSquares( numbers, mean(numbers) ) ) )
Subscribe to:
Post Comments (Atom)