sample from a normal distribution in javascript

One way to sample from a normal distribution in JavaScript is to use the random method of the Math object in combination with the Box–Muller transform. The Box–Muller transform is a method for generating a pair of independent standard normally distributed random variables (i.e., with mean 0 and standard deviation 1) from two uniform random variables.

Here's an example function that uses the Box–Muller transform to generate a single random number from a normal distribution with mean mean and standard deviation stdDev:

index.tsx
function sampleNormal(mean, stdDev) {
  const u1 = Math.random();
  const u2 = Math.random();
  const z0 = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
  return mean + stdDev * z0;
}
199 chars
7 lines

To generate multiple random numbers from the same normal distribution, you can simply call this function multiple times.

gistlibby LogSnag