具有不同種子的Java隨機實例是否真的產生不同的序列,或者它們是否在相同序列的不同位置開始?

[英]Do Java Random instances with different seeds really produce different sequences, or do they start at different places in the same sequence?


Imagine instantiating two Randoms with different seeds, rA and rB. See what the first integer generated by rA is. Then call nextInt() on rB until you get the same integer.

想象一下,使用不同的種子rA和rB實例化兩個Randoms。看看rA生成的第一個整數是什么。然后在rB上調用nextInt(),直到得到相同的整數。

groovy:000> rA = new Random()
===> java.util.Random@463b4ac8
groovy:000> rB = new Random(1)
===> java.util.Random@5644dc81
groovy:000> rA_0 = rA.nextInt()
===> -1458003306
groovy:000> rB_0 = rB.nextInt()
===> -1155869325
groovy:000> for (int rB_n = rB.nextInt(); rB_n != rA_0; rB_n = rB.nextInt());
===> null

Is it possible that the two instances are now "synced up," so to speak, such that they will produce the same sequence of integers going forward indefinitely?

兩個實例現在是否可能“同步”,可以這么說,它們將產生相同的整數序列無限期地前進?

groovy:000> rA.nextInt()
===> 1701960179
groovy:000> rB.nextInt()
===> 1760857409
groovy:000> for (int rB_n = rB.nextInt(); rB_n != rA_0; rB_n = rB.nextInt());
===> null
groovy:000> rB.nextInt()
===> 614305687

The limited experiment shown does not discover such a collision of sequences, but it's hard to know if such a collision could be found.

所示的有限實驗沒有發現序列的這種碰撞,但很難知道是否可以找到這種碰撞。

To rephrase the question, are we working with one very long sequence, and the seed determines where on that sequence we start, or can Random instances with different seeds be depended on to actually produce entirely different sequences of numbers? Or worse, do some seeds share sequences? (Or does it depend on which sea shore Sally sells sea shells on?)

為了重新解釋這個問題,我們是否使用了一個非常長的序列,種子確定了我們開始的序列的位置,或者可以依賴於具有不同種子的隨機實例來實際產生完全不同的數字序列?或者更糟糕的是,做一些種子共享序列? (或者它取決於Sally在哪個海岸上銷售海貝殼?)

1 个解决方案

#1


2  

Java Random.next() (which underlies all public nextX() methods) is contractually obliged to follow the following LCG equation:

Java Random.next()(它是所有公共nextX()方法的基礎)在合同上有義務遵循以下LCG方程:

(x * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)

Thus given a current state (x), the next state is entirely determined.

因此,給定當前狀態(x),完全確定下一狀態。

So assuming that this is a "full-cycle" LCG (i.e. it iterates over all possible values), then it must be the case that rB eventually reaches the starting state of rA. At that point, its output sequence will match that of rA.

因此,假設這是一個“全周期”LCG(即它迭代所有可能的值),那么必須是rB最終達到rA的起始狀態的情況。此時,其輸出序列將與rA的輸出序列匹配。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/09/72fbe0457edaa9882d69c96cff52bef5.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com