Achieve same random numbers in numpy as matlab -
i want know how generate same random (normal distribution) numbers in numpy in matlab.
as example when in matlab
randstream.setglobalstream(randstream('mt19937ar','seed',1)); rand ans = 0.417022004702574
now can reproduce numpy:
import numpy np np.random.seed(1) np.random.rand() 0.417022004702574
which nice, when normal distribution different numbers.
randstream.setglobalstream(randstream('mt19937ar','seed',1)); randn ans = -0.649013765191241
and numpy
import numpy np np.random.seed(1) np.random.randn() 1.6243453636632417
both functions in documentation draw standard normal distribution, yet give me different results. idea how can adjust python/numpy same numbers matlab.
because marked duplicate: normal distribution, wrote in beginning , end. wrote uniform distribution works fine, normal distribution. none of answers in linked thread normal distribution.
my guess matlab , numpy may use different methods normal distribution of random numbers (which obtained uniform numbers in way).
you can avoid problem writing box-muller method generate random numbers yourself. python,
import numpy np # box-muller normal distribution, note needs pairs of random numbers input def randn_from_rand(rand): assert rand.size == 2 #use box-muller 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))
which gives,
(array([ 0.417022 , 0.72032449]), array([-0.24517852, -1.29966152]))
and matlab,
% box-muller normal distribution, note needs pairs of random numbers input function randn = randn_from_rand(rand) %use box-muller 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));
which call with
randstream.setglobalstream(randstream('mt19937ar','seed',1)); r = [rand, rand] rn = randn_from_rand(r)
with answer,
r = 0.4170 0.7203 rn = -0.2452 -1.2997
note, can check output distributed, python,
import matplotlib.pyplot plt ra = [] np.random.seed(1) in range(1000000): rand = np.random.rand(2) ra.append(randn_from_rand(rand)) plt.hist(np.array(ra).ravel(),100) plt.show()
which gives,
Comments
Post a Comment