Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number with seed

Tags:

java

Reference: link text

i cannot understand the following line , can anybody provide me some example for the below statement?

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

like image 628
Lalchand Avatar asked Aug 27 '10 11:08

Lalchand


1 Answers

Since you asked for an example:

import java.util.Random;
public class RandomTest {
    public static void main(String[] s) {
        Random rnd1 = new Random(42);
        Random rnd2 = new Random(42);

        System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
        System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
        System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
        System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
    }
}

Both Random instances will always have the same output, no matter how often you run it, no matter what platform or what Java version you use:

30 - 30
234785527 - 234785527
0.6832234717598454 - 0.6832234717598454
5694868678511409995 - 5694868678511409995
like image 58
Michael Borgwardt Avatar answered Oct 27 '22 22:10

Michael Borgwardt