Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!munnari.oz.au!mel.dit.csiro.au!yarra!pta!teti!teslab!andrew From: andrew@teslab.lab.OZ (Andrew Phillips) Newsgroups: comp.sys.amiga.tech Subject: Re: rand() within a range. Message-ID: <1167@teslab.lab.OZ> Date: 11 Dec 90 06:15:44 GMT References: <666@sheoak.bcae.oz> <540@ssp9.idca.tds.philips.nl> Reply-To: andrew@teslab.lab.oz.au (Andrew Phillips) Organization: Technology Evaluation Section, L.A.B., Sydney Lines: 38 In article <540@ssp9.idca.tds.philips.nl> dolf@idca.tds.philips.nl (Dolf Grunbauer) writes: >In article <666@sheoak.bcae.oz> 737104@sheoak.bcae.oz (David Thiele) writes: >>Is there a way to generate random numbers within a certain range in >>Lattice C??. ... > >... >Random(range) >int range; >{ > if range = 0 > return(0); > else return (rand() % range); >} This is not the best solution for two reasons. First, unless range is a divisor of the maximum value returned by rand() plus one then the numbers will not be distributed evenly over the range. Second, even the best PRNG's are not very random in their least significant bits, so you want values which use the most significant bits. A simple portable solution would be to use drand48(): #define RANDOM(RANGE) ((int)(drand48()*(RANGE))) If you don't want to use floating point numbers or need more speed and know that longs are bigger than ints you could use (assuming rand() returns a value between zero and MAXINT): #define RANDOM(RANGE) ((int)(((long)rand()*(RANGE))/(MAXINT+1))) Or else if you know range is never going to be bigger than say 256 use something like: #define RANDOM(RANGE) (((rand()/256)*(RANGE))/((MAXINT+1)/256)) Andrew. -- Andrew Phillips (andrew@teslab.lab.oz.au) Phone +61 (Aust) 2 (Sydney) 289 8712