Skip to content

Instantly share code, notes, and snippets.

@samme
Last active April 26, 2025 03:30
Show Gist options
  • Save samme/42d822045f39c14e707c321cbb070488 to your computer and use it in GitHub Desktop.
Save samme/42d822045f39c14e707c321cbb070488 to your computer and use it in GitHub Desktop.
Weighted random number generators <https://codepen.io/samme/pen/dPPRKjO>
const { asin, cos, random, PI } = Math;
// Average 0.333
const Low = () => random() ** 2;
// Average 0.666
const High = () => 1 - random() ** 2;
// Average 0.5, middle-biased
const Mid = () => 0.5 + asin(2 * random() - 1) / PI;
// Average 0.5, end-biased
const HighLow = () => 0.5 * (1 - cos(PI * random()));
// Random value within [min, max)
const Rand = (min, max, rand) => min + (max - min) * rand();
// Random array member
const Pick = (arr, rand) => arr[Math.floor(rand() * arr.length)];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment