[ODE] dRandInt Crash Fix

Jon Watte (ODE) hplus-ode at mindcontrol.org
Wed Jun 22 10:47:49 MST 2005


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

That doesn't look right. You'll never hit your n-1 value that way, 
because the output of dRand() will always be strictly less than 4294967296.

Assuming dRand() returns a value between 0 and 4294967295, inclusive, 
then the following formulation SHOULD correctly return values between 0 
and (n-1), inclusive:

int dRandInt( int n )
{
   double a = double(n) / 4294967296.0;
   double dr = double( dRand() );
   assert( dr >= 0 && dr < 4294967296.0 );
   return (int) floor( dr * a );
}

Now, if dRand() returns negative values (rather than unsigned int), 
you'd be in trouble.

Cheers,

			/ h+




More information about the ODE mailing list