Is it possible to reproduce randn() of MATLAB with NumPy?

前端 未结 3 624
广开言路
广开言路 2021-02-09 11:34

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 di

3条回答
  •  星月不相逢
    2021-02-09 12:12

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

    Note: I also placed this answer on this similar question: Comparing Matlab and Numpy code that uses random number generation

提交回复
热议问题