-
-
Save arthur-e/7220571 to your computer and use it in GitHub Desktop.
A JavaScript function ("class") that returns an object which can be used to calculate statistics on the the passed numeric Array.
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
/** | |
Returns an object which can be used to calculate statistics on the | |
the passed numeric Array. | |
*/ | |
var Stats = function (arr) { | |
arr = arr || []; | |
// http://en.wikipedia.org/wiki/Mean#Arithmetic_mean_.28AM.29 | |
this.arithmeticMean = function () { | |
var i, sum = 0; | |
for (i = 0; i < arr.length; i += 1) { | |
sum += arr[i]; | |
} | |
return sum / arr.length; | |
}; | |
this.mean = this.arithmeticMean; | |
// http://en.wikipedia.org/wiki/Mean#Geometric_mean_.28GM.29 | |
this.geometricMean = function () { | |
var i, product = 1; | |
for (i = 0; i < arr.length; i += 1) { | |
product = product * arr[i]; | |
} | |
return Math.pow(product, (1 / arr.length)); | |
}; | |
// http://en.wikipedia.org/wiki/Mean#Harmonic_mean_.28HM.29 | |
this.harmonicMean = function () { | |
var i, sum = 0; | |
for (i = 0; i < arr.length; i += 1) { | |
sum += (1 / arr[i]); | |
} | |
return arr.length / sum; | |
}; | |
// http://en.wikipedia.org/wiki/Standard_deviation | |
this.stdDev = function () { | |
var mean, i, sum = 0; | |
mean = this.arithmeticMean(); | |
for (i = 0; i < arr.length; i += 1) { | |
sum += Math.pow(arr[i] - mean, 2); | |
} | |
return Math.pow(sum / arr.length, 0.5); | |
}; | |
// http://en.wikipedia.org/wiki/Median | |
this.median = function () { | |
var middleValueId = Math.floor(arr.length / 2); | |
return arr.slice().sort(function (a, b) { | |
return a - b; | |
})[middleValueId]; | |
}; | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment