Bug in rand() and srand()

Eugene D. Brooks III brooks at lll-crg.ARPA
Tue Mar 5 12:54:58 AEST 1985


> 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.  
> 
> It may be that this has already been hashed out in some
> of the above newsgroups, but since I only read net.lang.c among them I will
> have missed the discussion.  If anyone has a rewritten rand(), or other
> advice, I'd appreciate being mailed a fix.
> 
> Thanks,  Peter S. Shenkin,   {philabs,cmcl2!rna}!cubsvax!peters

rand uses a 32bit multiplicative random number generator.  These generators
tend to generate a repeating sequence in the lower bits.  On the pdp 11
the generator used a long and the returned value was shifted right by 16
bits to get an int.  The horribly behaved lower bits never hit the user.
On the vax the how 32 bit item is returned.  As you noticed those badly
behaved bits are there.  If you want to use rand shift it down.  Shift at
least 8 bits out.  A better way around the problem is to use the more
sophisticated random number generator random() all of its bits are supposed
to be random and its really not that much slower than rand().  A simple
#define rand random can fix your code.



More information about the Net.bugs mailing list