Created
February 24, 2010 00:07
-
-
Save anfedorov/312890 to your computer and use it in GitHub Desktop.
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
from __future__ import division | |
from collections import namedtuple | |
Stats = namedtuple('Stats', 'count min max average variance') | |
def statgenerator(initial=None): | |
l = u = None # lower and upper values seen | |
n = v = a = 0 # count, variance, average (arithmetic mean) | |
q = 0 # running sum (see wikipedia) | |
while 1: | |
#TODO: a better way to pass in initial iterators | |
x = initial.pop() if initial else (yield Stats(n,l,u,a,v)) | |
if (l is None) or (x < l): l = x | |
if (u is None) or (x > u): u = x | |
n += 1 | |
q = q + (n-1)*(x-a)*(x-a)/n | |
a = a + (x-a)/n | |
v = q/n | |
# For an explanation of the math, see: | |
# http://en.wikipedia.org/wiki/Stddev#Rapid_calculation_methods | |
s = statgenerator() | |
s.next() | |
print s.send(1) | |
print s.send(7) | |
print s.send(9) | |
print s.send(15) | |
print statgenerator([0,6,8,14]).next() | |
# Prints: | |
# Stats(count=1, min=1, max=1, average=1.0, variance=0.0) | |
# Stats(count=2, min=1, max=7, average=4.0, variance=9.0) | |
# Stats(count=3, min=1, max=9, average=5.666666666666667, variance=11.555555555555557) | |
# Stats(count=4, min=1, max=15, average=8.0, variance=24.999999999999996) | |
# | |
# Stats(count=4, min=0, max=14, average=7.0, variance=25.000000000000004) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment