Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created October 19, 2011 07:50
Show Gist options
  • Select an option

  • Save clauswitt/1297704 to your computer and use it in GitHub Desktop.

Select an option

Save clauswitt/1297704 to your computer and use it in GitHub Desktop.
Even simpler statistics
function SimpleStats(optionalInputArray) {
var self = this;
var setSize = 0,
arithmeticMean = 0,
standardDeviation = 0,
pwrSumAvg = 0;
//http://en.wikipedia.org/wiki/Mean#Arithmetic_mean_.28AM.29
var setArithmeticMean = function(x) {
arithmeticMean += (x - arithmeticMean) / setSize;
}
//http://en.wikipedia.org/wiki/Standard_deviation
var setStandardDeviation = function(x) {
pwrSumAvg += ( x * x - pwrSumAvg) / setSize;
standardDeviation = Math.pow( (pwrSumAvg * setSize - arithmeticMean * arithmeticMean * setSize) / setSize, 0.5 );
}
self.addValues = function(arr) {
var arrLength = arr.length;
for(var i=0;i<arrLength;i++) {
self.addValue(arr[i]);
}
return self;
}
self.addValue = function(x) {
setSize += 1;
setArithmeticMean(x);
setStandardDeviation(x);
return self;
}
self.getArithmeticMean = function() {
return arithmeticMean;
}
self.getStandardDeviation = function() {
return standardDeviation;
}
if(typeof optionalInputArray != 'undefined') {
self.addValues(optionalInputArray);
}
return self;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment