Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative distribution function in Javascript

I am searching for a way to calculate the Cumulative distribution function 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

like image 530
Thomaschaaf Avatar asked Mar 10 '11 12:03

Thomaschaaf


2 Answers

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.000223264606750539
//wolframalpha.com              0.000223221102572082
like image 178
Thomaschaaf Avatar answered Sep 21 '22 16:09

Thomaschaaf


The math.js library provides an erf function. Based on a definition found at Wolfram Alpha , the cdfNormalfunction can be implemented like this in Javascript:

const mathjs = require('mathjs')

function cdfNormal (x, mean, standardDeviation) {
  return (1 - mathjs.erf((mean - x ) / (Math.sqrt(2) * standardDeviation))) / 2
}

In the node.js console:

> console.log(cdfNormal(5, 30, 25))
> 0.15865525393145707 // Equal to Wolfram Alpha's result at: https://sandbox.open.wolframcloud.com/app/objects/4935c1cb-c245-4d8d-9668-4d353ad714ec#sidebar=compute
like image 41
Marcus Vinícius Monteiro Avatar answered Sep 21 '22 16:09

Marcus Vinícius Monteiro