Random values with a normal distribution

suggest change

Math.random() is approximately uniform over the interval from 0 inclusive to 1 exclusive. Summing several uniform samples produces a bell-shaped approximation, but the Box–Muller transform gives a more direct standard normal distribution:

function randomNormal() {
  // Math.random() can return 0, which is unsuitable for log().
  let u = 0;
  let v = 0;

  while (u === 0) u = Math.random();
  while (v === 0) v = Math.random();

  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}

The result has an approximate mean of 0 and standard deviation of 1. Scale and shift it for another normal distribution:

function randomNormalWith(mean, standardDeviation) {
  return mean + randomNormal() * standardDeviation;
}

const sample = randomNormalWith(100, 15);

Math.random() is not cryptographically secure. Use crypto.getRandomValues() for security-sensitive random bytes, while remembering that uniform cryptographic randomness still needs an appropriate transform when a normal distribution is required.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents