python利用scipy.integrate中的odeint方法解微分方程

一阶微分方程

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

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值