Skip to content

Instantly share code, notes, and snippets.

@amergin
Created December 31, 2014 16:33
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 amergin/7635e3399446de0f05a8 to your computer and use it in GitHub Desktop.
Save amergin/7635e3399446de0f05a8 to your computer and use it in GitHub Desktop.
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