Python Numpy随机数不一致?

2024-10-02 20:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面我将从法线(然后使用Exp)和直接从LogNormals生成一系列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)

有什么建议吗? 我也试过这个瓦卡里.io-所以结果也是一致的

更新: 我从Wikipedia得到了“真实”的均值和方差公式:https://en.wikipedia.org/wiki/Log-normal_distribution

结果快照: (一)

^{pr2}$

(二)

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

Tags: 代码truevarnprandomsqrtmeanprint
2条回答

好的,因为您刚刚构建了示例,并使用了wikipedia中的符号(第一节,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

所以,即使这些值并不完全完美,我也不认为它们是完全错误的。在

即使你有很大的样本量,有了这些参数,估计的方差也会在不同的运行中发生巨大的变化。这就是厚尾对数正态分布的本质。尝试多次运行np.exp(np.random.normal(...)).var()。您将看到类似于np.random.lognormal(...).var()的值摆动。在

在任何情况下,np.random.lognormal()只是实现为np.exp(np.random.normal())(好吧,相当于C)。在

相关问题 更多 >