一阶微分方程
d x d t + x = s i n ( t ) \frac{\mathrm{dx}}{\mathrm{dt}}+x=\mathrm{sin}\left(t\right) dtdx+x=sin(t)
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
def func(y, t):
x = y
dx = -x+np.sin(t)
return dx
t = np.arange(0, 10, 0.001)
sol1 = odeint(func, [0], t)
fig = plt.figure(figsize=(16,8))
plt.plot(t, sol1[:,0], label='x')
plt.legend(fontsize=15)
plt.show()
二阶微分方程
以下面的方程为例
d
2
x
d
t
2
+
d
x
d
t
+
x
=
s
i
n
(
t
)
\frac{d^2 x}{{\mathrm{dt}}^2 }+\frac{\mathrm{dx}}{\mathrm{dt}}+x=\mathrm{sin}\left(t\right)
dt2d2x+dtdx+x=sin(t)
from scipy.integrate import odeint
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
def func(y, t):
x, dx = y
d2x = [dx, -dx-x+np.sin(t)]
return d2x
t = np.arange(0, 10, 0.001)
sol1 = odeint(func, [0, 0], t)
fig = plt.figure(figsize=(16,8))
plt.plot(t, sol1[:,0])
plt.plot(t, sol1[:,1])
plt.show()
sol1 = odeint(func, [0, 0], t)中[0, 0]是传递给func函数的初始值,func是待解的方程。
二阶微分方程组
d
2
x
d
t
2
+
y
d
x
d
t
+
x
=
s
i
n
(
t
)
\frac{d^2 x}{{\mathrm{dt}}^2 }+y\frac{\mathrm{dx}}{\mathrm{dt}}+x=\mathrm{sin}\left(t\right)
dt2d2x+ydtdx+x=sin(t)
d
2
y
d
t
2
+
x
d
y
d
t
+
y
=
1
\frac{d^2 y}{{\mathrm{dt}}^2 }+x\frac{\mathrm{dy}}{\mathrm{dt}}+y=1
dt2d2y+xdtdy+y=1
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
def func(y, t):
x, dx, z, dz = y
d2q = [dx, -z*dx-x+np.sin(t), dz, -x*dz-z+1]
return d2q
t = np.arange(0, 10, 0.001)
sol1 = odeint(func, [0, 0, 0, 0], t)
fig = plt.figure(figsize=(16,8))
plt.plot(t, sol1[:,0], label='x')
plt.plot(t, sol1[:,2], label='y')
plt.legend(fontsize=15)
plt.show()
sol1里对应着x,dx/dt,y,dy/dt