www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/09/26/09:52:13

Date: Mon, 26 Sep 94 08:24:23 EDT
To: roalz AT varano DOT ing DOT unico DOT it
From: richard DOT young AT clark DOT dgim DOT doc DOT ca (Richard Young)
Subject: Re: Problem with rand() (fwd)
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu

>> It seems that rand() returns alternately an even and an odd number
>>    result += ((rand() % _sides) + 1);
>
>It is not uncommon to find inadequate pseudorandom generators.  One thing
>which may help when generating a small number from a random value is to make
>the number depend on the high order bits returned by rand().  Right shifting
>as many bits as possible before doing the modulo operation will probably work.


The book "Numerical Recipies" and its counterpart "Numerical Recipies in C" 
published by the Cambridge University Press go to great length describing 
random number generators.  They emphasize that system supplied random number 
generators should be used with great caution.  The authors also confirm what 
Mr.Babcock has stated: that many such system generated rand() functions 
often have their lower order (least significant bits) much less random than 
their higher order (most significant bits).  

For your application, they recommend the following:

        roll += int(rand()*_sides) + 1;

This implementation is also attractive because it does not involve a divide 
(the %) and therefore should be somewhat faster.

However, they recommend that if you want to develop software that is 
portable and behaves the same from machine to machine, you should implement 
your own rand() function.  They give a number of algorithms to choose from.  

Their chapter on random number generators is well worth reading.  The 
authors are W.H.Press, B.P.Flannery, S.A.Teukolsky and W.T.Vetterling.  The 
C version of the book also comes with a diskette and source code for many 
mathematical functions such as the rand() functions.

Happy randomizing!

Richard Young,
Signal Processing Engineer,
Communications Research Centre,
Ottawa, Canada.


- Raw text -


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