Created
January 14, 2019 14:54
-
-
Save talesa/a6539f56c4d36ce4d66bae3c2c60a270 to your computer and use it in GitHub Desktop.
online mean & variance estimators
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
class OnlineStats: | |
# https://www.johndcook.com/blog/standard_deviation/ | |
# Knuth TAOCP vol 2, 3rd edition, page 232 | |
def __init__(self): | |
self.n = 0 | |
def push(self, x): | |
self.n += 1 | |
if self.n == 1: | |
self.oldM = x | |
self.newM = x | |
self.oldS = 0. | |
else: | |
self.newM = self.oldM + (x - self.oldM) / self.n | |
self.newS = self.oldS + (x - self.oldM) * (x - self.newM) | |
self.oldM = self.newM | |
self.oldS = self.newS | |
def mean(self): | |
return self.newM if self.n > 0 else 0. | |
def variance(self): | |
return self.newS/(self.n - 1) if self.n > 1 else 0. | |
def std(self): | |
return self.variance().sqrt_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment