Random number with seed

Link: link text

I can't figure out the following line, can someone provide me an example for the statement below?

If two instances of Random are created with the same seed, and for each of them the same sequence of method calls is made, they will generate and return identical sequences of numbers

+5
source share
6 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 instances Randomwill always have the same output, no matter how often you run it, no matter which platform or version of Java you use:

30 - 30
234785527 - 234785527
0.6832234717598454 - 0.6832234717598454
5694868678511409995 - 5694868678511409995
+11
source

. Random Random, , , .

- , , . .

+8

Random ( ), , . , , (, seed). - , 2 .

+3

, () . , , , .

, , SecureRandom.

. , wikipedia .

+2

, Random (, ) , , . , .

, , , : , , - , , . , . , () .

+1

Random / ; : http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter04/javaRandNums.html

Ruby:

class LCG; def initialize(seed=Time.now.to_i, a=2416, b=374441, m=1771075); @x, @a, @b, @m = seed % m, a, b, m; end; def next(); @x = (@a * @x + @b) % @m; end; end

irb(main):004:0> time = Time.now.to_i
=> 1282908389

irb(main):005:0> r = LCG.new(time)
=> #<LCG:0x0000010094f578 @x=650089, @a=2416, @b=374441, @m=1771075>
irb(main):006:0> r.next
=> 45940
irb(main):007:0> r.next
=> 1558831
irb(main):008:0> r.next
=> 1204687
irb(main):009:0> f = LCG.new(time)
=> #<LCG:0x0000010084cb28 @x=650089, @a=2416, @b=374441, @m=1771075>
irb(main):010:0> f.next
=> 45940
irb(main):011:0> f.next
=> 1558831
irb(main):012:0> f.next
=> 1204687

a/b/m, . "" , . ; , , .

0

All Articles