logoalt Hacker News

adrian_btoday at 12:46 PM0 repliesview on HN

If you want uniformly-distributed random numbers, computing the remainder works only when the modulus is a power of two.

Otherwise, a slightly more complicated algorithm is necessary, where you reject a range of numbers either before computing the remainder (to make the set of possible values a multiple of the modulus) or after computing the value modulo some power of two (to reject values greater than your target).

Besides these 2 variants based on the remainder of division of integers, there are also 2 corresponding algorithms using multiplication of the input interpreted as a fraction, followed by taking the integer part of the result.