Random Numbers

Doug Gwyn gwyn at brl-smoke.ARPA
Thu Feb 11 11:16:45 AEST 1988


In article <22926 at ucbvax.BERKELEY.EDU> becmug at ernie.Berkeley.EDU (BECMUG Guests) writes:
>	I've just learned C, and am thinking of good ways to generate random
>numbers. Does anyone have any suggestions?

Start by reading Donald Knuth's "The Art of Computer Programming, Vol. 2:
Seminumerical Algorithms", Chapter 3 (Random Numbers).  Until you basically
understand this material, you're probably best off by simply using the
pseudo-random number generator in your C library (usually called rand(),
sometimes random(); on System V drand48() is pretty good).  There are a few
good algorithms in the professional literature and a bunch of not-so-good
ones.  The main moral to be drawn from Knuth is: if you really need good
randomness properties, you had better thoroughly test whatever generator
you're considering.

All that said, here's a typical (portable) linear-congruential pseudo-random
number generator, taken from the draft ANSI C standard; rand() returns an
integer uniformly distributed from 0 through 32767 (inclusive), and srand()
is used to initialize a sequence to a particular seed, or to avoid getting
a predictable sequence (by setting a seed based on some system variable
such as process ID or time-of-day).

	static unsigned long int next = 1;

	int rand(void)
	{
		next = next * 1103515245 + 12345;
		return (unsigned int)(next/65536) % 32768;
	}

	void srand(unsigned int seed)
	{
		next = seed;
	}



More information about the Comp.lang.c mailing list