11.11. Getting a Random Integer in a Range
Problem
You want to choose a number in a particular range, with each possible value equally likely. For example, you may be simulating dice rolling and do not want any number to be more likely to come up than any other. You want all numbers in the range to be possible values, including both endpoints. That is, if you ask for a number between 1 and 6, you’d like both 1 and 6 to be as likely as 2, 3, 4, or 5.
Solution
There are multiple ways to handle this problem. The most common is the least correct, and that is to simply reduce a random integer (see Recipe 11.10) modulo the size of the range and add to the minimum possible value. This can lead to slight biases in your random numbers, which can sometimes lead to practical attacks, because it means that some outputs are more likely than others.
We discuss more exact solutions in the next section.
Discussion
In all cases, you will start with a function that gives you a random
unsigned number that can be any value, such as
spc_rand_uint( )
from Recipe 11.10. You will mold numbers
returned from this function into numbers in a specific range.
If you need random numbers in a particular range, the general approach is to get a number between zero and one less than the number of values in the range, then add the result to the smallest possible value in the range.
Ideally, when picking a random number in a range, you would like every possible value to be equally likely. However, if you map from an arbitrary ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access