produce same array in matlab and python with randn

Jen*_*eto 1 python random matlab random-seed

Hello I'm trying to produce the same vector in python and matlab but I'm not able to get it. Someone knows how to do that?

My python code is:

np.random.seed(1337)
A = np.random.randn(1,3)
A = array([[-0.70318731, -0.49028236, -0.32181433]])
Run Code Online (Sandbox Code Playgroud)

My matlab code is:

rng(1337, 'twister');
A = randn(1,3)
A = -0.7832   -0.7012   -0.7178
Run Code Online (Sandbox Code Playgroud)

I would like to both give the same vector...

Cri*_*ngo 5

MATLAB 和 Python/NumPy,按照您的方式配置和使用,使用相同的伪随机数生成器。这个生成器产生相同的数字序列:

>> format long
>> rng(1337, 'twister');
>> rand(1,3)
ans =
   0.262024675015582   0.158683972154466   0.278126519494360
Run Code Online (Sandbox Code Playgroud)
>>> np.random.seed(1337)
>>> np.random.rand(1,3)
array([[0.26202468, 0.15868397, 0.27812652]])
Run Code Online (Sandbox Code Playgroud)

因此,似乎是从随机流中生成正态分布值的算法有所不同。有许多不同的算法可以从随机流中生成正态分布的值,并且 MATLAB 文档没有提到它使用的是哪一种。NumPy 确实提到了至少一种方法

用于生成 NumPy 法线的 Box-Muller 方法在Generator. 使用Generator正态分布或依赖于正态分布的任何其他分布(例如RandomState.gamma或 ),不可能重现精确的随机值RandomState.standard_t。如果您需要按位向后兼容的流,请使用RandomState.

简而言之,NumPy 有一个新的随机数系统 ( Generator),遗留系统仍然可用 ( RandomState)。这两个系统使用不同的算法将随机流转换为正态分布数:

>>> r = np.random.RandomState(1337)
>>> r.randn(1,3)                        # same as np.random.randn()
array([[-0.70318731, -0.49028236, -0.32181433]])
>>> g = np.random.Generator(np.random.MT19937(1337))
>>> g.normal(size=(1,3))
array([[-1.22574554, -0.45908464,  0.77301878]])
Run Code Online (Sandbox Code Playgroud)

r并且g这里都产生相同的随机流(使用具有相同种子的 MT19937 生成器),但不同的正态分布随机数。

我找不到Generator.normal.