Skip to content

Instantly share code, notes, and snippets.

@benjamn
Created May 19, 2009 20:59
Show Gist options
  • Save benjamn/114399 to your computer and use it in GitHub Desktop.
Save benjamn/114399 to your computer and use it in GitHub Desktop.
def mean(*xs):
return sum(xs) / float(len(xs))
def naive(*xs):
m = mean(*xs)
return sum((x-m)**2 for x in xs) / float(len(xs))
def update(x, prior):
s, n, m = prior
m_ = float(m*n + x) / (n + 1)
s_ = s + n * abs(m_-m)**2
return (s_ + (x - m_)**2, # new sum
n + 1, # new count
m_) # new mean
def running(*xs):
if len(xs) <= 1:
return (naive(*xs),
len(xs),
mean(*xs))
return update(xs[0], running(*xs[1:]))
def var(*xs):
return running(*xs)[0] / len(xs)
def std(*xs):
return sqrt(var(*xs))
if __name__ == "__main__":
from sys import argv
xs = [float(n) for n in argv[1:]]
print "naive:", naive(*xs)
print "running:", var(*xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment