当使用scipy.integrate.quad时,增加正函数的界线会减小积分!怎么解决呢?

问题描述

我正在使用scipy.integrate评估定积分。我编写了以下代码段,以评估概率密度函数(PDF)和累积分布函数(CDF),以评估PDF的CDF,如下所示:

inf = 10000

def f_normal(m,tau): #normal pdf with mean np.sqrt(m- 1/2) and var 1/pi
    tmp = 1/np.sqrt(np.pi) * np.exp(  -  ( tau - np.sqrt(m- 1/2) )**2   )
    return tmp

def F_normal(m,x): #integral of f_normal from -inf to x
    return integrate.quad(lambda tau: f_normal(m,tau),-inf,x)

但是当我评估时:

m=10    
print(f_normal(m,10))    
print(F_normal(m,inf))

(0.0,0.0)得到F_normal(m,inf),而我真的期望1.我不知道发生了什么。我也试图理解命令integrate.quad,因此得到了这些奇怪的值:增加边界会减小正函数PDF的定积分,因此没有任何意义:

integrate.quad(lambda tau: f_normal(m,-10,10)
Out[30]: (1.0,2.2977017217085778e-09)

integrate.quad(lambda tau: f_normal(m,-100,100)
Out[31]: (1.0,8.447041410391393e-09)

integrate.quad(lambda tau: f_normal(m,-1000,1000)
Out[32]: (0.9999934640807174,1.857441875165816e-09)

integrate.quad(lambda tau: f_normal(m,-10000,10000)
Out[33]: (5.659684283308144e-150,1.1253180602819657e-149)

integrate.quad(lambda tau: f_normal(m,100)
Out[34]: (0.0,0.0)

integrate.quad(lambda tau: f_normal(m,1000000)
Out[35]: (0.0,0.0)

我有点困惑:帮助表示赞赏!

解决方法

问题在于inf太大。您正在尝试使该功能失效,

enter image description here

但是您要发送给integrate.quad的是

enter image description here

正交例程不太可能在该值基本上不是0导致错误结果的任何地方对该函数进行采样。

幸运的是,使用np.inf,您可以告诉算法积分在一个无限区间内,并且在寻找函数的相关行为在哪里会更明智。这段代码给出了正确的积分:

def f_normal(m,tau): #normal pdf with mean np.sqrt(m- 1/2) and var 1/pi
    tmp = 1/np.sqrt(np.pi) * np.exp(  -  ( tau - np.sqrt(m- 1/2) )**2   )
    return tmp

def F_normal(m,x): #integral of f_normal from -inf to x
    return integrate.quad(lambda tau: f_normal(m,tau),-np.inf,x)

m=10    
print(f_normal(m,m-.5))    
print(F_normal(m,np.inf))

或者,您可以在函数不太接近0的位置附近合并一个较小的有限间隔。在这种情况下,中心(np.sqrt(m-1/2))加上或减去100是可靠的(原始长度20,000为太大):

def f_normal(m,np.sqrt(m- 1/2)-100,x)

m=10000
print(f_normal(m,np.sqrt(m- 1/2)+100))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...