Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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 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
104    private static final AtomicLong seedUniquifier = new AtomicLong(8682522807148012L);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top