Bug in rand() and srand()
Tim Smith
tim at callan.UUCP
Tue Mar 5 11:31:30 AEST 1985
In article <320 at cubsvax.UUCP> peters at cubsvax.UUCP (Peter S. Shenkin) writes:
>In attempting to use these functions under 4.1bsd on a VAX/780, I found that
>rand() returns strictly alternating even and odd numbers, regardless of
>seed!!! So I went and tried the same thing on a 4.2bsd system, and found
>the same behavior.
>
If BSD rand() is at all like System V rand(), this is not a bug. Rand()
is a multiplicitive congruential (sp?) random number generator, which means
it works like this:
R = A * R + C mod M
i+1 i
So, depending on the parity of A and C, you have one of the following cases:
Ri+1 is always odd
Ri+1 is always even
Ri+1 is always same parity as Ri
or Ri+1 is always opposite parity of Ri
In this sort of number generator, the high bits are "more random" than the
low bits. Thus, for example, to get a stream or random bits, one would
look at the top bit ( assuming M is a power of two... ), not the bottom bit.
Look at Knuth, Vol. II for almost all that is known on this topic.
--
Duty Now for the Future
Tim Smith
ihnp4!wlbr!callan!tim or ihnp4!cithep!tim
More information about the Comp.lang.c
mailing list