get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in javascript

To generate a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in JavaScript, we can use the Box-Muller transform. The Box-Muller transform takes two uniformly distributed random numbers and transforms them into two independent random numbers with a normal distribution.

Here's an example implementation:

index.tsx
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 );
}

var random_number = randn_bm(); // random_number is a random number from a normal distribution with mean 0 and standard deviation 1
353 chars
9 lines

In the randn_bm function, we first generate two uniformly distributed random numbers between 0 and 1 using Math.random(). We then transform these uniform random numbers into two normal random numbers using the Box-Muller transform. We return one of these normal random numbers, which will have a mean of 0 and a standard deviation of 1.

We can call the randn_bm() function as many times as we need to generate as many random numbers from a normal distribution as we want.

gistlibby LogSnag