how to limit rand() range?

7 posts / 0 new
Author
Message

According to the libc documentation, it seems that rand() has an upper limit set by RAND_MAX macro which defaults to 0x7FFF. I would like to cap the max. number at different values at run-time. Any suggestions on how to do that?

Be aware that if you actually need randomness, you don't want to use rand() at all, it's usually pretty awful. And also note that the obvious strategies listed on that page will produce slightly uneven distributions.

the_real_seebs wrote:
if you actually need randomness, you don't want to use rand() at all

Indeed - it is clearly documented as a pseudo-random number generator.

note that the obvious strategies listed on that page will produce slightly uneven distributions.

As stated there:

cplusplus.com wrote:
Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).

The traditional method is the % operator. So

`val = rand() % 10;`

gives you 0..9 but note that % is an "expensive" operation (effectively a divide) so you might settle for something like:

`val = rand() & 0x0F;`

to get numbers 0 .. 15 because & is a far less expensive operation - but then again maybe it was some arbitrary, not binary range you wanted ?

Thanks for the feedback... I was afraid that modulo might be the only way when using the library functions + requiring a range that is not a power of 2.

For the current stage of development these functions will be fine, however I am tempted to use the ADC as a noise source.

rand() would not be safe for a Casino operator but it should be plenty random enough for testing a program or Simulation.

I really don't see why anyone would worry about the cost of the modulo versus an AND.  The rand() takes a quite a few cycles by itself.

You might use noise from the ADC to create the initial seed for rand() but you certainly would not trust the ADC to give you an even distribution of "noise".

No,  I have not been following this thread.    I may not have grasped the plot.

David.