Skip to content

Instantly share code, notes, and snippets.

@stober
Created July 13, 2012 22:00
Show Gist options
  • Save stober/3107828 to your computer and use it in GitHub Desktop.
Save stober/3107828 to your computer and use it in GitHub Desktop.
A generator for incremental averaging in Python
def consumer(func):
"""
See: http://www.dabeaz.com/generators/
"""
def start(*args,**kwargs):
c = func(*args,**kwargs)
c.next()
return c
return start
@consumer
def incavg(val = None):
"""
Can optionally send the first value at initialization.
"""
cnt = 0
avg = 0
if not val is None:
cnt = 1
avg = val
while True:
val = (yield avg)
if val is None:
pass # next was called
elif cnt == 0: # first value
cnt = 1
avg = val
else:
cnt += 1
avg = avg + (val - avg) / float(cnt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment