• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Two different Random generator but the same resulting random integers....

 
Ellen Zhao
Ranch Hand
Posts: 581
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two different random integers were needed in my program, I wrote a code segment like this:

I've checked that r1 and r2 do exist in different physical memory addresses, but the int1 and int2 were always the same.
The javadoc says:
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. ...
public Random()Creates a new random number generator. Its seed is initialized to a value based on the current time:
public Random() { this(System.currentTimeMillis()); }Two Random objects created within the same millisecond will have the same sequence of random numbers...

Were my r1 and r2 really created at the same time??? How can I believe it?
I've modified my code so that finally I got two different random integers:

Could anyone tell me why the first version didn't work? Thank you very much in advance.
Regards,
Ellen
[ September 12, 2003: Message edited by: Ellen Zhao ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The system clock can only measure time to a certain resolution. Apparently creating two Random objects takes less than one clock "tick"; this isn't really a surprise. The clock resolution on many systems is quite low; I believe it's 17 milliseconds on Windows, for example.
 
Ellen Zhao
Ranch Hand
Posts: 581
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest,
according to your reply, I think this:

would also work. (haven't tried out yet...)
Thank you very much for your immediate reply.

Regards,
Ellen
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm at a loss as to why two generators were needed in the first place. Why not just call nextInt() twice to get two random numbers?

The above does the same as the original code posted.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic