When random is not actually random enough

This article explains the technical flaw in using the modulo operator to select items from a set using a random number generator. It demonstrates how this method creates a non-uniform distribution, leading to biased selection results.
Why it matters
It addresses a common programming pitfall that can lead to subtle, hard-to-debug logic errors in software systems requiring true randomness.
There is a common pattern you see pop up in codebases everywhere that many of us have written: given a set of objects, pick one at random. Every object should have the same chance of being picked. A rather simple and direct solution is to pick a big random number, then clamp that number to the number of choices by modulo:
Get smarter about the news
Sign up free for a feed built around what you actually care about, Dive Deeper research on any story, and the full text of every article.
Create free accountAlready have an account? Sign in