scipy.integrate.quad在大范围内给出错误的结果 [英] scipy.integrate.quad gives wrong result on large ranges

查看:208
本文介绍了scipy.integrate.quad在大范围内给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对两个半"正态分布的总和进行积分.当我尝试在较小的范围内进行积分时,scipy.integrate.quad可以正常工作,但在较大的范围内进行积分时返回0.这是代码:

I am trying to integrate over the sum of two 'half' normal distributions. scipy.integrate.quad works fine when I try to integrate over a small range but returns 0 when I do it for large ranges. Here's the code:

mu1 = 0
mu2 = 0
std1 = 1
std2 = 1

def integral_fun(x):
    nor1 = 0.5 * ((1 / (np.sqrt(2 * np.pi) * std1)) * (np.e ** ((-(x-mu1) ** 2) / (2 * std1 **2))))
    nor2 = 0.5 * ((1 / (np.sqrt(2 * np.pi) * std2)) * (np.e ** ((-(x-mu2) ** 2) / (2 * std2 **2))))
    return nor1 + nor2


integrate.quad(integral_fun, -5, 5)
Out[54]: (0.9999994266968564, 8.668320228277793e-10)

integrate.quad(integral_fun, -10, 10)
Out[55]: (1.0000000000000002, 8.671029607900576e-10)

integrate.quad(integral_fun, -100000, 100000)
Out[56]: (0.0, 0.0)

为什么会这样?

推荐答案

此处的原因是,您的函数仅在集成区域的很小区域内达到非常强的峰值,而在其他所有区域实际上都为零,因此quad从未找到这个峰值,因此只能看到被积为零.

The reason here is that your function is only very strongly peaked in a very small region of your integration region and is effectively zero everywhere else, quad never finds this peak and thus only see's the integrand being zero.

由于在这种情况下,您知道峰的位置,因此合理地划分积分范围,以便您分别考虑峰周围的区域.

Since in this case you know where the peaks are, it would be reasonable to split the limits of the integration so that you consider the regions around the peaks separately.

为此,您可以使用points参数以一种有点混蛋的方式来强制quad分别考虑峰.

To do this you can use the points argument in a slightly bastardized way to force quad to consider the peaks separately.

In [3]: integrate.quad(integral_fun, -100000, 100000, points=[-10,10])
Out[3]: (1.0000000000000002, 8.671029607900576e-10)

这篇关于scipy.integrate.quad在大范围内给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆