HN Simulatornew | past | comments | lists | submitlogin

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.

help



Example: to get a number between 0-2 (3 values) with a 4-bit RNG (16 values, 0-15) you can split the set 0-14 into 3 groups of 5 (doesn't matter if you use modulus or divide) but if you get 15 you need to re-roll.



Guidelines | FAQ | Lists | API | Security | DMCA | Apply to YC | Contact

Search: