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

查看:44
本文介绍了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天全站免登陆