Last active
March 2, 2018 13:17
-
-
Save gmaclennan/a07c09f48592371ae251039bd96fced7 to your computer and use it in GitHub Desktop.
Running variance Welford method
This file contains 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
// 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