Given a 32-bit unsigned ran num, how to manipulate value in a certain range [low, high]?

67 views Asked by At

Like the title says, I'm using a random number generator on a Freescale Coldfire chip and it returns a 32 bit unsigned value. As far as I know, there is no way to configure the generator to limit the range. What would be the best way to manipulate the number to be in the accepted range?

I was thinking of modding the number by the high range value but I would still have to deal with the lower bound.

3

There are 3 answers

0
Lee Daniel Crocker On BEST ANSWER

Yes, the traditional way is to MOD by the range, and this will be fine for many ordinary uses (simulating cards, dice, etc.) if the range is very small (a range of 52 compared to the 32-bit range of your generator is quite small). This will still be biased, but the bias will be nearly impossible to detect. If your range is bigger, the bias will be bigger. For example, if you want a random 9-digit number, the bias will be dreadful. If you want to eliminate bias altogether, there is no alternative but to do rejection sampling--that is, you must have a loop in which you generate random numbers and throw some away. If you do it right, you can keep those extra numbers needed to a minimum so you don't slow things down much.

0
Shafik Yaghmour On

This C FAQ article How can I get random integers in a certain range? explains how to properly generate random numbers in range [M,N] basically the formula you should use is:

M + (random number) / (RAND_MAX / (N - M + 1) + 1)
2
woolstar On

Stephan T. Lavavej explains why doing this is still not going to be that great:

From Going Native 2013 - rand() Considered Harmful

If you really care about even distribution, stick with a power of 2, or find some routines for dithering.