Created
February 3, 2014 01:47
-
-
Save MarcoPolo/8777796 to your computer and use it in GitHub Desktop.
Simple Javascript Statistics
This file contains 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
// | |
// +-------------------------------------------------+ | |
// | Statistics.js!! | | |
// |-------------------------------------------------| | |
// | error fn -> a pretty good approximator | | |
// | cdf to find the percentile from zScore | | |
// | p value calculator | | |
// | | | |
// +-------------------------------------------------+ | |
// | |
function Stat(){} | |
Stat.prototype.cdf = function (zScore){ | |
if ( zScore == 0 ) { | |
return 0; | |
} | |
return (1/2)*(1+this.erf(zScore/(Math.sqrt(2)))); | |
} | |
Stat.prototype.erf = function (x){ | |
//This is an approximation to the error function | |
var a=((8*(Math.PI-3))/(3*Math.PI*(4-Math.PI))); | |
var t=Math.sqrt(1-Math.exp(-x*x*(4/Math.PI + a*x*x)/(1+a*x*x))); | |
var sign = Math.abs(x)/x | |
return t*sign; | |
} | |
Stat.prototype.pCalc = function (t, df) { | |
t=Math.abs(t); | |
var arctan = Math.atan(t/Math.sqrt(df)); | |
//Lets approximate it by using the special cases | |
if ( df == 1 ) { | |
return (1-(arctan)/(Math.PI/2)); | |
} | |
var sinTheta = Math.sin(arctan); | |
var cosTheta = Math.cos(arctan); | |
if ( df%2 == 1) { | |
// if the number is odd | |
return 1 - (arctan + sinTheta*cosTheta*this.pEstimate(cosTheta*cosTheta,2,df-3))/(Math.PI/2); | |
}else{ // it is even | |
return 1 - sinTheta*this.pEstimate(cosTheta*cosTheta, 1, df-3) | |
} | |
} | |
Stat.prototype.pEstimate = function (a, start, end) { | |
var multFactor=1; | |
var sum=1; | |
while (start<=end) { | |
multFactor*=a*start/(start+1); | |
sum+=multFactor; | |
start+=2 | |
} | |
return sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment