Skip to content

Instantly share code, notes, and snippets.

@mblondel
Created August 2, 2011 11:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mblondel/1120009 to your computer and use it in GitHub Desktop.
Save mblondel/1120009 to your computer and use it in GitHub Desktop.
Sample variance in a single pass
def online_mean_variance(iterable):
mN = 0
mM = 0.0
mS = 0.0
for x in iterable:
mN += 1
nextM = mM + (x - mM) / mN
mS += (x - mM) * (x - nextM)
mM = nextM
mean = mM
var = mS / (mN - 1) if mN > 1 else 0.0
return mean, var
if __name__ == '__main__':
import numpy as np
data = np.random.random(1000)
print (np.mean(data), np.var(data))
print online_mean_variance(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment