Reputation: 512
I am trying to reproduce the C++ code into Python 3.6, but the sequence of pseudo random numbers is different in each implementation. The seed are the same on both implementation and as far as I know, both use Mersenne Twister algorithm.
What am I doing wrong?
REMEMBER1: Both codes uses the SAME seed
REMEMBER2: As far as I know, both code uses functions that implemente the SAME algorithm (Mersenne Twister).
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:
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. That is why I use 61 on C++ code, but 62 on Python code.
Upvotes: 3
Views: 1172
Reputation: 32878
You should note that C++'s standard library distributions, including std::uniform_int_distribution
, use implementation-defined algorithms. 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. (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.
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. (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.)
Upvotes: 4
Reputation: 16184
There isn't one unique way of getting from a RNG to a single bounded int. See for example:
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.
Upvotes: 1