如何使用数值方法近似积分的解

时间:2019-04-20 08:56:44

标签: python numerical-methods numerical-integration

我有以下积分(更多详细信息:https://math.stackexchange.com/questions/3193669/how-to-evaluate-the-line-integral-checking-stokes-theorem

enter image description here

可以使用三角技巧来评估C_3。然后您可以通过以下方法解决它:

import sympy as sp
t = sp.symbols('t')
sp.Integral((1-sp.cos(t)-sp.sin(t))**2 * sp.exp(1-sp.cos(t)-sp.sin(t)) * (sp.sin(t)-sp.cos(t)), (t, 0, 2*sp.pi))

问题是C_1和C_2。这些不能用技巧来评估。然后,我必须使用数值方法。

您有什么建议?我一直在尝试N(),但一无所获。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用scipy.integrate.quad函数:

from scipy.integrate import quad
from numpy import cos, sin, exp, pi

f1 = lambda t: (1 + sin(t))*exp(1+cos(t))*(-sin(t))
f2 = lambda t: ((1 + cos(t))**2 + exp(1+cos(t)))*cos(t)

C1, err1 = quad(f1, 0, 2*pi)
C2, err2 = quad(f2, 0, 2*pi)

print("C1 = ", C1, ", estimated error: ", err1)
print("C2 = ", C2, ", estimated error: ", err2)

输出

C1 =  -9.652617083240306, estimated error:  2.549444932020608e-09
C2 =  15.93580239041989, estimated error:  3.4140955340600243e-10

编辑: 您还可以通过以下参数指定精度:epsrel:相对误差,epsabs:绝对误差。但这有点棘手(请参见this): 我们将绝对误差目标指定为零。无法满足此条件,因此相对误差目标将确定积分何时停止。

C1, err1 = quad(f1, 0, 2*pi, epsrel=1e-10, epsabs=0)
print("C1 = ", C1, ", estimated error: ", err1)

输出

C1 =  -9.652617083240308 , estimated error:  1.4186554373311127e-13

答案 1 :(得分:1)

替代:使用quadpy(属于我的项目):

import quadpy
from numpy import cos, sin, exp, pi

c1, err1 = quadpy.line_segment.integrate_adaptive(
    lambda t: (1 + sin(t)) * exp(1 + cos(t)) * (-sin(t)),
    [0.0, 2 * pi],
    1.0e-10
)

c2, err2 = quadpy.line_segment.integrate_adaptive(
    lambda t: ((1 + cos(t))**2 + exp(1+cos(t)))*cos(t),
    [0.0, 2 * pi],
    1.0e-10
)

print("C1 = ", c1, ", estimated error: ", err1)
print("C2 = ", c2, ", estimated error: ", err2)
C1 =  -9.652617082755405 , estimated error:  2.0513709554864616e-11
C2 =  15.935802389560804 , estimated error:  6.646538563488704e-11