🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

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

Re: rand() within a range.

#7266
From: Narciso Jaramillo
Date: Thu, 06 Dec 1990 17:26
38 lines
2098 bytes
In article <1990Dec6.033145.22855@zorch.SF-Bay.ORG> xanthian@zorch.SF-Bay.ORG (Kent Paul Dolan) writes:

   dolf@idca.tds.philips.nl (Dolf Grunbauer) writes:
   > 737104@sheoak.bcae.oz (David Thiele) writes:

   >> Is there a way to generate random numbers within a certain range in
   >> Lattice C??. Ive done it with the following code but it's not very
   >> elegant (or fast!),

   >	return (rand() % range);

   Nope.  You don't want to do that; it gives you a biased sample.  To see
   the worst case, suppose, where MAXINT is the largest possible output of
   rand(), that range is approximately 2*MAXINT/3.  Then you're going to
   get about twice as many samples in the interval from zero to range/2 -1,
   as in range/2 to range -1.

If you're willing to do some floating-point arithmetic, you
can also do

return ((int)floor((double)(rand())/MAXINT * high));

or

return ((int)floor(drand48() * high));

Since rand() returns values that are (presumably evenly) distributed
over the range [0, MAXINT), (double)(rand())/MAXINT should return
floating point values that are evenly distributed over the range [0.0,
1.0).  Since drand48() also returns values in [0.0, 1.0), both of
these should return unbiased values in the range [0, high).  Slightly
expensive because of the floating-point operations, but you don't have
to go through the (admittedly fast, though not necessarily faster)
contortions of Kent's algorithm.



nj
Technical Details
Message-ID: <NJ.90Dec6092622@magnolia.Berkeley.EDU>
Path: arc1-ca.pugleaf.net!utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!samsung!rex!ames!bionet!agate!agate.berkeley.edu!nj
References: <666@sheoak.bcae.oz> <540@ssp9.idca.tds.philips.nl> <1990Dec6.033145.22855@zorch.SF-Bay.ORG>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!samsung!rex!ames!bionet!agate!agate.berkeley.edu!nj
From: nj@magnolia.Berkeley.EDU (Narciso Jaramillo)
Newsgroups: comp.sys.amiga.tech
Subject: Re: rand() within a range.
Message-ID: <NJ.90Dec6092622@magnolia.Berkeley.EDU>
Date: 6 Dec 90 17:26:22 GMT
References: <666@sheoak.bcae.oz> <540@ssp9.idca.tds.philips.nl>
 <1990Dec6.033145.22855@zorch.SF-Bay.ORG>
Sender: usenet@agate.berkeley.edu (USENET Administrator)
Organization: /h/bair/nj/.organization
Lines: 38
In-Reply-To: xanthian@zorch.SF-Bay.ORG's message of 6 Dec 90 03:31:45 GMT