Path: utzoo!mnetor!uunet!portal!cup.portal.com!Uly From: Uly@cup.portal.com Newsgroups: comp.lang.c Subject: Re: Random Numbers Message-ID: <3128@cup.portal.com> Date: 11 Feb 88 10:11:07 GMT References: <22926@ucbvax.BERKELEY.EDU> Organization: The Portal System (TM) Lines: 44 XPortal-User-Id: 1.1001.3486 Here's my favorite random number generator. It's Knuth's algorithm A from Seminumerical Algorithms. The primary advantage is speed over the linear congruential methods. The primary disadvantage is that as of 1981 (correct me if I'm out of date) the theoretical underpinnings for this technique were not well-understood. In any case, I use this routine constantly and have never had a problem with it. The initializing routine can use any 55 int array, I normally preset it with known values and change only the first word based on the current clock ticks. Note that the array must possess at least one odd integer. The period of this generator is guaranteed to be at least 2^55-1. Uly ---------------------------------------------------------------------------- Michael Hill, Hill SoftSystems | "Millions long for immortality who don't 4616 N. 16th, Arlington VA 22207| don't know what to do on a rainy Sunday (703) 525-2353 | afternoon." -- Susan Ertz ARPA: Uly@cup.portal.com | USENET: uunet!portal!cup!Uly ---------------------------------------------------------------------------- (Apologies for weak c code, I invariably code this one in assembler) static int Y[55],K,J; initrandom(seed) int *seed; { int i=55; while(i--) Y[i]= *seed++; Y[0]=13; /* array must have one odd val */ J=23; K=54; } random(maxval) /* Return psuedorandom val mod maxval */ int maxval; { maxval= (Y[K--]+=Y[J--])%maxval; if(J<0) J=54; if(K<0) K=54; if(maxval<0) return -maxval; return maxval; } ...............