Michael A
Michael A

Reputation: 9920

How to find the normal distribution in Javascript?

I'm trying to convert a formula from an Excel spreadsheet into an online calculator, the formula specifically is:

=(NORM.S.DIST(2.5467437 + -1.9344945 *B7^( -0.5),1))^2

The problem I'm encountering is that NORM.S.DIST doesn't appear to exist in any Javascript library that I've found. In researching the problem I did find this solution, but it's a C# based one and I don't know how to convert that into Javascript. How do I approach this problem in Javascript?

Upvotes: 3

Views: 2309

Answers (2)

Rich C
Rich C

Reputation: 21

This should do the trick.

For any normal distribution defined by the mean and SD, let myval be the value for which you want to find the centile.

If you want just to return the output of NORM.S.DIST in excel, just skip the centile function.

var myval = 14;
var mean = 15.5;
var SD = 4.8333;

var answer = centile(mean, SD, myval);
console.log(answer);

function centile(mean, SD, val)
{
    z = (val-mean)/SD;
    ans = NORMSDIST(z);
    return ans;
}

function erf(x)
{
    //A&S formula 7.1.26
  
  var ans = 0;
    var a1 = 0.254829592;
    var a2 = -0.284496736;
    var a3 = 1.421413741;
    var a4 = -1.453152027;
    var a5 = 1.061405429;
    var p = 0.3275911;
    x = Math.abs(x);
    var t = 1 / (1 + p * x);
    //Horner's method, takes O(n) operations for nth order polynomial
    ans = 1 - ((((((a5 * t + a4) * t) + a3) * t + a2) * t) + a1) * t * Math.exp(-1 * x * x);
    return ans; 
}

function NORMSDIST(z)
{
    var ans = 0;
    var sign = 1;
    if (z < 0) sign = -1;
    ans = 0.5 * (1.0 + sign * erf(Math.abs(z)/Math.sqrt(2)));
    return ans;
}

working pen: https://codepen.io/RichClarke/pen/oNdpoRM?editors=0011

Upvotes: 2

Paul Draper
Paul Draper

Reputation: 83393

EDITED:

This varies from the actual value by less than 0.005:

function cummulativeNormalDist(x) {
    if(x < 2.2) {
        return .1 * x * (4.4 - x);
    } else if(x < 2.6) {
        return .49;
    } else {
        return .50;
    }
}

Source: http://mathworld.wolfram.com/NormalDistributionFunction.html

Upvotes: 2

Related Questions