Reputation: 31
How do I get the same random numbers in Python and Matlab?
For example, my Matlab code prints random integers of 1 and 2 with the given seed:
>> rng(1);
>> randi(2,1,10)
ans =
1 2 1 1 1 1 1 1 1 2
However, when I have the same seed using NumPy, I get a different order of random numbers:
np.random.seed(1)
np.random.randint(1,3,10)
array([2, 2, 1, 1, 2, 2, 2, 2, 2, 1])
Is there any way the two methods can produce the same order of random numbers?
Upvotes: 2
Views: 577
Reputation: 60504
As seen in this answer, it is possible to produce the same random stream of uniformly distributed numbers in both MATLAB and Python/NumPy. Both use the same MT19937 Mersenne Twister:
>> format long
>> rng(1)
>> rand(1,3)
ans =
0.417022004702574 0.720324493442158 0.000114374817345
>>> import numpy as np
>>> np.random.seed(1)
>>> np.random.rand(1,3)
array([[4.17022005e-01, 7.20324493e-01, 1.14374817e-04]])
So the difference we are seeing here is in how these numbers are converted into integers in the given range. But fortunately this is a trivial step that we can implement identically in both languages:
rng(1)
upper = 2;
lower = 1;
v = floor((rand(1,10) * (upper-lower+1)) + lower);
np.random.seed(1)
upper = 2;
lower = 1;
v = np.floor((np.random.rand(1,10) * (upper-lower+1)) + lower).astype(np.int64)
Note that this is not the best way to produce integers in a given range, this method is biased because the input random numbers can obtain only a set of discrete values, and these discrete values do not necessarily distribute uniformly within the set of output discrete values. Of course the effect is very small, and might not be important for your application. For more details on this, and a correct (but more complex) algorithm, see this anser.
Upvotes: 3