Skip to content

Instantly share code, notes, and snippets.

@talesa
Created January 14, 2019 14:54
Show Gist options
  • Save talesa/a6539f56c4d36ce4d66bae3c2c60a270 to your computer and use it in GitHub Desktop.
Save talesa/a6539f56c4d36ce4d66bae3c2c60a270 to your computer and use it in GitHub Desktop.
online mean & variance estimators
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