Mail Archives: djgpp/1997/06/05/08:45:41
Francois Charton wrote:
> This is not the case with the rand() function from DJGPP
> libc, but it may exist for other rand() functions.
The DJGPP one is better than most (you're correct, it
does avoid the odd/even trap) but as you say it's not
portably true, and it does still have more randomness
in some bits than in others.
> 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).
As pointed out before, that will sometimes generate numbers
outside your range due to rounding. For instance:
max. random value M = 65535
range of numbers n = 10
M/n = 6553
65535 / 6553 = 10
so it can sometimes generate the number 10 which is outside
the range 0-9. That's fine if you combine it with George's
algorithm (generata another number if the result is outside
the wanted range), but not on its own.
OK, it's only (in the above case) 5 out of 65536 times, but
if you're using it to index an array you can guarantee those
cases will occur and cause a SEGV at exactly the wrong time.
Chris C
- Raw text -