Friday, November 25, 2005

Visual Basic RND issues, take 2

I talked about this a few months ago in Visual Basic Rnd() function tricks and traps, where I discovered that I wasn't getting a full 32bits of randomness out of VB's Rnd() function in my VBScript/Visual Basic pages. At the time, I thought it was simply due to Rnd() returning a 32bit IEEE floating point value which really only has 30bits of data.

In reality, the situation is even worse:

PRNG (Pseudo Random Number Generator) By Michael Meelis
Microsoft Visual Basic: Pseudo Random Number Generator
Using and Creating Cryptographic-Quality Random Numbers By Jon Callas
True random number generators

VB's Rnd() function only provides 24bits of randomness. After the 2^24th sample, it starts repeating. (See INFO: How Visual Basic Generates Pseudo-Random Numbers for the RND Function.)

Randomize() just contributes to the problem. See An Examination of Visual Basic's Random Number Generation By Mark Hutchinson and notice that calling Randomize() is based on the time of the day and only provides around 2^16 different starting points within the 2^24 stream. So if you're calling Randomize() before every Rnd(), you're only getting 16bits of randomness. (It's actually worse, because you'll get identical starting points at the same time of day.)

No comments: