一阶微分方程

dxdt+x=sin(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()

二阶微分方程

以下面的方程为例
d2xdt2+dxdt+x=sin(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是待解的方程。
结果图

二阶微分方程组

d2xdt2+ydxdt+x=sin(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)
d2ydt2+xdydt+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

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐