Default seed PRNG in Java

2019-02-18 11:56发布

问题:

I was wondering what the default seed for the PRNG* behind Math.random() in Java is. From what I understand the one in C is based upon the system clock. So is it similar in Java? Also, is the seed changed everytime Math.random() is called?

*PRNG = Pseudo Random Number Generator

回答1:

If you Read The Fine Manual it tells you

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random()

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

Following up with java.util.Random(), the documentation says

public Random()

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

The current implementation appears to be based on System.nanoTime() but could change and still be compliant with the documentation's contract.

As for changing the seed with every call, that's not how seeds work. PRNGs are seeded once, and then produce a sequence of values that evolve from that initial state. You shouldn't, and Java doesn't, keep re-seeding.



回答2:

You can always read the code.

Math.random() just uses an internal static Random object thats instantiated with no args...

       Random() {
90         this(seedUniquifier() ^ System.nanoTime());
91     }
92 
93     private static long More ...seedUniquifier() {
94         // L'Ecuyer, "Tables of Linear Congruential Generators of
95         // Different Sizes and Good Lattice Structure", 1999
96         for (;;) {
97             long current = seedUniquifier.get();
98             long next = current * 181783497276652981L;
99             if (seedUniquifier.compareAndSet(current, next))
100                return next;
101        }
102    }
103


回答3:

As you can see on documentation, the function uses a class called Random(), wich uses a 48-bit seed, and generate a uniform distribution.



标签: java random prng