Path: utzoo!utgpu!water!watmath!clyde!bellcore!decvax!decwrl!labrea!aurora!amelia!ames!nrl-cmf!cmcl2!brl-adm!brl-smoke!gwyn From: gwyn@brl-smoke.ARPA (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: Random Numbers Message-ID: <7238@brl-smoke.ARPA> Date: 11 Feb 88 01:16:45 GMT References: <22926@ucbvax.BERKELEY.EDU> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 33 In article <22926@ucbvax.BERKELEY.EDU> becmug@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; }