From d649a2b1147b4141b84ef831182c0d5dcadac15b Mon Sep 17 00:00:00 2001 From: stephen mcquay Date: Thu, 25 Jun 2015 16:35:19 -0700 Subject: [PATCH] init --- ostat/__init__.py | 1 + ostat/ostat.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++ setup.py | 16 ++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 ostat/__init__.py create mode 100644 ostat/ostat.py create mode 100644 setup.py diff --git a/ostat/__init__.py b/ostat/__init__.py new file mode 100644 index 0000000..73befc9 --- /dev/null +++ b/ostat/__init__.py @@ -0,0 +1 @@ +from .ostat import OnlineStat diff --git a/ostat/ostat.py b/ostat/ostat.py new file mode 100644 index 0000000..de07305 --- /dev/null +++ b/ostat/ostat.py @@ -0,0 +1,55 @@ +import math + + +class OnlineStat(object): + def __init__(self): + self.n = 0.0 + + self.min = float('inf') + self.max = float('-inf') + + self.old_m = 0.0 + self.old_s = 0.0 + + self.new_m = 0.0 + self.new_s = 0.0 + + def push(self, x): + self.n += 1 + + if x < self.min: + self.min = x + if x > self.max: + self.max = x + + self.new_m = self.old_m + (x - self.old_m) / self.n + self.new_s = self.old_s + (x - self.old_m) * (x - self.new_m) + + self.old_m = self.new_m + self.old_s = self.new_s + + @property + def mean(self): + return self.new_m if self.n > 0 else 0.0 + + @property + def variance(self): + return self.new_s / (self.n) if self.n > 1 else 0.0 + + @property + def stddev(self): + return math.sqrt(self.variance) + + def __unicode__(self): + return u'{min} {mean} {max} {stddev}'.format( + min=self.min, + mean=self.mean, + max=self.max, + stddev=self.stddev, + ) + + def __str__(self): + return u'{}'.format(self).encode('utf8') + + def __repr__(self): + return u''.format(self) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..da21249 --- /dev/null +++ b/setup.py @@ -0,0 +1,16 @@ +from setuptools import setup + +setup( + name='ostat', + version='0.1', + description=( + 'efficient, accurate, and stable calculation of online ' + 'statistical quantities.' + ), + url='https://s.mcquay.me/sm/py-ostat/', + author='Stephen McQuay', + author_email='stephen@mcquay.me', + license='MIT', + packages=['ostat'], + zip_safe=False, +)