Pseudorandom number within a range

Need some help on a project you are working on or got stuck on a tutorial? Post your questions here.
Post Reply
cerkit
Posts: 27
Joined: March 30th, 2017, 10:27 am

Pseudorandom number within a range

Post by cerkit » May 1st, 2018, 7:22 pm

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.
Michael Earls
https://cerkit.com

embmicro
Site Admin
Posts: 834
Joined: March 24th, 2013, 12:45 pm

Re: Pseudorandom number within a range

Post by embmicro » May 9th, 2018, 11:58 am

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.

Post Reply