Skip to content

Instantly share code, notes, and snippets.

@jmelesky
Forked from schmichael/runningavg.py
Created October 20, 2011 04:25
Show Gist options
  • Save jmelesky/1300412 to your computer and use it in GitHub Desktop.
Save jmelesky/1300412 to your computer and use it in GitHub Desktop.
Handy script for calculating averages streamed via stdin
#!/usr/bin/env python
import sys
import math
CHUNK = 100
if len(sys.argv) > 1:
CHUNK = int(sys.argv[1])
s = 0
ss = 0
n = 0
i = 1
while 1:
l = sys.stdin.readline()
if not l:
break
num = float(l.strip())
s += num
ss += (num * num)
n += 1
if i % CHUNK == 0:
m = s / n
print "Count: %10d - Total: %10.4f - Average: %10.4f - Std Dev: %10.4f" % (
n, s, m, math.sqrt((ss / n) - (m * m)) )
i += 1
m = s / n
print "Count: %10d - Total: %10.4f - Average: %10.4f - Std Dev: %10.4f" % (
n, s, m, math.sqrt((ss / n) - (m * m)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment