Last active
June 10, 2016 08:48
-
-
Save gimdongwoo/d912aec6432e171340314a0b158f1e2b to your computer and use it in GitHub Desktop.
Standard Deviation & Standard Score @javascript
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
// https://gist.github.com/matthutchinson/1648603 | |
// http://jsfiddle.net/hiddenloop/TPeJt/ | |
var array = [2, 3, 4, 6, 2, 5, 7, 2, 4, 5]; | |
var within_std_of = 1; | |
outputResult = function(str) { | |
console.log(str); | |
} | |
average = function(a) { | |
var r = {mean: 0, variance: 0, deviation: 0}, t = a.length; | |
for(var m, s = 0, l = t; l--; s += a[l]); | |
for(m = r.mean = s / t, l = t, s = 0; l--; s += Math.pow(a[l] - m, 2)); | |
return r.deviation = Math.sqrt(r.variance = s / t), r; | |
} | |
withinStd = function(x, val, stdev) { | |
var low = x.mean-(stdev*x.deviation); | |
var hi = x.mean+(stdev*x.deviation); | |
return (val > low) && (val < hi); | |
} | |
stdScore = function(x, val) { | |
var z = (val-x.mean)/x.deviation; | |
return (z*10)+50; | |
} | |
outputResult("Set = [" + array.concat(',') + "]"); | |
var x = average(array); | |
outputResult( | |
"mean = " + x.mean + " / " + | |
"deviation = " + x.deviation + " / " + | |
"variance = " + x.variance + "" | |
); | |
for(i=0; i<array.length; i++) { | |
outputResult (array[i] + " / inside " + within_std_of + "std? " + withinStd(x, array[i],within_std_of) + " / stdScore = " + stdScore(x, array[i])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment