delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/05/08:45:41

Sender: crough45 AT amc DOT de
Message-Id: <97Jun5.143235gmt+0100.16652@internet01.amc.de>
Date: Thu, 5 Jun 1997 13:36:05 +0100
From: Chris Croughton <crough45 AT amc DOT de>
Mime-Version: 1.0
To: deef AT pobox DOT oleane DOT com
Cc: djgpp AT delorie DOT com
Subject: Re: Random numbers/George

Francois Charton wrote:

> This is not the case with the rand() function from DJGPP 
> libc, but it may exist for other rand() functions. 

The DJGPP one is better than most (you're correct, it 
does avoid the odd/even trap) but as you say it's not 
portably true, and it does still have more randomness 
in some bits than in others.

> For this reason, I think it is always bad programming 
> practice to use (rand()%n), the good way to do it is 
> (rand()/(MAXRAND/n)), MAXRAND being the largest number 
> rand() can produce (the modulus in the case of a linear 
> congruential generator). 

As pointed out before, that will sometimes generate numbers
outside your range due to rounding.  For instance:

max. random value M = 65535
range of numbers  n = 10

M/n = 6553

65535 / 6553 = 10

so it can sometimes generate the number 10 which is outside 
the range 0-9.  That's fine if you combine it with George's 
algorithm (generata another number if the result is outside 
the wanted range), but not on its own.

OK, it's only (in the above case) 5 out of 65536 times, but
if you're using it to index an array you can guarantee those
cases will occur and cause a SEGV at exactly the wrong time.

Chris C

- Raw text -


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