Reach the same random numbers in numpy like matlab

I want to know how to create the same random (normal distribution) number in numpy, like in MATLAB.

As an example, when I do this in MATLAB

RandStream.setGlobalStream(RandStream('mt19937ar','seed',1));
rand
ans =
    0.417022004702574

Now I can reproduce this with numpy:

import numpy as np
np.random.seed(1)
np.random.rand()
0.417022004702574

This is good, but when I do it with a normal distribution, I get different numbers.

RandStream.setGlobalStream(RandStream('mt19937ar','seed',1));
randn
ans =
    -0.649013765191241

And with numpy

import numpy as np
np.random.seed(1)
np.random.randn()
1.6243453636632417

Both functions say in their documentation that they draw from the standard normal distribution, but give me different results. Any idea how I can configure my python / numpy to get the same numbers as MATLAB.

- : , . , , . .

+4
1

, matlab numpy ( - ).

, box-muller . python

import numpy as np

# Box-muller normal distribution, note needs pairs of random numbers as input
def randn_from_rand(rand):

    assert rand.size == 2

    #Use box-muller to get normally distributed random numbers
    randn = np.zeros(2)
    randn[0] = np.sqrt(-2.*np.log(rand[0]))*np.cos(2*np.pi*rand[1])
    randn[1] = np.sqrt(-2.*np.log(rand[0]))*np.sin(2*np.pi*rand[1])

    return randn


np.random.seed(1)
r = np.random.rand(2)
print(r, randn_from_rand(r))

,

(array([ 0.417022  ,  0.72032449]), array([-0.24517852, -1.29966152]))

matlab,

% Box-muller normal distribution, note needs pairs of random numbers as input
function randn = randn_from_rand(rand)

    %Use box-muller to get normally distributed random numbers
    randn(1) = sqrt(-2*log(rand(1)))*cos(2*pi*rand(2));
    randn(2) = sqrt(-2*log(rand(1)))*sin(2*pi*rand(2));

RandStream.setGlobalStream(RandStream('mt19937ar','seed',1));
r = [rand, rand]
rn = randn_from_rand(r)

,

r =
    0.4170    0.7203
rn =
   -0.2452   -1.2997

. , python,

import matplotlib.pyplot as plt

ra = []
np.random.seed(1)
for i in range(1000000):
    rand = np.random.rand(2)
    ra.append(randn_from_rand(rand))


plt.hist(np.array(ra).ravel(),100)
plt.show()

,

enter image description here

+1

Source: https://habr.com/ru/post/1648397/


All Articles