Search code examples
javascriptprobability

How do I convert probability into z-score


Javascript>

If you are in the data science industry, you would be bothered if you don't have normal distribution table. I came across the article in Stackoverflow that converts z-score to probability in JavaScript. What I really want to know is the reverse calculation of this function.

/**
 * @param {number} z - Number of standard deviations from the mean.
 */
function GetZPercent(z) {
   // 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 = 0.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;
 }

I have a sense of how to convert z-score into the probability. But, I have no idea how to calculate the z-score(Standard deviation) from corresponding probability in javascript. For example, If I put in 0.95 (or 95%), I can expect to get 2.25 standard deviation. Above code gives me 95%, if I enter 2.25.


Solution

  • Here is a function that does an opposite calculation (probability to z-score). This snippet allows you to input the probability and the the corresponding z-score is displayed:

    function percentile_z(p) {
        if (p < 0.5) return -percentile_z(1-p);
    
        if (p > 0.92) {
            if (p == 1) return Infinity;
            let r = Math.sqrt(-Math.log(1-p));
            return (((2.3212128*r+4.8501413)*r-2.2979648)*r-2.7871893)/
                   ((1.6370678*r+3.5438892)*r+1);
        }
        p -= 0.5;
        let r = p*p;
        return p*(((-25.4410605*r+41.3911977)*r-18.6150006)*r+2.5066282)/
                 ((((3.1308291*r-21.0622410)*r+23.0833674)*r-8.4735109)*r+1);
    }
    
    // I/O handling
    function calc() {
        var p = +document.getElementById("prob").value;
        var z = percentile_z(p);
        document.getElementById("z").textContent = z.toFixed(4);
    }
    calc();
    input { width: 5em }
    Probability (between 0 and 1):
    <input type="number" id="prob" step="0.0001" min="0" max="1" value="0.9500" oninput="calc()"><p>
    
    Z Score: <span id="z"></span>

    For a probability of 0.95 it returns a z-score of 1.6449. See also this table as reference.


    Derived from easycalculation.com