Created
August 2, 2011 11:03
-
-
Save mblondel/1120009 to your computer and use it in GitHub Desktop.
Sample variance in a single pass
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
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