Created
June 27, 2017 03:12
-
-
Save wware/b6cfd71018f847964856b3a224030d9b to your computer and use it in GitHub Desktop.
Generate mu, sigma for a stream of numbers, incrementally.
This file contains hidden or 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
import collections | |
class RunningAverage(object): | |
""" | |
>>> r = RunningAverage() | |
>>> r | |
<__main__.RunningAverage object at 0x...> | |
>>> r.update(1) | |
>>> r.update(2) | |
>>> r.update(3) | |
>>> r.stats() | |
(2.0, 0.816...) | |
>>> RunningAverage.q((1, 2, 3)) | |
(2.0, 0.816...) | |
>>> RunningAverage.q((1, 2, 3, 6, 10, 12)) | |
(5.666..., 4.109...) | |
""" | |
def __init__(self): | |
self._n = 0 | |
self._sumx = 0 | |
self._sumxsq = 0 | |
def update(self, x): | |
def update_one(x): | |
self._n += 1 | |
self._sumx += x | |
self._sumxsq += x * x | |
if isinstance(x, collections.Iterable): | |
[update_one(y) for y in x] | |
else: | |
update_one(x) | |
def stats(self): | |
mu = 1.0 * self._sumx / self._n | |
sigma = ((1.0 * self._sumxsq / self._n) - mu ** 2) ** 0.5 | |
return (mu, sigma) | |
@classmethod | |
def q(cls, lst): | |
R = RunningAverage() | |
R.update(lst) | |
return R.stats() | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod(optionflags=doctest.ELLIPSIS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment