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

前端 未结 3 620
广开言路
广开言路 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:03

    The user asked if it was possible to reproduce the output of randn() of Matlab, not rand. I have not been able to set the algorithm or seed to reproduce the exact number for randn(), but the solution below works for me.

    In Matlab: Generate your normal distributed random numbers as follows:

    rng(1);
    norminv(rand(1,5),0,1)
    ans = 
       -0.2095    0.5838   -3.6849   -0.5177   -1.0504
    

    In Python: Generate your normal distributed random numbers as follows:

    import numpy as np
    from scipy.stats import norm
    np.random.seed(1)
    norm.ppf(np.random.rand(1,5))
    array([[-0.2095,  0.5838, -3.6849, -0.5177,-1.0504]])
    

    It is quite convenient to have functions, which can reproduce equal random numbers, when moving from Matlab to Python or vice versa.

提交回复
热议问题