高等数学问题的符号解(8)--解微分方程

微分方程,是指含有未知函数及其导数的关系式。解微分方程就是找出未知函数。

例:求下列微分方程的通解
(1)齐次方程 $ y^{\prime \prime}-5y^{\prime }+6y = 0 $
(2)非齐次方程 $ y^{\prime \prime}-5y^{\prime }+6y = xe^{2x} $

1
2
3
4
5
6
7
8
9
10
from sympy import *

x = symbols('x')
y = symbols('y', cls=Function) # 或者 y = Function('y')

eq1 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)
eq2 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)-x*exp(2*x)

print('齐次方程的解为:', dsolve(eq1,y(x)))
print('非齐次方程的解为:', dsolve(eq2,y(x)))

例:求下列微分方程的解
(1)初值问题:$ y^{\prime \prime}-5y^{\prime }+6y = 0, y(0) = 1, y^{\prime } = 0 $
(2)边值问题:$ y^{\prime \prime}-5y^{\prime }+6y = xe^{2x}, y(0) = 1, y(2) = 0 $

1
2
3
4
5
6
7
8
9
10
11
12
13
from sympy import *

x = symbols('x')
y = symbols('y', cls=Function) # 或者 y = Function('y')

eq1 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)
eq2 = diff(y(x),x,2)-5*diff(y(x),x)+6*y(x)-x*exp(2*x)

s1 = dsolve(eq1,y(x), ics={y(0):1, diff(y(x),x).subs(x,0):0})
print('初值问题的解为:', s1)

s2 = dsolve(eq2,y(x), ics={y(0):1, y(2):0})
print('边值问题的解为:', s2)

例:求下述微分方程的特解
$\frac{d^{2}y}{dx^{2}}+2\frac{dy}{dx}+2y=0,y(0)=0,y^{\prime }(0)=1$

1
2
3
4
5
6
7
8
9
from sympy.abc import x
from sympy import diff, dsolve, simplify, Function

y = Function('y')
eq = diff(y(x),x,2)+2*diff(y(x),x)+2*y(x) # 定义方程
con = {y(0): 0, diff(y(x),x).subs(x,0): 1} # 定义初值条件
y = dsolve(eq, ics=con)

print(simplify(y))

例:求下述微分方程的解
$\frac{d^{2}y}{dx^{2}}+2\frac{dy}{dx}+2y=sinx,y(0)=0,y^{\prime }(0)=1$

1
2
3
4
5
6
7
8
9
from sympy.abc import x
from sympy import Function, diff, dsolve, sin

y = Function('y')
eq = diff(y(x),x,2)+2*diff(y(x),x)+2*y(x)-sin(x) # 定义方程
con = {y(0): 0, diff(y(x), x).subs(x,0): 1} # 定义初值条件
y = dsolve(eq, ics=con)

print(y)

例:求下列微分方程组的解
$$
\begin{cases}
\frac{dx_{1}}{dt}=2x_{1}-3x_{2}+3x_{3} x_{1}(0)=1 \\
\frac{dx_{2}}{dt}=4x_{1}-5x_{2}+3x_{3} x_{2}(0)=2 \\
\frac{dx_{3}}{dt}=4x_{1}-5x_{2}+2x_{3} x_{3}(0)=3
\end{cases}
$$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import sympy as sp

t = sp.symbols('t')
x1,x2,x3 = sp.symbols('x1,x2,x3',cls=sp.Function)
eq = [x1(t).diff(t)-2*x1(t)+3*x2(t)-3*x3(t),
x2(t).diff(t)-4*x1(t)+5*x2(t)-3*x3(t),
x3(t).diff(t)-4*x1(t)+4*x2(t)-2*x3(t)]
con = {x1(0):1, x2(0):2, x3(0):3}
s = sp.dsolve(eq, ics=con)

'''
# 更简洁的写法
t = sp.symbols('t')
x1,x2,x3 = sp.symbols('x1:4',cls=sp.Function)
x = sp.Matrix([x1(t),x2(t),x3(t)])
A = sp.Matrix([[2,-3,3],[4,-5,3],[4,-4,2]])
eq = x.diff(t)-A*x
s = sp.dsolve(eq,ics={x1(0):1,x2(0):2,x3(0):3})
'''
print(s)
0%