[英]How do I reproduce the same random integer array in matlab and python?
How do I get the same random numbers in Python and Matlab?如何在 Python 和 Matlab 中获得相同的随机数?
For example, my Matlab code prints random integers of 1 and 2 with the given seed:例如,我的 Matlab 代码使用给定的种子打印随机整数 1 和 2:
>> 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:但是,当我使用 NumPy 拥有相同的种子时,我会得到不同顺序的随机数:
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?这两种方法有什么办法可以产生相同顺序的随机数吗?
As seen in this answer , it is possible to produce the same random stream of uniformly distributed numbers in both MATLAB and Python/NumPy.正如在这个答案中看到的那样,可以在 MATLAB 和 Python/NumPy 中产生相同的随机 stream 均匀分布的数字。 Both use the same MT19937 Mersenne Twister:
两者都使用相同的 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.请注意,这不是产生给定范围内整数的最佳方法,这种方法是有偏差的,因为输入的随机数只能获得一组离散值,而这些离散值不一定均匀分布在 output 离散值集合内. 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 .
有关这方面的更多详细信息以及正确(但更复杂)的算法,请参阅此 anser 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.