[ODE] dRandInt Crash Fix

Jaroslav Sinecky jsinecky at tiscali.cz
Wed Jun 22 15:58:20 MST 2005


You're right, dRandInt uses the formula from Numerical Recipes book. But I
think it uses it correctly, I don't see the error and still don't see how
integer greater than n-1 could have come out of it ...

 return (int) ( (double)(n) * (double)dRand() / 4294967296.0 )

Because (double)dRand()/((double)RAND_MAX+1.0) should never reach 1.0 and
conversion to int just truncates at the floating point.
And this number 4294967296.0 should really be RAND_MAX+1 in our case
(0xffffffff + 1).

Maybe because some flointing point precision error in double division??

I was so worried, that I created a very simple test where I substitute
dRand() for its possibly max value...

int dRandInt (int n)
{
  double a = double(n) / 4294967296.0;
  int ret = (int) (double(0xffffffff) * a);
  return ret;
}

int _main(int argc, _CHAR* argv[])
{
	int i;
	i = dRandInt(1);
	i = dRandInt(1000);
	i = dRandInt(100000);
	i = dRandInt(2147483647); // max possible signed int value

	return 0;
}

And it works without problem!
Maybe on some other platform/compiler will not?


I have no neurona left to figure how your xor-folding method works, but did
you try it? Do you think It can be faster then the original version? (on pc
that has hw double support)

Cheers!
Jaroslav



More information about the ODE mailing list