sympy提供了常微分方程求解器,以下面的微分方程为例
9 f ( x ) + d 2 d x 2 f ( x ) = 0 9 f{\left(x \right)} + \frac{d^{2}}{d x^{2}} f{\left(x \right)}=0 9f(x)+dx2d2?f(x)=0
可调用dsolve来进行求解
from sympy import Function, dsolve, Derivative
from sympy.abc import x
from sympy import print_latex
f = Function('f')
ff = dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
print_latex(ff)
结果如下
f ( x ) = C 1 sin ? ( 3 x ) + C 2 cos ? ( 3 x ) f{\left(x \right)} = C_{1} \sin{\left(3 x \right)} + C_{2} \cos{\left(3 x \right)} f(x)=C1?sin(3x)+C2?cos(3x)
dsolve的完整参数如下
sympy.solvers.ode.dsolve(eq, func=None, hint='default', simplify=True, ics=None, xi=None, eta=None, x0=0, n=6, **kwargs)
各参数含义为
sympy.solvers.ode中提供了allhints元组,给出了所有hint的可选方法,共计45个,下面随机挑选两个进行测试。
# 可查看所有的hint
from sympy.solvers.ode import allhints
以下面的函数为例
sin ? ( x ) cos ? ( f ( x ) ) + sin ? ( f ( x ) ) cos ? ( x ) d d x f ( x ) \sin{\left(x \right)} \cos{\left(f{\left(x \right)} \right)} + \sin{\left(f{\left(x \right)} \right)} \cos{\left(x \right)} \frac{d}{d x} f{\left(x \right)} sin(x)cos(f(x))+sin(f(x))cos(x)dxd?f(x)
from sympy import sin, cos
eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
f1 = dsolve(eq, hint='1st_exact')
f2 = dsolve(eq, hint='almost_linear')
二者的求解结果完全一致:
[ f ( x ) = ? acos ? ( C 1 cos ? ( x ) ) + 2 π , ? f ( x ) = acos ? ( C 1 cos ? ( x ) ) ] \left[ f{\left(x \right)} = - \operatorname{acos}{\left(\frac{C_{1}}{\cos{\left(x \right)}} \right)} + 2 \pi, \ f{\left(x \right)} = \operatorname{acos}{\left(\frac{C_{1}}{\cos{\left(x \right)}} \right)}\right] [f(x)=?acos(cos(x)C1??)+2π,?f(x)=acos(cos(x)C1??)]
dsolve也可以求解常微分方程组,以下面的方程组为例
x ′ ( t ) = 12 t x ( t ) + 8 y ( t ) y ′ ( t ) = 7 t y ( t ) + 21 x ( t ) x'{\left(t \right)} = 12 t x{\left(t \right)} + 8 y{\left(t \right)}\\ y'{\left(t \right)} = 7 t y{\left(t \right)} + 21 x{\left(t \right)} x′(t)=12tx(t)+8y(t)y′(t)=7ty(t)+21x(t)
求解方法如下
from sympy import Eq, symbols
from sympy.abc import t
x, y = symbols('x, y', cls=Function)
eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
xys = dsolve(eq)
print_latex(xys)
x ( t ) = C 1 x 0 ( t ) + C 2 x 0 ( t ) ∫ 8 ( e ∫ 7 t ? d t ) e ∫ 12 t ? d t x 0 2 ( t ) ? d t , y ( t ) = C 1 y 0 ( t ) + C 2 ( y 0 ( t ) ∫ 8 ( e ∫ 7 t ? d t ) e ∫ 12 t ? d t x 0 2 ( t ) ? d t + ( e ∫ 7 t ? d t ) e ∫ 12 t ? d t x 0 ( t ) ) x{\left(t \right)} = C_{1} x_{0}{\left(t \right)} + C_{2} x_{0}{\left(t \right)} \int \frac{8 \left(e^{\int 7 t\, dt}\right) e^{\int 12 t\, dt}}{x_{0}^{2}{\left(t \right)}}\, dt, \\ y{\left(t \right)} = C_{1} y_{0}{\left(t \right)} + C_{2} \left(y_{0}{\left(t \right)} \int \frac{8 \left(e^{\int 7 t\, dt}\right) e^{\int 12 t\, dt}}{x_{0}^{2}{\left(t \right)}}\, dt + \frac{\left(e^{\int 7 t\, dt}\right) e^{\int 12 t\, dt}}{x_{0}{\left(t \right)}}\right) x(t)=C1?x0?(t)+C2?x0?(t)∫x02?(t)8(e∫7tdt)e∫12tdt?dt,y(t)=C1?y0?(t)+C2? ?y0?(t)∫x02?(t)8(e∫7tdt)e∫12tdt?dt+x0?(t)(e∫7tdt)e∫12tdt? ?