Random number generator

John Woods john at frog.UUCP
Thu Dec 28 13:41:00 AEST 1989


In article <940001 at hpavla.HP.COM>, gary at hpavla.HP.COM (Gary Jackoway) writes:
> > I was trying to generate a random number bewteen 0 and maxlongint (i.e. 2^32)
> > on my machine (80386 with Interactive). The rand() function that I have
> > returns a psuedo-random number between 0 and MAXINT (which in this case
> > is 32768). 

I assume you mean 32767.

>        longrand = (unsigned long) rand() | ((unsigned long) rand() << 32);

This is the second wrong answer I've seen.  A correct answer is

	typedef unsigned long ulong;

	longrand = (ulong)rand() | ((ulong)rand() << 15)
				 | (((ulong)rand()&3) << 30);

The first wrong answer shifted by 16, but rand() as described returns a 15-bit
integer.

A better solution (IMHO) is to grab Knuth Vol. 2 and code up a good 32 bit
RNG of your own.
-- 
John Woods, Charles River Data Systems, Framingham MA, (508) 626-1101
...!decvax!frog!john, john at frog.UUCP, ...!mit-eddie!jfw, jfw at eddie.mit.edu

Happiness is Planet Earth in your rear-view mirror.	- Sam Hurt



More information about the Comp.lang.c mailing list