www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/02/01/14:47:09

From: "Oliver Roese" <oroese AT edina DOT xnc DOT com>
Newsgroups: comp.os.msdos.djgpp
References: <Pine DOT SUN DOT 3 DOT 91 DOT 990201130503 DOT 14737A-100000 AT is>
Subject: Re: random
Date: Mon, 1 Feb 1999 20:09:38 +0100
Lines: 43
X-Newsreader: Microsoft Outlook Express 4.72.3110.5
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3
NNTP-Posting-Host: ip209.xnc.de
Message-ID: <36b5ff84.0@news.xenologics.com>
X-Trace: 1 Feb 1999 20:24:52 +0100, ip209.xnc.de
Organization: .XNC GmbH
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Eli Zaretskii wrote...
>
>On Sun, 31 Jan 1999, Rehammar wrote:
>
>> a=range*(float)random()/(float)RAND_MAX;
>>
>> but I didn't likt the way of doing it, is there no other way ??
>
>The other way is to say "random()%(range - 1)" (assuming `range' is an
>int),  but that might yield less random results, as lower bits returned
>by RNGs are usually not-so-random.
>
>What's wrong with what you did in the first place, anyway?

Both method are indeed seen very often in published code, but there are both
not correct!!! That means that the original sequence is not evenly
distributed over the whole range of [0:Limit-1]. The reason is, that such an
arrangement is simply impossible if RAND_MAX is not divisible by 'range' and
this is very likely!
Though the effect lessens if you increase RAND_MAX it is not neglectible.I
would not recommend the above methods in a serious application.
One simple fix would be to iterate rand() until its result is in a range,
those length is divisible by 'range'.
For example:

  unsigned a,range=17;

  do
    a = rand();
  while (a < ((unsigned)RAND_MAX+1) % range); //be aware of overflow
  a%= range;

Hope i have helped.
Oliver Roese








- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019