Comment by dark-star
5 days ago
Usually you do "rdrand % <some-number>" anyways, and in that case you will still get zeroes. True, your result might be skewed by 1/(maxint/some-number) but I guess that's not a big problem in practice
5 days ago
Usually you do "rdrand % <some-number>" anyways, and in that case you will still get zeroes. True, your result might be skewed by 1/(maxint/some-number) but I guess that's not a big problem in practice
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.
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.