delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/05/18/06:41:34

Date: Tue, 18 May 1999 13:39:08 +0300 (IDT)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: Dlanor Blytkerchan <dlanor AT dds DOT nl>
cc: djgpp AT delorie DOT com
Subject: Re: ** Random error **
In-Reply-To: <l03130304b364ec5e3186@[145.98.116.109]>
Message-ID: <Pine.SUN.3.91.990518133848.24330K-100000@is>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

On Sun, 16 May 1999, Dlanor Blytkerchan wrote:

> #define rnd(x,y) ((random()/RAND_MAX)*(y-x) + x);

Beware: the division by RAND_MAX is done in integer, and since
RAND_MAX is larger than almost any int, random()/RAND_MAX will yield
zero most of the time--not a random value at all.

If you want to avoid that, convert the value returned by random() to a
double.

(Also, the semi-colon at the end of the macro definition is evil;
don't use that.)

For simple applications, this should be good enough (UNTESTED!):

  #define rnd(x,y) (random()%(y-x) + x)

> NB: sometimes, using rand() is recommended over using random(). Why is not
> entirly clear, look it up in libc.

The only reason is portability: `rand' is ANSI while `random' is not.
Most DOS/Windows compilers don't provide `random' at all, while `rand'
is always there.

- Raw text -


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