Created
October 19, 2011 07:50
-
-
Save clauswitt/1297704 to your computer and use it in GitHub Desktop.
Even simpler statistics
This file contains hidden or 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
| 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