Skip to content

Instantly share code, notes, and snippets.

@gmaclennan
Last active March 2, 2018 13:17
Show Gist options
  • Save gmaclennan/a07c09f48592371ae251039bd96fced7 to your computer and use it in GitHub Desktop.
Save gmaclennan/a07c09f48592371ae251039bd96fced7 to your computer and use it in GitHub Desktop.
Running variance Welford method
// See http://www.johndcook.com/blog/standard_deviation/
function varianceReduce (p, x, i) {
p.mean = isNaN(p.mean) ? 0 : p.mean
var mean = p.mean + (x - p.mean) / (i + 1)
var vari = i < 1 ? 0 : (p.vari * i + (x - p.mean) * (x - mean)) / (i + 1)
return {
mean: mean,
vari: vari
}
}
[ 2, 4, 5, 3, 8, 2 ].reduce(varianceReduce, {mean: NaN, vari: NaN}).vari
// 4.3333333333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment