Generating a random double

jhunt
08-17-2009, 07:17 AM
Hello, I'm attempting to generate a random double, but I'm having an issue.

Here is the forumla I am using to generate the double:

dblTemp = Int((dblUBound - dblLBound + 1) * Rnd + dblLBound)

A test case is failing, where dblUbound = 4294967295 and dblLBound = 0. In this case the above forumla reliably returns a double where the least signifigant byte is zero.

In the routine that tests for unusual patterns in the random numbers, I have:

dblTemp - (fix(dblTemp / 256) * 256)

to display the LSB (since MOD doesn't work with doubles). This formula passes the a unit test properly.

If I use this formula to evaulate the numbers returned (or any forumla) the LSB is zero.

Even if I break it down further:

dblTemp = dblUBound * Rnd

Running it through my MOD forumla relaibly produces an LSB of 255, and of course a decimal component.

So, just a sanity check here.. is somthing in my math very wrong, or is VB failing ye olde basic mathe (or ye olde randome number generation)

Thanks!

kassyopeia
08-17-2009, 08:10 AM
I think it comes down to granularity in the RNG. Rnd returns a Single, which gives you something like 24 significant bits. You're then multiplying by 2^32and converting to a Long, at which point you will already have clumping - not all integer values in the range will be produced, instead there will be a step size on the order of 100. Finally, you're assigning that Long to a Double, which has something like 53 significant bits. And since you're casting from an integer value, the unused bits should be all zero. Thus, I'd expect the three LSBs to all be zero, not just the final one.

The solution is to use Rnd more than once in the generator expression. To homogeneously span the Long value space, you need to use it at least twice. But even then, casting to Double should leave you with the two LSBs being zero, so if that is a problem, there seems to be a fundamental and not just a technical flaw in your approach, if I'm not mistaken.

Hope I didn't completely misunderstand the issue... :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum