[英]Different pseudo random numbers between C++ and Python implementations
I am trying to reproduce the C++ code into Python 3.6, but the sequence of pseudo random numbers is different in each implementation. 我试图将C ++代码重现到Python 3.6中,但是伪随机数的顺序在每个实现中都不同。 The seed are the same on both implementation and as far as I know, both use Mersenne Twister algorithm.
种子在两个实现上都是相同的,据我所知,都使用Mersenne Twister算法。
What am I doing wrong? 我究竟做错了什么?
REMEMBER1: Both codes uses the SAME seed 记住1:两种代码都使用相同的种子
REMEMBER2: As far as I know, both code uses functions that implemente the SAME algorithm (Mersenne Twister). 记住2:据我所知,两个代码都使用实现SAME算法的功能(Mersenne Twister)。
C++: C ++:
#include <random>
#include <iostream>
int main(int argc, char* argv[])
{
std::mt19937 gen(2);
std::uniform_int_distribution<> dis(0, 61);
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
return 0;
}
Python 3.6: Python 3.6:
import numpy as np
rng = np.random.RandomState(2)
for i in range(10):
print(str(rng.randint(0, 62)))
Note: randint
has an exclusive upper bound. 注意:
randint
有一个专用上限。 That is why I use 61 on C++ code, but 62 on Python code. 这就是为什么我在C ++代码上使用61,而在Python代码上使用62的原因。
You should note that C++'s standard library distributions, including std::uniform_int_distribution
, use implementation-defined algorithms. 您应该注意,C ++的标准库发行版(包括
std::uniform_int_distribution
)使用实现定义的算法。 In other words, these implementations may change depending on which C++ library implementation you choose, and those libraries may change those algorithms in the future. 换句话说,这些实现可能会根据您选择的C ++库实现而改变,并且这些库将来可能会更改这些算法。 (This is in contrast to C++'s random engine classes, such as
std::mt19937
, which do guarantee returning the same pseudorandom values from the same seed.) See also this answer . (这与C ++的随机引擎类(例如
std::mt19937
)形成std::mt19937
,后者确实保证从同一种子返回相同的伪随机值。)另请参std::mt19937
答案 。
Your best course of action is to implement or find a stable implementation of an RNG algorithm (such as an algorithm I describe in my article ) and implement methods to transform the random numbers they deliver. 最好的做法是实现或找到RNG算法(例如我在本文中描述的算法)的稳定实现,并实现转换其传递的随机数的方法。 (There are certain things to keep in mind when choosing an RNG for a particular application; the first article I linked here has more information.)
(在为特定应用程序选择RNG时要牢记某些事情;我在此处链接的第一篇文章提供了更多信息。)
There isn't one unique way of getting from a RNG to a single bounded int. 从RNG到单个有界int没有唯一的方法。 See for example:
参见例如:
http://www.pcg-random.org/posts/bounded-rands.html http://www.pcg-random.org/posts/bounded-rands.html
Which has several versions. 里面有几个版本。 Note that C++ and Python take different options here, hence you'll get a different sequence from the "same" RNG and seed.
请注意,C ++和Python在这里采用不同的选项,因此您将获得与“相同” RNG和种子不同的序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.