java伪随机数跨系统和版本的再现性?

发布于 2025-01-02 06:51:16 字数 391 浏览 3 评论 0原文

我需要在给定初始整数参数的情况下生成伪随机数的受控序列。为此,我使用标准 Java Random 类,由整数参数作为种子。我想确保在可预见的未来(以及更多!)跨系统(操作系统,还有 Java/JDK 版本)生成相同的序列。

总之:Java 是否确保其伪随机数生成器在实现版本之间的可重复性/可移植性?

注意:我已经问过 Python 完全相同的问题。后来由于其他原因,我将实现语言更改为 Java。

I need to generate a controlled sequence of pseudo-random numbers, given an initial integer parameter. For that I'm using the standard Java Random class, seeded by an integer parameter. I'd like to make sure that I will generate the same sequence across systems (Operating system, but also Java/JDK version), in the foreseeable future (and more!).

In summary: Does Java ensure the reproducibility / portability of it's pseudo-random number generator across implementation and versions?

Note: I've asked the exact same question for Python. I since changed the implementation language to Java but for other reasons.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合约呢 2025-01-09 06:51:16

是的。

javadoc 解释:

此类的实例用于生成伪随机数流。该类使用 48 位种子,并使用线性同余公式对其进行修改。 (参见 Donald Knuth,《计算机编程的艺术》,第 2 卷,第 3.2.1 节。)

如果使用相同的种子创建 Random 的两个实例,并且对每个实例进行相同的方法调用序列,则它们将生成并返回相同的数字序列。 为了保证这个属性,Random类指定了特定的算法。为了 Java 代码的绝对可移植性,Java 实现必须使用此处所示的 Random 类的所有算法。 但是,Random 类 的子类可以使用其他算法,只要它们遵守所有方法的通用契约即可。

Yes.

The javadoc explains:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文