Wednesday, October 03, 2007

Stupid Me, System.currentTimeMills()

for(int j=0;j<100;j++)
{
    java.util.Random rnd = new java.util.Random(System.currentTimeMillis());
    for(int i=0;i<100;i++)
    {
        System.out.print(rnd.nextInt(10)+"");
    }
    System.out.println();
}

please don't expect the above program to give 100 different sets of 100 random numbers, there will be repetitions like anything. why?
First: for a particular seed a Random number generator should give same set of numbers, when ever it is run,
Second: our computers are fast enough to finish execution in micro seconds

so the generation of 100 numbers takes few micro seconds and the System.currentTimeMills() has resolution in milliseconds so, a week of stupid searching and debugging, here is a post.

how to fix it:-
use new Random(); forget about seed, this produces 100 different sets of 100 random numbers.

Blogged with Flock

No comments: