Python 如何用数值方法逼近积分的解
我有以下积分(更多细节:) C_3可以用三角技巧计算。然后,您可以通过以下方式解决此问题:Python 如何用数值方法逼近积分的解,python,numerical-methods,numerical-integration,Python,Numerical Methods,Numerical Integration,我有以下积分(更多细节:) 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。这些不能用技巧来评估。然后,我必须使用数值方法。 你有什么建议吗?我一直在尝试
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()
,但一无所获
谢谢。您可以使用
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
:绝对误差。但这有点棘手(请参阅):
我们将绝对误差目标指定为零。无法满足此条件,因此相对误差目标将确定积分何时停止
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
备选方案:使用(矿山项目):
导入四边形
从numpy进口cos、sin、exp、pi
c1,err1=四边形(
λt:(1+sin(t))*exp(1+cos(t))*(-sin(t)),0.0,2*pi,
)
c2,err2=四边形(
λt:((1+cos(t))**2+exp(1+cos(t)))*cos(t),0.0,2*pi,
)
打印(“C1=”,C1,”,估计错误:,错误1)
打印(“C2=”,C2,”,估计错误:,错误2)
C1 = -9.652617076333142 , estimated error: 1.3725463615061705e-09
C2 = 15.9358023895608 , estimated error: 6.646678031309946e-11