Mail Archives: djgpp/1997/06/05/07:31:47
Chris Croughton wrote:
>
> Actually, for the most common use (rand() % n) they are not equally as
> good. The problem with rand() is that the bottom bits are not at all
> random, in fact they are a fairly short sequence especially if 'n' is
> a power of 2 (i.e. extracting the bottom bits). I believe it just
> alternates even and odd numbers, for instance.
>
This is not the case with the rand() function from DJGPP libc, but it may
exist for other rand() functions.
For this reason, I think it is always bad programming practice to use
(rand()%n), the good way to do it is (rand()/(MAXRAND/n)), MAXRAND being
the largest number rand() can produce (the modulus in the case of a
linear congruential generator).
rand()%n may succeed if your rand() function is good, but you are taking
chances with portability matters.
Francois
- Raw text -