JCV
JCV

Reputation: 515

produce same array in matlab and python with randn

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]])

My matlab code is:

rng(1337, 'twister');
A = randn(1,3)
A = -0.7832   -0.7012   -0.7178

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

Upvotes: 1

Views: 1308

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

Both MATLAB and Python/NumPy, configured and used the way you do, use the same pseudo-random number generator. This generator produces the same sequence of numbers:

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

So it seems that it is the algorithm that produces normally distributed values from the random stream that is different. There are many different algorithms to produce normally-distributed values from a random stream, and the MATLAB documentation doesn't mention which one it uses. NumPy does mention at least one method:

The Box-Muller method used to produce NumPy’s normals is no longer available in Generator. It is not possible to reproduce the exact random values using Generator for the normal distribution or any other distribution that relies on the normal such as the RandomState.gamma or RandomState.standard_t. If you require bitwise backward compatible streams, use RandomState.

In short, NumPy has a new system for random numbers (Generator), the legacy system is still available (RandomState). These two systems use a different algorithm for converting a random stream into normally distributed numbers:

>>> 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]])

r and g here both produce the same random stream (using the MT19937 generator with the same seed), but different normally distributed random numbers.

I cannot find which algorithm is used by Generator.normal.

Upvotes: 5

Related Questions