Search code examples
javascriptmath

Cumulative distribution function of the normal distribution in Javascript


I am searching for a way to calculate the Cumulative distribution function of the normal distribution in Javascript. Are there classes which have implemented this? Do you have an idea to get this to work? It does not need to be 100% percent accurate but I need a good idea of the value.

http://en.wikipedia.org/wiki/Cumulative_distribution_function


Solution

  • I was able to write my own function with the help of Is there an easily available implementation of erf() for Python? and the knowledge from wikipedia.

    The calculation is not 100% correct as it is just a approximation.

    function normalcdf(mean, sigma, to) 
    {
        var z = (to-mean)/Math.sqrt(2*sigma*sigma);
        var t = 1/(1+0.3275911*Math.abs(z));
        var a1 =  0.254829592;
        var a2 = -0.284496736;
        var a3 =  1.421413741;
        var a4 = -1.453152027;
        var a5 =  1.061405429;
        var erf = 1-(((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*Math.exp(-z*z);
        var sign = 1;
        if(z < 0)
        {
            sign = -1;
        }
        return (1/2)*(1+sign*erf);
    }
    
    normalcdf(30, 25, 1.4241); //-> 0.12651187738346226
    //wolframalpha.com              0.12651200000000000