python 求常微分方程 sympy库

问题1:
f(x)2f(x)+f(x)=sin(x)f''(x)-2f'(x) + f(x) = sin(x)f′′(x)−2f′(x)+f(x)=sin(x)

程序,如下

from sympy import *
f = symbols('f', cls=Function)
x = symbols('x')
eq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))
print(dsolve(eq, f(x)))

结果

Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2)

 ~ 
 ~ 
 ~ 
 ~ 
附:布置考试中两题
1.利用python的Sympy库求解微分方程的解 y=f(x)y=f(x)y=f(x),并尝试利用matplotlib绘制函数图像

f(x)+f(x)+f2(x)=0,f(0)=1f'(x)+f(x)+f^2(x)=0,\qquad f(0)=1f′(x)+f(x)+f2(x)=0,f(0)=1

程序,如下

from sympy import *
f = symbols('f', cls=Function)
x = symbols('x')
eq = Eq(f(x).diff(x,1)+f(x)+f(x)**2, 0)
print(dsolve(eq, f(x)))
C1 = symbols('C1')
eqr = -C1/(C1 - exp(x))
eqr1 = eqr.subs(x, 0)
print(solveset(eqr1 - 1, C1))
eqr2 = eqr.subs(C1, 1/2)
# 画图
import matplotlib.pyplot as plt
import numpy as np
x_1 = np.arange(-5, 5, 0.1)
y_1 = [-0.5/(0.5 - exp(x)) for x in x_1]
plt.plot(x_1, y_1)
plt.axis([-6,6,-10,10])
plt.grid()
plt.show()

结果

Eq(f(x), -C1/(C1 - exp(x)))
FiniteSet(1/2)

python 求常微分方程 sympy库
 ~ 
2.利用python的Sympy库求解微分方程的解 y=y(x)y=y(x)y=y(x),并尝试利用matplotlib绘制函数图像

y(x)=y(x),y(0)=1y'(x)=y(x),\qquad y(0)=1y′(x)=y(x),y(0)=1

程序,如下

from sympy import *
y = symbols('y', cls=Function)
x = symbols('x')
eq = Eq(y(x).diff(x,1), y(x))
print(dsolve(eq, y(x)))
C1 = symbols('C1')
eqr = C1*exp(x)
eqr1 = eqr.subs(x, 0)
print(solveset(eqr1 - 1, C1))
eqr2 = eqr.subs(C1, 1)
# 画图
import matplotlib.pyplot as plt
import numpy as np
x_1 = np.arange(-5, 5, 0.01)
y_1 = [exp(x) for x in x_1]
plt.plot(x_1, y_1, color='orange')
plt.grid()
plt.show()

结果

Eq(y(x), C1*exp(x))
FiniteSet(1)

python 求常微分方程 sympy库

上一篇:【Python】SymPy符号计算库学习


下一篇:python使用sympy不定积分入门及求解