如何在一种语言中生成与另一种语言相同的随机数?

huangapple go评论59阅读模式
英文:

How to generate the same random numbers in one language as in another?

问题

我正在将Stata中的代码翻译成R。相同的随机种子在生成相同的输出时不起作用。我不确定在其他语言(Python、Java等)中是否也是如此。如何在不同语言中生成相同的随机数?

英文:

I am translating codes from Stata to R. The same random seed does not generate the same outputs. I am not sure if this is also the case in other languages (Python, Java etc.). How to generate identical random numbers in different languages?

答案1

得分: 3

R使用自己的初始化方法来生成Mersenne-Twister随机数(参见help("set.seed")),这与其他编程语言不同。确保使用相同的伪随机数生成器(PRNG)并避免自行实现不佳的方法,最简单的方式是在R和Stata之间进行接口操作,然后使用其中一个的PRNG。

然而,值得注意的是,要实现真正的可重复性,除非在完全相同的硬件和操作系统上使用完全相同的软件,否则是不可能的。因此,我不会花费精力尝试在不同的软件中实现相同的PRNG流。相反,我会生成这些数字,将其存储,并根据需要导入它们。

英文:

R uses its own initialization method for the Mersenne-Twister (see help("set.seed")), which differs from what other languages do. The easiest way to ensure the same PRNG is used (and to avoid implementing something subpar yourself), is simply interfacing R and Stata and using the PRNG from either of these.

However, it's worth keeping in mind that achieving true reproducibility is impossible unless you are using exactly the same software on exactly the same hardware and OS. Thus, I wouldn't spent effort on trying to achieve the same PRNG streams with different software. Instead I would generate these numbers, store them and import them as needed.

huangapple
  • 本文由 发表于 2020年7月29日 20:02:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63153166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定