🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.sys.amiga.tech
Article #7436

Re: rand() within a range.

#7436
From: Kent Paul Dolan
Date: Thu, 13 Dec 1990 05:24
20 lines
1309 bytes
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.
<xanthian@Zorch.SF-Bay.ORG> <xanthian@well.sf.ca.us>
Technical Details
Message-ID: <1990Dec13.052449.28701@zorch.SF-Bay.ORG>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!usc!apple!vsi1!zorch!xanthian
References: <666@sheoak.bcae.oz> <540@ssp9.idca.tds.philips.nl> <1167@teslab.lab.OZ>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!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