Mail Archives: djgpp/1997/03/08/03:54:42
John M. Aldrich <fighteer AT cs DOT com> wrote:
>
>To get a random number from 0 to X - 1, use:
>
> n = random( ) % X;
>
>Before everybody gets hysterical on me again, let me say in advance that
>the GNU random() RNG, unlike rand(), is guaranteed to be random in the
>lower bits, so you can use the mod operator safely.
Yes, but then you are taking chances about portability: rand() is an ANSI
library function, and could be implemented in a less intelligent way on
other systems or with other compilers... Actually, chances are high that
is will be so: the ANSI comitee itself has published such an algorithm as
a example, so many programmers will certainly copy it.
IMHO, it is better to use the divide than the mod operation: precalculate
RAND_MAX/X, and do rand()/(RAND_MAX/X), it is as fast as the mod, a
little less readable (if you are afraid about that, use a macro to make
it clearer to readers of your code), and it is guaranteed to be portable.
(It is a bit like the void main(void) vs int main(void) problem) the
former is usable in many cases, but still not a good idea).
While we are at it, did anyone try some good random generator crash test
suite (like the tests in Knuth for instance) on rand() and random()?
Francois
- Raw text -