Gregory Gregory - 7 months ago 36
Javascript Question

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.

Answer

Here is a function that does an opposite calculation (probability to z-score):

function percentile_z(p) {
    var a0= 2.5066282,  a1=-18.6150006,  a2= 41.3911977,   a3=-25.4410605,
        b1=-8.4735109,  b2= 23.0833674,  b3=-21.0622410,   b4=  3.1308291,
        c0=-2.7871893,  c1= -2.2979648,  c2=  4.8501413,   c3=  2.3212128,
        d1= 3.5438892,  d2=  1.6370678, r, z;

    if (p>0.42) {
        r=Math.sqrt(-Math.log(0.5-p));
        z=(((c3*r+c2)*r+c1)*r+c0)/((d2*r+d1)*r+1);
    } else {
        r=p*p;
        z=p*(((a3*r+a2)*r+a1)*r+a0)/((((b4*r+b3)*r+b2)*r+b1)*r+1);
    }
    return z;
}

Grabbed from easycalculation.com