Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeking a statistical javascript function to return p-value from a z-score

I need to convert z-scores to percentile. I found reference to a function in the jStat library that I could use (jstat.ztest), but the jStat documentation seems to be ahead of the available library because there is no such function in the currently available version of the library.

I think there is a more recent version of the library on GitHub, which may include the ztest function, but I am a linux novice and could not figure out how to build the library from the instructions. I spent most of a day learning about git bash and cygwin trying to build the library; I finally decided I'd be better off asking here.

So, could anyone point me toward a javascript function that would do what I need? Alternatively, could anyone point me toward a built version of the jStat library with ztest function included?

like image 723
burgerB Avatar asked Apr 24 '13 14:04

burgerB


2 Answers

I found this in a forum online and it works like a charm.

function GetZPercent(z) 
  {
    //z == number of standard deviations from the mean

    //if z is greater than 6.5 standard deviations from the mean
    //the number of significant digits will be outside of a reasonable 
    //range
    if ( z < -6.5)
      return 0.0;
    if( z > 6.5) 
      return 1.0;

    var factK = 1;
    var sum = 0;
    var term = 1;
    var k = 0;
    var loopStop = Math.exp(-23);
    while(Math.abs(term) > loopStop) 
    {
      term = .3989422804 * Math.pow(-1,k) * Math.pow(z,k) / (2 * k + 1) / Math.pow(2,k) * Math.pow(z,k+1) / factK;
      sum += term;
      k++;
      factK *= k;

    }
    sum += 0.5;

    return sum;
  }

And I don't need to include a large library just for the one function.

like image 157
burgerB Avatar answered Oct 02 '22 12:10

burgerB


Just editing the code from Paul's answer for a two-sided t-test

function GetZPercent(z) 
{
//z == number of standard deviations from the mean

//if z is greater than 6.5 standard deviations from the mean
//the number of significant digits will be outside of a reasonable 
//range
if ( z < -6.5)
  return 0.0;
if( z > 6.5) 
  return 1.0;

if (z > 0) { z = -z;}

var factK = 1;
var sum = 0;
var term = 1;
var k = 0;
var loopStop = Math.exp(-23);
while(Math.abs(term) > loopStop) 
{
  term = .3989422804 * Math.pow(-1,k) * Math.pow(z,k) / (2 * k + 1) / Math.pow(2,k) * Math.pow(z,k+1) / factK;
  sum += term;
  k++;
  factK *= k;

}
sum += 0.5;

return (2*sum);
}
like image 27
Ravdeep Chawla Avatar answered Oct 02 '22 14:10

Ravdeep Chawla