A common programming pattern involves selecting a random item from a set by generating a large random number and then using the modulo operator to clamp it to the size of the set. For example, `choices[random_u64() % 10]` is often used to pick one of ten items. This method is intuitive and frequently implemented, especially in languages like C or Haskell where standard libraries might offer limited random number generation functions.
The issue with this approach is that it does not preserve a uniform distribution. While the initial `random_u64()` might be uniformly distributed, the modulo operation can introduce bias. If the range of the input random number is not an exact multiple of the number of choices, some choices will have more input values mapping to them than others.
Consider selecting from 3 objects using a random number from 0 to 9. Object #1 would be chosen if the input is 0, 3, 6, or 9 (4 times). Object #2 would be chosen for 1, 4, 7 (3 times), and Object #3 for 2, 5, 8 (3 times). This results in Object #1 being picked 40% of the time, while Objects #2 and #3 are picked only 30% of the time, deviating from the desired 33.3% uniform chance.
To ensure a truly uniform distribution when selecting from a specific range, developers should use functions designed for this purpose, such as `random_between(l, h)`. These functions correctly handle the mapping of a large random input to a smaller, specific range while maintaining an even probability for each possible outcome.
✨ This summary was generated by AI from the outlets' reporting listed below. It is not independently verified and may contain errors — check the original sources. How BrevFeed works →
One email each morning: the day's tech stories, clustered across outlets and summarized. No account needed.
One email a day. Unsubscribe in one click, any time.
Spend a few minutes, get the whole day. Every topic's top stories in one hands-free rundown — listen, watch, or read the transcript.
▶ Play today's briefNew every morning, and the back catalogue is archived by date.
Using the modulo operator with a large random number to select from a smaller set of choices can lead to a non-uniform distribution, where some choices are picked more frequently than others. This occurs because the modulo operation does not evenly distribute the input range across the output range when the input range size is not a multiple of the output range size. Developers should use functions like `random_between(l, h)` to ensure uniform distribution when selecting from a range.