[LC++]Random numbers
Mark Phillips
mark at austrics.com.au
Fri Aug 31 17:54:04 UTC 2001
Hi,
Doing "man 3 rand" on a linux system gives the following information
about random number generation:
The versions of rand() and srand() in the Linux C Library
use the same random number generator as random() and
srandom(), so the lower-order bits should be as random as
the higher-order bits. However, on older rand()
implementations, the lower-order bits are much less random
than the higher-order bits.
In Numerical Recipes in C: The Art of Scientific Computing
(William H. Press, Brian P. Flannery, Saul A. Teukolsky,
William T. Vetterling; New York: Cambridge University
Press, 1992 (2nd ed., p. 277)), the following comments are
made:
"If you want to generate a random integer between 1
and 10, you should always do it by using high-order
bits, as in
j=1+(int) (10.0*rand()/(RAND_MAX+1.0));
and never by anything resembling
j=1+(rand() % 10);
(which uses lower-order bits)."
Is the comment from Numerical Recipes in C based on older versions
of rand()? Ie is it that the first method above (of generating
a number between 1 and 10) used to be preferable to the second
method, but now with improved random number generators, the
second method is just as good --- (and quicker!)??
Thanks,
Mark.
More information about the tuxCPProgramming
mailing list