Default seed PRNG in Java

亡梦爱人 提交于 2019-12-01 07:16:51

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.

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!