javarandomprng

Default seed PRNG in Java


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


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.