The new function factory looks a lot like the class based version of my previous post, and performs similarly.
def make_standard_deviator2():
'''Generate functions that return running standard deviations
Uses function attributes applied by decorator
'''
def setup(func):
func.N, func.X, func.X2 = [0.0]*3
return func
@setup
def sd(x):
'''returns standard deviation.
Uses function attributes holding running sums
'''
from math import sqrt
sd.N += 1 # Num values
sd.X += x # sum values
sd.X2 += x**2 # sum squares
if sd.N<2: return 0.0
return sqrt((sd.N*sd.X2 - sd.X**2)
/(sd.N*(sd.N-1)))
return sd
No comments:
Post a Comment