HeadlinesBriefing HeadlinesBriefing.com

Why Modulo Random Selection Creates Bias

Hacker News •
×

A common programming pattern picks random items using modulo: `choices[random_u64() % n]`. This seems intuitive but introduces statistical bias because the random range rarely divides evenly by the number of choices.

For example, picking from 3 items using a random number in [0, 9] gives 4 inputs to choice 1 (0, 3, 6, 9) but only 3 inputs each to choices 2 and 3. Choice 1 appears 40% of the time instead of the expected 33.3%. This modulo bias occurs whenever the random range isn't a multiple of the choice count.

The correct approach uses `random_between(l, h)` which properly distributes probability, though it's more complex to implement. Better API design would provide higher-level functions like `random_choice()` that accept explicit probability distributions, forcing developers to confront distribution requirements directly rather than relying on flawed low-level primitives.

Source: Hacker News · Summarized by HeadlinesBriefing