Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - Comparing Matlab and Numpy code that uses random number generation

Is there some way to make the random number generator in numpy generate the same random numbers as in Matlab, given the same seed?

I tried the following in Matlab:

>> rng(1);
>> randn(2, 2)

ans =

    0.9794   -0.5484
   -0.2656   -0.0963

And the following in iPython with Numpy:

In [21]: import numpy as np
In [22]: np.random.seed(1)
In [23]: np.random.randn(2, 2)
Out[23]: 
array([[ 1.624, -0.612],
       [-0.528, -1.073]])

Values in both the arrays are different.

Or could someone suggest a good idea to compare two implementations of the same algorithm in Matlab and Python that uses random number generation.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just wanted to further clarify on using the twister/seeding method: MATLAB and numpy generate the same sequence using this seeding but will fill them out in matrices differently.

MATLAB fills out a matrix down columns, while python goes down rows. So in order to get the same matrices in both, you have to transpose:

MATLAB:

rand('twister', 1337);
A = rand(3,5)
A = 
 Columns 1 through 2
   0.262024675015582   0.459316887214567
   0.158683972154466   0.321000540520167
   0.278126519494360   0.518392820597537
  Columns 3 through 4
   0.261942925565145   0.115274226683149
   0.976085284877434   0.386275068634359
   0.732814552690482   0.628501179539712
  Column 5
   0.125057926335599
   0.983548605143641
   0.443224868645128

python:

import numpy as np
np.random.seed(1337)
A = np.random.random((5,3))
A.T
array([[ 0.26202468,  0.45931689,  0.26194293,  0.11527423,  0.12505793],
       [ 0.15868397,  0.32100054,  0.97608528,  0.38627507,  0.98354861],
       [ 0.27812652,  0.51839282,  0.73281455,  0.62850118,  0.44322487]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...