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

前端 未结 3 1340
日久生厌
日久生厌 2020-12-06 11:38

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

相关标签:
3条回答
  • 2020-12-06 12:21

    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.

    0 讨论(0)
  • 2020-12-06 12:29

    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);
    }
    
    0 讨论(0)
  • 2020-12-06 12:29

    This seems like such a simple ask but I had a hard time tracking down a library that does this instead of copying some random code snippet. Best I can tell this will calculate z-score from a percentage using the simple-statistics library.

    I took their documentation about cumulativestdnormalprobability and backed into the following algorithm. Feels like there should be an easier way but who knows.

    https://simplestatistics.org/docs/#cumulativestdnormalprobability

    const z_score = inverseErrorFunction((percentile_value - 0.5) / 0.5) * Math.sqrt(2);
    
    0 讨论(0)
提交回复
热议问题