Skip to content

Instantly share code, notes, and snippets.

@lakemove
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lakemove/9929800 to your computer and use it in GitHub Desktop.
Save lakemove/9929800 to your computer and use it in GitHub Desktop.
calculate mean and variance in a single iteration
// http://en.wikipedia.org/wiki/Variance
// http://upload.wikimedia.org/math/a/3/3/a336557f138eb90bafc9e6ebc00e926d.png
var data = [{x: 1, p: 0.1}, {x: 2, p: 0.3}, {x: 8, p: 0.6}]; //{x:probability}
var mu = 0, sigma = 0;
for (i in data) {
mu += i.p * i.x;
sigma += i.p * i.x * i.x;
}
console.log("mu = " + mu + ", sigma = " + sigma);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment