Last active
August 29, 2015 14:04
-
-
Save kcha/506a5545873c405066d2 to your computer and use it in GitHub Desktop.
Python math and stats functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $Date: 2010-10-29 16:09:50 -0400 (Fri, 29 Oct 2010) $ | |
# Filename: stats.py | |
# | |
# A bunch of math/stats functions | |
import math | |
'''calculate average''' | |
def calcAvg(ls): | |
n, mean = len(ls), 0.0 | |
if n <= 1: | |
return ls[0] | |
# calculate average | |
for el in ls: | |
mean = mean + float(el) | |
mean = mean / float(n) | |
return mean | |
'''calculate standard deviation''' | |
def calcSD(ls): | |
n = len(ls) | |
if n <= 1: | |
return 0.0 | |
mean, sd = calcAvg(ls), 0.0 | |
# calculate stan. dev. | |
for el in ls: | |
sd += (float(el) - mean)**2 | |
sd = math.sqrt(sd / float(n-1)) | |
return sd | |
'''calculate both average and standard deviation''' | |
def calcAvgAndSD(ls): | |
return calcAvg(ls), calcSD(ls) | |
'''calculate the median''' | |
def median(ls): | |
ls = sorted(ls) | |
n = len(ls) | |
median = 0 | |
if n % 2 == 0: | |
median = (ls[(n/2)-1] + ls[n/2])/2.0 | |
else: | |
median = ls[((n+1)/2)-1] | |
return median | |
'''calculate the lower quartile - defined as median of the lower | |
half of the data. if ls has odd number of elements, the median is | |
not included in the calculation''' | |
def lowerQuartile(ls): | |
ls = sorted(ls) | |
n = len(ls) | |
return median(ls[0:(n/2)]) | |
'''same as lowerQuartile() but calculating the upper quartile''' | |
def upperQuartile(ls): | |
ls = sorted(ls) | |
n = len(ls) | |
return median(ls[((n+1)/2):]) | |
'''Determine whether a number is between two numbers x and y. Return True if | |
yes, False otherwise.''' | |
def isBetween(i, x, y): | |
return (i >= x and i <= y) | |
if __name__ == "__main__": | |
print isBetween(4.1,1,5) | |
ls = [4, 5, 6] | |
print calcAvg(ls) | |
print calcSD(ls) | |
print calcAvgAndSD(ls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment