I'd like to use the PRNG to generate a number between 1-20 (or 1-10, etc.). What's the best way to go about this?

Thanks for any input.

## Pseudorandom number within a range

### Pseudorandom number within a range

Michael Earls

https://cerkit.com

https://cerkit.com

### Re: Pseudorandom number within a range

If you can make your range fit a power of 2 just pick a subset of bits that it outputs. For example if 0-31 is acceptable then just use the first five bits of the output.

To get it to an arbitrary range is a little harder to do efficiently. The simplest way is to truncate to the closest range (ie for 1-20 truncate to 0-31). Add one if you don't want to include 0. Then subtract the max value when it overflows. So if it is over 20 subtract 20. The downside for this is that 1-12 will be more likely to show up than 13-20. To fix this you'd need to actually divide which is expensive but doable.

If you need an exact range with even distribution you can multiply by the max then shift right. So for 1-20 example, first add one so you get 1-32. Then multiply it by 20 and then shift by 5 to the right (effectively dividing by 32). You can add rounding if you need a super even distribution.

For an even more even distribution you can use the full 32 bits then shift by 32 bits right instead of 5. This makes the multiplication a lot more expensive though.

To get it to an arbitrary range is a little harder to do efficiently. The simplest way is to truncate to the closest range (ie for 1-20 truncate to 0-31). Add one if you don't want to include 0. Then subtract the max value when it overflows. So if it is over 20 subtract 20. The downside for this is that 1-12 will be more likely to show up than 13-20. To fix this you'd need to actually divide which is expensive but doable.

If you need an exact range with even distribution you can multiply by the max then shift right. So for 1-20 example, first add one so you get 1-32. Then multiply it by 20 and then shift by 5 to the right (effectively dividing by 32). You can add rounding if you need a super even distribution.

For an even more even distribution you can use the full 32 bits then shift by 32 bits right instead of 5. This makes the multiplication a lot more expensive though.