Python Numpy随机数 - 不一致?

时间:2013-10-22 17:20:17

标签: python random numpy

我正在尝试在python中生成对数正态分布的随机数(用于以后的MC模拟),并且当参数稍大时我发现结果非常不一致。

下面我从Normals生成一系列LogNormals(然后使用Exp)并直接从LogNormals生成。 由此产生的手段是可以忍受的,但差异 - 非常不精确..这也适用于mu = 4,5,......

如果您重复运行以下代码几次 - 结果会有很大不同。

代码:

import numpy as np
mu = 10;
tmp1 = np.random.normal(loc=-mu, scale=np.sqrt(mu*2),size=1e7)
tmp1 = np.exp(tmp1)
print tmp1.mean(), tmp1.var()
tmp2 = np.random.lognormal(mean=-mu, sigma=np.sqrt(mu*2), size=1e7)
print tmp2.mean(), tmp2.var()
print 'True Mean:', np.exp(0), 'True Var:',(np.exp(mu*2)-1)

有任何建议如何解决这个问题? 我也在Wakari.io上试过这个 - 所以结果也一致

更新: 我已经采取了真实的'维基百科的均值和方差公式:https://en.wikipedia.org/wiki/Log-normal_distribution

结果快照: 1)

0.798301881219 57161.0894726
1.32976988569 2651578.69947
True Mean: 1.0 True Var: 485165194.41

2)

1.20346203176 315782.004309
0.967106664211 408888.403175
True Mean: 1.0 True Var: 485165194.41

3)最后一个n = 1e8随机数

1.17719369919 2821978.59163
0.913827160458 338931.343819
True Mean: 1.0 True Var: 485165194.41

2 个答案:

答案 0 :(得分:6)

即使您拥有较大的样本量,使用这些参数,估计的差异也会在不同的运行中发生巨大变化。这只是胖尾对数正态分布的本质。尝试多次运行np.exp(np.random.normal(...)).var()。您会看到类似于np.random.lognormal(...).var()的值。

无论如何,np.random.lognormal()只是作为np.exp(np.random.normal())实现的(嗯,C等价物)。

答案 1 :(得分:1)

好的,你刚刚构建了样本,并使用维基百科中的符号(第一部分,mu和sigma)以及你给出的例子:

from numpy import log, exp, sqrt
import numpy as np
mu = -10
scale = sqrt(2*10)   # scale is sigma, not variance
tmp1 = np.random.normal(loc=mu, scale=scale, size=1e8)
# Just checking
print tmp1.mean(), tmp1.std()
# 10.0011028634 4.47048010775, perfectly accurate
tmp1_exp = exp(tmp1)    # Not sensible to use the same name for two samples
# WIKIPEDIA NOTATION!
m = tmp1_exp.mean()     # until proven wrong, this is a meassure of the mean
v = tmp1_exp.var()  # again, until proven wrong, this is sigma**2
#Now, according to wikipedia
print "This: ", log(m**2/sqrt(v+m**2)), "should be similar to", mu
# I get This:  13.9983309499 should be similar to 10
print "And this:", sqrt(log(1+v/m**2)), "should be similar to", scale
# I get And this: 3.39421327037 should be similar to 4.472135955

所以,即使价值观并不完美,我也不会声称它们是完全错误的。