Skip to content

Instantly share code, notes, and snippets.

@tef
Created November 11, 2013 11:18
Show Gist options
  • Save tef/7411714 to your computer and use it in GitHub Desktop.
Save tef/7411714 to your computer and use it in GitHub Desktop.
# based upon http://www.johndcook.com/standard%5Fdeviation.html
from collections import OrderedDict
class RunningStat(object):
def __init__(self):
self.n = 0
self.m = None
self.s = None
self.min = None
self.max = None
def clear(self):
self.n = 0
self.m = None
self.s = None
self.min = None
self.max = None
def push(self, x):
x = float(x)
self.n += 1
if self.n == 1:
self.min = self.max = self.m = x
self.s = 0.0
else:
self.min = min(self.min, x)
self.max = max(self.max, x)
m = self.m
self.m = m + (x - m)/self.n
self.s = self.s + (x - m)*(x - self.m)
@property
def mean(self):
return self.m if self.n > 0 else 0.0
@property
def variance(self):
return self.s/(self.n-1) if self.n > 1 else 0.0
@property
def stddev(self):
return self.variance ** 0.5
@property
def stats(self):
if self.n > 0:
return OrderedDict(count=self.n, min=self.min, max=self.max, mean=self.mean, stddev=self.stddev)
else:
return OrderedDict()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment