Created
December 31, 2014 16:33
-
-
Save amergin/7635e3399446de0f05a8 to your computer and use it in GitHub Desktop.
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
this.getReducedSTD2 = function(dimensionGroup, variable) { | |
// see https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance | |
var reduceAdd = function (p, v) { | |
var value = +v.variables[variable]; | |
if( _.isNaN(value) ) { | |
//pass | |
} | |
else { | |
if( p.n === 0 ) { | |
p.k = value; | |
} | |
p.n = p.n + 1; | |
p.ex = p.ex + (value-p.k); | |
p.ex2 = p.ex2 + (value-p.k) * (value-p.k); | |
} | |
return p; | |
}; | |
var reduceRemove = function (p, v) { | |
var value = +v.variables[variable]; | |
if( _.isNaN(value) ) { | |
//pass | |
} else { | |
p.n = p.n - 1; | |
p.ex = p.ex - (value-p.k); | |
p.ex2 = p.ex2 - (value-p.k) * (value-p.k); | |
} | |
return p; | |
}; | |
var reduceInitial = function () { | |
var p = { | |
k: 0, | |
n: 0, | |
ex: 0, | |
ex2: 0, | |
valueOf: function() { | |
var variance = (p.ex2 - (p.ex * p.ex)/p.n) / (p.n-1); | |
var mean = p.k + p.ex / p.n; | |
return { | |
variance: variance, | |
stddev: Math.sqrt(variance), | |
mean: mean | |
}; | |
} | |
}; | |
return p; | |
}; | |
return dimensionGroup.reduce(reduceAdd, reduceRemove, reduceInitial); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment