在numpy中实现与matlab

时间:2016-07-19 14:37:51

标签: matlab numpy

我想知道如何在numpy中生成相同的随机(正态分布)数字,就像在MATLAB中一样。

作为我在MATLAB中执行此操作的示例

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

现在我可以用numpy重现这个:

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

哪个好,但是当我使用正态分布执行此操作时,我会得到不同的数字。

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

并且有numpy

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

这两个函数在他们的文档中都说他们从标准的正态分布中得出,但给出了不同的结果。我知道如何调整我的python / numpy以获得与MATLAB相同的数字。

因为有人将此标记为副本: 正如我在开头和结尾所写的那样,这是正态分布。 因为我写的统一分布工作正常,这是关于正态分布。 链接线程中的所有答案都不能帮助正常分发。

1 个答案:

答案 0 :(得分: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