www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/08/30/03:26:15

Message-ID: <322697D8.6854@pobox.oleane.com>
Date: Fri, 30 Aug 1996 09:27:20 +0200
From: Francois Charton <deef AT pobox DOT oleane DOT com>
Organization: CCMSA
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re : rand() and random()

kagel AT quasar DOT bloomberg DOT com wrote:
> 
> just call random(), after using srandom() to seed the generator, modulo the
> result and add one.  The following will give a number between 1 and 50
> inclusive:
> 
> long num;
> 
> #define MAX_RAND 50
> 
> srandom( time(NULL) );
> 
> num = random();
> num = (num % MAX_RAND) + 1;
> 

IMHO, this is **not** a good idea : 

many random number generators use linear congruences :
they calculate one random number after the other by iterating formulae 
like :

next=a next + b (a and b being ints), 

in this formula :

if a is even, next is always the same as b (even if b is, odd if b is).
if b is odd, next follows the scheme even-odd-even-odd...

This is not a very random way of behaving... in particular, if n=2, your 
formula will generate "clockwork random numbers..."

Worse still, many implementations of rand() use the "ANSI rand()" 
formula, as above with

a=1103515245
b=12345

As you can see, these are both multiplies of 5, which means *any* random 
number out of this generator will be a multiply of 5... and that its 
parity will alternate even/odd... Even in simple applications, this can 
have disastrous effects...

As DJGPP have a slightly different way of proceeding, this effect does 
not appear here, *this does not make the above method better* : basically 
this is a problem with all linear congrunet method, and DJGPP use one of 
them...

There is an easy solution to this : divide, instead of using "%". It 
should be just the same in terms of speed (calculated by a DIV 
instruction when n is not a power of 2, and by AND or BITSHIFT when it 
is) and will guarantee your random numbers to be random.

Regards,
Francois

- Raw text -


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