Created
July 13, 2012 22:00
-
-
Save stober/3107828 to your computer and use it in GitHub Desktop.
A generator for incremental averaging in Python
This file contains 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
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