如何在 Python 中使用 scipy.integrate.quad 中的参数 epsabs?
How do I use parameter epsabs in scipy.integrate.quad in Python?
我正在尝试通过为 scipy.integrate.quad
指定参数 epsabs
来更精确地计算积分,假设我们正在积分函数 sin(x) / x^2 从 1e-16 到 1.0
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
integral = quad(integrand, 1e-16, 1.0)
这给了我们
(36.760078801255595, 0.01091187908038005)
为了使结果更精确,我们通过epsabs
指定绝对误差容限
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
integral = quad(integrand, 1e-16, 1.0, epsabs = 1e-4)
结果一模一样,误差还是0.0109那么大!我对参数 epsabs
的理解有误吗?我应该怎么做才能提高积分的精度?
根据 scipy 手册 quad function 有 limit
参数指定
An upper bound on the number of subintervals used in the adaptive algorithm.
默认情况下 limit
的值为 50。
你代码 return 警告信息
quadpack.py:364: IntegrationWarning: The maximum number of
subdivisions (50) has been achieved. If increasing the limit yields
no improvement it is advised to analyze the integrand in order to
determine the difficulties. If the position of a local difficulty
can be determined (singularity, discontinuity) one will probably
gain from splitting up the interval and calling the integrator on
the subranges. Perhaps a special-purpose integrator should be used.
warnings.warn(msg, IntegrationWarning)
您必须更改 limit
参数,即:
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
print(quad(integrand, 1e-16, 1.0, epsabs = 1e-4, limit=100))
输出:
(36.7600787611414, 3.635057215414274e-05)
输出中没有警告信息。细分数低于 100,quad
达到了要求的精度。
我正在尝试通过为 scipy.integrate.quad
指定参数 epsabs
来更精确地计算积分,假设我们正在积分函数 sin(x) / x^2 从 1e-16 到 1.0
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
integral = quad(integrand, 1e-16, 1.0)
这给了我们
(36.760078801255595, 0.01091187908038005)
为了使结果更精确,我们通过epsabs
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
integral = quad(integrand, 1e-16, 1.0, epsabs = 1e-4)
结果一模一样,误差还是0.0109那么大!我对参数 epsabs
的理解有误吗?我应该怎么做才能提高积分的精度?
根据 scipy 手册 quad function 有 limit
参数指定
An upper bound on the number of subintervals used in the adaptive algorithm.
默认情况下 limit
的值为 50。
你代码 return 警告信息
quadpack.py:364: IntegrationWarning: The maximum number of subdivisions (50) has been achieved. If increasing the limit yields no improvement it is advised to analyze the integrand in order to determine the difficulties. If the position of a local difficulty can be determined (singularity, discontinuity) one will probably gain from splitting up the interval and calling the integrator on the subranges. Perhaps a special-purpose integrator should be used.
warnings.warn(msg, IntegrationWarning)
您必须更改 limit
参数,即:
from scipy.integrate import quad
import numpy
integrand = lambda x: numpy.sin(x) / x ** 2
print(quad(integrand, 1e-16, 1.0, epsabs = 1e-4, limit=100))
输出:
(36.7600787611414, 3.635057215414274e-05)
输出中没有警告信息。细分数低于 100,quad
达到了要求的精度。