If I use the same seed value for Random in a java program and run this on two different machines ,will I get the same set of numbers?
for example
long seed = 123L;//may be taken from some database or something
java.util.Random ran = new java.util.Random(seed);
int ret = 0;
for (int i= 0; i< 10; i++){
ret = ran.nextInt(1000);
System.out.println("ret="+ret);
}
I always get
ret=782
ret=450
ret=176
ret=789
ret=795
ret=657
ret=834
ret=837
ret=585
ret=453
If I run this multiple times on my computer,I would get the same set of numbers.. but suppose someone manages to get the secret seed value I used(by guessing or from the secret location where it was stored) and run this code on his machine,will he get the same set of numbers?
Yes, the contract specifying the way in which random numbers are generated is the same in both cases, so they'll produce the same sequence of numbers if given the same seed. Implementations of Random
must use prescribed algorithms in order to ensure that this is the case. A more precise way of putting it (from the relevant documentation) is:
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. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.
The JRE should generate the same sequence of random numbers, given that they use same seed, and algorithm are used. The Java documentation on Random 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.
The algorithms are used by all JRE implementations, too:
In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.
Yes, thats the point.
For example: In Minecraft you can obtain level seeds to initialize the Random Generator, and everyboy with this seed will get the same map.
If you read the JavaDoc, you'll see that next(int bits)
(and nextInt()
is just next(32)
) will update the seed to (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and return (int)(seed >>> (48 - bits))
. Thats always the same on any computer for the same seed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With