delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/05/07:31:47

Message-ID: <33969D57.5F83@pobox.oleane.com>
Date: Thu, 05 Jun 1997 13:04:55 +0200
From: Francois Charton <deef AT pobox DOT oleane DOT com>
Organization: CCMSA
MIME-Version: 1.0
To: Chris Croughton <crough45 AT amc DOT de>
CC: djgpp AT delorie DOT com
Subject: Re: Random numbers/George
References: <97Jun5.122135gmt+0100 DOT 16656 AT internet01 DOT amc DOT de>

Chris Croughton wrote:
> 
> Actually, for the most common use (rand() % n) they are not equally as
> good.  The problem with rand() is that the bottom bits are not at all
> random, in fact they are a fairly short sequence especially if 'n' is
> a power of 2 (i.e. extracting the bottom bits).  I believe it just
> alternates even and odd numbers, for instance.
> 

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

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). 

rand()%n may succeed if your rand() function is good, but you are taking 
chances with portability matters.

Francois

- Raw text -


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