
The Surprisingly Deep Problem of Generating Random Numbers
In 1955, the RAND Corporation published "A Million Random Digits with 100,000 Normal Deviates," a book containing exactly what the title describes. They generated the numbers using an electronic roulette wheel connected to a computer. The book is still in print. Its Amazon reviews are legendary. Generating random numbers seems trivial until you understand the requirements. For a dice game, Math.random() is fine. For a lottery, it's legally insufficient. For cryptography, it's dangerously inadequate. The modulo bias problem A common pattern for generating a random integer from 1 to 6: Math . floor ( Math . random () * 6 ) + 1 This works because 6 divides evenly into the possible outputs. But what about generating 1 to 5? Math.random() returns a floating-point number with 2^53 significant bits. 2^53 is not evenly divisible by 5. Some values (1 and 2) are very slightly more probable than others (3, 4, 5). The bias is tiny (on the order of 10^-16) and irrelevant for most applications. But
Continue reading on Dev.to JavaScript
Opens in a new tab



