Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!cs.utexas.edu!uunet!munnari.oz.au!brolga!uqcspe!batserver.cs.uq.oz.au!thyssen From: thyssen@batserver.cs.uq.oz.au (Anthony Thyssen) Newsgroups: comp.sys.amiga Subject: Re: Lattice Random Numbers Message-ID: <4980@uqcspe.cs.uq.oz.au> Date: 24 Sep 90 00:16:44 GMT References: <4604@crash.cts.com> Sender: news@uqcspe.cs.uq.oz.au Reply-To: thyssen@batserver.cs.uq.oz.au Lines: 34 acota@pro-realm.cts.com (Arnold Cota) writes: >How do I generate a random number in the range of 1 to 54 in Lattice C? I recently had the same problem as you - random numbers in a certian range To solve this I used the lattice C random number generators srand((long)time(NULL)); /* seed random with current time */ ULONG r = rand(); /* get a random number */ Note that the seeding is done once at the begining of your program only. the result is a number in the rand 0..2^31 IE a positive long number. (Of 31 bit length). I large number of people will then tell you to then mod (`%' in C) this over the range. - This is wrong and on larger ranges makes the random number generator tend to produce more low numbers in the range than higher ones. The solution is a little more complicated. The folloing is my macro definition to produce a number over a range (inclusive) #define RandInt(lo,hi) (int)\ ((lo)+((((long)((hi)-(lo)+1)*(long)(rand()&0x7fff))>>15) & 0x7fff)) Then to get a number over range 1 to 54 inclusive you do number = RandInt(1,54) The macro definition spreads the numbers produced equally over the whole range. Anthony Thyssen - (Dragon Computing!) thyssen@batserver.cs.uq.oz.au ------------------------------------------------------------------------------- It has been proved, beyond a shadow of a doubt, that million-to-one chances, occur nine times out of ten! --- Terry Pratchet -------------------------------------------------------------------------------