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

To get a random number from a normal distribution in TypeScript, you can use the Box-Muller transform. The following function takes in a standard normal distribution with a mean of 0 and a standard deviation of 1 and returns a random number from that distribution:

index.ts
function randomNormalDistribution(): number {
  let u = 0, v = 0;
  while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)
  while (v === 0) v = Math.random();
  const num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);

  return num;
}
260 chars
9 lines

You can use this function to generate random numbers from a normal distribution as needed by calling it in your code.

gistlibby LogSnag