2017-04-19 91 views
1

我一直在测试python中的一些函数(为了确保我很好地理解函数),我感到困惑,因为我有不同的结果。Python对数正态密度与解析解决方案不同

我正在测试stats.lognorm.pdf表格scipy。这个函数应该在下面的代码与x,shape, scale, loc = 0返回相同的结果:

val1 = (1/(x*shape*math.sqrt(2*math.pi)))*math.exp(-((math.log(x)-math.log(scale)**2)/(2*math.pow(shape,2)))) 
val2 = stats.lognorm.pdf(x, shape, 0, scale) #I expect that val1 == val2 

当我和一些细微的数字看起来好像没什么尝试。

x = 1 

scale = 1 #log(shape) = u => u=0 
shape = 0.25 

然后

val1 = 1.5957691216057308 

val2 = 1.59576912161 

,但是当我设置

shape = 0.8 
scale = 25.16 
x = 23 

结果差别很大

val1 = 6.33367993244142 
val2 = 0.0215455972263 

这究竟是为什么?我的代码有问题吗?

回答

1

您的val1是错误的,您在指数内部有**2,而不是在括号外。如果您尝试这样做:

val1 = (1/(x * shape * math.sqrt(2 * math.pi))) * math.exp(
     -(math.log(x) - math.log(scale))**2/(2 * math.pow(shape, 2))) 

一切都应按预期工作。

在这里可能需要吸取教训,了解为什么PEP8坚持正确地格式化和放置代码,因为它使发现这样的错误更容易。

+0

哎呀,我没有适当控制我的代码,谢谢。 – Bobesh

1

我想你看错文档

The probability density function for lognorm is: 

lognorm.pdf(x, s) = 1/(s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2) 

for x > 0, s > 0. 

lognorm takes s as a shape parameter. 

The probability density above is defined in the “standardized” form. To 
shift and/or scale the distribution use the loc and scale parameters. 
Specifically, lognorm.pdf(x, s, loc, scale) is identically equivalent to 
lognorm.pdf(y, s)/scale with y = (x - loc)/scale. 

如果我们按照步骤有:

x = 23. 
shape = 0.8 
scale = 25.16 
loc = 0. 


xp = (x - loc)/scale 
val1 = 1./(shape*xp*math.sqrt(2.*math.pi)) * math.exp(-1./2.*(math.log(xp)/shape)**2) 
val1 = (val1)/scale 

print(val1) 
val2 = stats.lognorm.pdf(x, shape, 0, scale) #I expect that val1 == val2 
print(val2) 

这给:

0.02154559722626566 
0.0215455972263