Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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