get a normally distributed random number in javascript

One way to generate a normally distributed random number in JavaScript is to use the Box-Muller transform. Here's an implementation of the transform:

index.tsx
function getRandomNormal(mean, standardDeviation) {
  let u = 0, v = 0;
  while (u === 0) u = Math.random(); // Converting [0,1) to (0,1)
  while (v === 0) v = Math.random();
  const normal = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);

  return normal * standardDeviation + mean;
}
300 chars
9 lines

This function takes two parameters: mean (the mean of the normal distribution) and standardDeviation (the standard deviation of the normal distribution). It returns a single random number from the specified normal distribution.

You can call this function like this:

index.tsx
const mean = 0;
const standardDeviation = 1;
const randomNormal = getRandomNormal(mean, standardDeviation);
console.log(randomNormal);
135 chars
5 lines

This will generate a normally distributed random number with a mean of 0 and a standard deviation of 1.

gistlibby LogSnag