JavaScript Math.random Normal distribution (Gaussian bell curve)?

Mangooxx picture Mangooxx · Aug 30, 2014 · Viewed 75.6k times · Source

I want to know if the JavaScript function Math.random uses a normal (vs. uniform) distribution or not.

If not, how can I get numbers which use a normal distribution? I haven't found a clear answer on the Internet, for an algorithm to create random normally-distributed numbers.

I want to rebuild a Schmidt-machine (German physicist). The machine produces random numbers of 0 or 1, and they have to be normally-distributed so that I can draw them as a Gaussian bell curve.

For example, the random function produces 120 numbers (0 or 1) and the average (mean) of these summed values has to be near 60.

Answer

Maxwell Collard picture Maxwell Collard · Apr 7, 2016

Since this is the first Google result for "js gaussian random" in my experience, I feel an obligation to give an actual answer to that query.

The Box-Muller transform converts two independent uniform variates on (0, 1) into two standard Gaussian variates (mean 0, variance 1). This probably isn't very performant because of the sqrt, log, and cos calls, but this method is superior to the central limit theorem approaches (summing N uniform variates) because it doesn't restrict the output to the bounded range (-N/2, N/2). It's also really simple:

// Standard Normal variate using Box-Muller transform.
function randn_bm() {
    var u = 0, v = 0;
    while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
    while(v === 0) v = Math.random();
    return Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
}