gpt4 book ai didi

java - 用于在两台机器上创建 java Random 的种子值相同

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:17 25 4
gpt4 key购买 nike

如果我在 java 程序中使用相同的随机种子值并在两台不同的机器上运行它,我会得到相同的一组数字吗?

例如

    long seed = 123L;//may be taken from some database or something
java.util.Random ran = new java.util.Random(seed);
int ret = 0;
for (int i= 0; i< 10; i++){
ret = ran.nextInt(1000);
System.out.println("ret="+ret);
}

我总是得到

ret=782
ret=450
ret=176
ret=789
ret=795
ret=657
ret=834
ret=837
ret=585
ret=453

如果我在我的电脑上多次运行这个程序,我会得到相同的一组数字..但假设有人设法获得我使用的 secret 种子值(通过猜测或从 secret 位置它存储在哪里)并在他的机器上运行这段代码,他会得到相同的一组数字吗?

最佳答案

是的,指定随机数生成方式的契约(Contract)在两种情况下都是相同的,因此如果给定相同的种子,它们将生成相同的数字序列。 Random 的实现必须使用规定的算法以确保情况如此。更准确的表述方式(来自相关文档)是:

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

关于java - 用于在两台机器上创建 java Random 的种子值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com