views:

95

answers:

1

Hi,

I wonder if it is possible to exactly reproduce the whole sequence of randn() of MATLAB with NumPy. I coded my own routine with Python/Numpy, and it is giving me a little bit different results from the MATLAB code somebody else did, and I am having hard time finding out where it is coming from because of different random draws.

I have found the numpy random.seed value which produces the same number for the first draw, but from the second draw and on, it is completely different. I'm drawing multivariate normal for like 20,000 times so I don't want to just save the matlab draws and read it in Python. If there is any other way I guess I have to do that. Please let me know.

-Joon

A: 

If you set the random number generator to the same seed, it will theoretically create the same numbers, ie in matlab. I am not quite sure how to best do it, but this seems to work, in matlab do:

rand('twister', 5489)

and corresponding in numy:

np.random.seed(5489)

To (re)initalize your random number generators. This gives for me the same numbers for rand() and np.random.random(), however not for randn, I am not sure if there is an easy method for that.

With newer matlab versions you can probably set up a RandStream with the same properties as numpy, for older you can reproduce numpy's randn in matlab (or vice versa). Numpy uses the polar form to create the uniform numbers from np.random.random() (the second algorithm given here: http://www.taygeta.com/random/gaussian.html). You could just write that algorithm in matlab to create the same randn numbers as numpy does from the rand function in matlab.

If you don't need a huge amount of random numbers, just save them in a .mat and read them from scipy.io though...

Sebastian
Thank you very much for your answer. I will definitely try it.
joon