delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/03/08/03:54:42

Message-ID: <3321274F.6266@pobox.oleane.com>
Date: Sat, 08 Mar 1997 09:46:07 +0100
From: Francois Charton <deef AT pobox DOT oleane DOT com>
Organization: CCMSA
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: a randomize function for DJGPP?
References: <5flbpp$m74 AT nr1 DOT ottawa DOT istar DOT net> <331FC0D1 DOT 1A26 AT cs DOT com> <E6oqJs DOT K2n AT boss DOT cs DOT ohiou DOT edu>

John M. Aldrich <fighteer AT cs DOT com> wrote:
>
>To get a random number from 0 to X - 1, use:
>
>    n = random( ) % X;
>
>Before everybody gets hysterical on me again, let me say in advance that
>the GNU random() RNG, unlike rand(), is guaranteed to be random in the
>lower bits, so you can use the mod operator safely.


Yes, but then you are taking chances about portability: rand() is an ANSI 
library function, and could be implemented in a less intelligent way on 
other systems or with other compilers... Actually, chances are high that 
is will be so: the ANSI comitee itself has published such an algorithm as 
a example, so many programmers will certainly copy it.

IMHO, it is better to use the divide than the mod operation: precalculate 
RAND_MAX/X, and do rand()/(RAND_MAX/X), it is as fast as the mod, a 
little less readable (if you are afraid about that, use a macro to make 
it clearer to readers of your code), and it is guaranteed to be portable. 
(It is a bit like the void main(void) vs int main(void) problem) the 
former is usable in many cases, but still not a good idea).

While we are at it, did anyone try some good random generator crash test 
suite (like the tests in Knuth for instance) on rand() and random()?

Francois

- Raw text -


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