Skip to content

Instantly share code, notes, and snippets.

@paulroth3d
Created August 20, 2023 02:51
Show Gist options
  • Save paulroth3d/745d69051d3ec8bfd0dd011ad6304bf9 to your computer and use it in GitHub Desktop.
Save paulroth3d/745d69051d3ec8bfd0dd011ad6304bf9 to your computer and use it in GitHub Desktop.
simple box muller
// https://stackoverflow.com/questions/25582882/javascript-math-random-normal-distribution-gaussian-bell-curve
module.exports.boxMueller = function boxMueller(min = 0, max = 1) {
const u = 1 - Math.random();
const v = Math.random();
let num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
// translate from (-10,10) to (0,1) inclusive
num = num / 10.0 + 0.5; // Translate to 0 -> 1
num = Math.max(0, num);
num = Math.min(1, num);
// resample if out of bounds
// if (num > 1 || num < 0) return RandomUtil.randomBM();
return num * (max - min) + min;
};
module.exports.boxMuellerPick = function boxMuellerPick(list, skew) {
let index = RandomUtil.boxMueller(0, list.length - 1);
// eslint-disable-next-line
index = index ** (skew || 1); // Math.pow(index, skew || 1);
return list[index];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment