Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!usc!apple!vsi1!zorch!xanthian From: xanthian@zorch.SF-Bay.ORG (Kent Paul Dolan) Newsgroups: comp.sys.amiga.tech Subject: Re: rand() within a range. Message-ID: <1990Dec13.052449.28701@zorch.SF-Bay.ORG> Date: 13 Dec 90 05:24:49 GMT References: <666@sheoak.bcae.oz> <540@ssp9.idca.tds.philips.nl> <1167@teslab.lab.OZ> Organization: SF-Bay Public-Access Unix Lines: 20 andrew@teslab.lab.oz.au (Andrew Phillips) writes: >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))) ^^^^^^^^probably not >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)) ^^^^^^^^nope Your first example will overflow to MAXNEGINT if the compiler chooses to do the promotion to long as late as possible, and your second one is guaranteed to overflow. Kent, the man from xanth.