"We act as though comfort and luxury were the chief requirements of life, when all that we need to make us happy is something to be enthusiastic about." - Einstein

the brown-dragon blog

Using rand ();

2009-05-13

The rand () function generates a pseudo-random number in the range [0, RAND_MAX]. You can initialize it with srand (seed). In most cases, however, we want random numbers in a much smaller range [0, M). What's the best way to do this?

Points to note:

When we need to adjust the range from [0, RAND_MAX] to [0, M) | (M<RAND_MAX) we should not use:
        num = rand () % M;
as the result will focus on the lower bits of the rand () result, which are much less random than the higher bytes (for a linear congruential generator).

The recommended way to get a random number in the required range is:

        num = (int)(( ((double)rand ()) / ((double)(RAND_MAX) + 1.0) ) * M);

Points to note:

Other Posts

(ordered by Tags then Date)