Wednesday, October 29, 2008

Getting Fooled By Randomness



Reactions 

I ended up spending last one hour in debugging a program which runs perfectly while debugging but does not work as expected; when I run it normally. Bizarre...

Well, problem was the way in which I was generating random numbers. Look at the following snippet.


Random randomGen = new Random(System.currentTimeMillis());

Looks very simple and straightforward. But this line was part of a function. Which was structured as



fun()
{
for 1 to 1000
doRandom()
}
...

doRandom()
{
Random randomGen = new Random(System.currentTimeMillis());
number = randomGen.nextInt();
...
}


Has anyone reading it, figured out the problem with above code and why it will work fine while debugging?

If you have. Kudos.

The problem here is seed I am using i.e. System.currentTimeMillis().
  1. This seed will remain same for next 1/1000th of a second
  2. That's lots of time for a computer
  3. While debugging, every break point I place will result in delay and hence will lead to generation of different seed
Obvious solution is to make randomGen a class level variable. Modified code is like below



private Random _randomGen = new Random(System.currentTimeMillis());

...

doRandom()
{
number = _randomGen.nextInt();
...
}

2 comments:

Kashyap said...

This is a Heisen-bug

Anonymous said...

It is remarkable, this very valuable message