random() error in Turbo C++

VanZandt jrv at sdimax2.mitre.org
Fri Aug 31 00:41:07 AEST 1990


random() in Turbo C is supposed to return a random integer in the range
0...n-1.  Actually, it will occasionally (once in 32768 calls) return n.

random() is implemented by a macro

     #define random(n) ((int)((long)rand()*(n))/RAND_MAX)

However, when rand() returns RAND_MAX (which is 32767), this evaluates 
to n.

To correct this, increment RAND_MAX (noting that it must thereby become
a long):

     #define random(n) ((int)((long)rand()*(n))/((long)RAND_MAX+1))
     
                   - Jim Van Zandt (jrv at mbunix.mitre.org)

p.s.  Note that the common device of using rand()%n is guaranteed to
yield a number in the range 0...n-1, but the probabilities are not uniform.
For n=30000, the probability of getting 9 is twice the probability
of getting 29000.



More information about the Comp.lang.c mailing list