[ODE] dRandInt Crash Fix

Adam D. Moss adam at gimp.org
Wed Jun 22 10:57:07 MST 2005


Colin Bonstead wrote:
 > but at this point I don't really
> have time to investigate it any further, just getting it fixed is more 
> important.  Frankly, I'm not quite sure why dRandInt even needs to use 
> doubles.

It's trying to replicate this wisdom for its own private dRand
function (from the rand manpage):

        In Numerical Recipes in C: The Art of Scientific Computing
        (William  H.  Press, Brian P. Flannery, Saul A. Teukolsky,
        William T.  Vetterling;  New  York:  Cambridge  University
        Press,  1990 (1st ed, p. 207)), the following comments are
        made:
               "If you want to generate a random integer between 1
               and 10, you should always do it by

                      j=1+(int) (10.0*rand()/(RAND_MAX+1.0));

               and never by anything resembling

                      j=1+((int) (1000000.0*rand()) % 10);

               (which uses lower-order bits)."

 > Wouldn't just doing dRand() % n give you a number between 0
> and n? 

The distribution of dRand()'s random bits is very uneven; dRand()'s
results would have to be xor-folded before this can start to be
reliable, if not using the double-mult-trick.

Now, it looks like dRandInt() implements the above (1..n) recipe
incorrectly when adapting it for the (0..n-1) range.

I think that what it intends to do is:

int dRandInt (int n)
{
   double a = double(n-1) / 4294967296.0;
   return (int) (double(dRand()) * a);
}

--adam
-- 
Adam D. Moss   -   adam at gimp.org


More information about the ODE mailing list