如何用Python求解微分方程组

文章目录

odeint简介

scipy文档中将odeint函数和ode, comples_ode这两个类称为旧API,是scipy早期使用的微分方程求解器,但由于是Fortran实现的,尽管使用起来并不方便,但速度没得说,所以有的时候还挺推荐使用的。

其中,odeint的参数如下

scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0, tfirst=False)

其中func为待求解函数;y0为初值;t为自变量列表,其他参数都有默认选项,可以不填,而且这些参数非常多,其中常用的有

  • args func中除了t之外的其他变量
  • Dfun func的梯度函数,当此参数不为None时,若将col_deriv设为True,则可提升效率。
  • full_output 如果为True,则额外返回一个参数字典
  • ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5,
  • printmessgTrue时打印信息。
  • tfirst 当为False时,func的格式为func(y,t…),否则格式为func(t, y…)

示例

对于常微分方程

θ ′ ′ ( t ) + b θ ′ ( t ) + c sin ⁡ θ ( t ) = 0 b = 0.25 ; c = 5 θ ( 0 ) = π − 0.1 ; θ ′ ( 0 ) = 0 \theta''(t)+b\theta'(t)+c\sin\theta(t)=0\\ b=0.25;\quad c=5\\ \theta(0)=\pi-0.1;\quad \theta'(0)=0 θ′′(t)+bθ(t)+csinθ(t)=0b=0.25;c=5θ(0)=π0.1;θ(0)=0

将其中的二阶导数项用一个新变量替代, ω ( t ) = θ ′ ( t ) \omega(t)=\theta'(t) ω(t)=θ(t),则常微分方程可拆分成微分方程组

θ ′ ( t ) = ω ( t ) ω ′ ( t ) = − b ω ( t ) − c sin ⁡ θ ( t ) \begin{aligned} \theta'(t)&=\omega(t)\\ \omega'(t)&=-b\omega(t)-c\sin\theta(t) \end{aligned} θ(t)ω(t)=ω(t)=(t)csinθ(t)

y = [ θ , ω ] y=[\theta, \omega] y=[θ,ω],则 y ′ = [ θ ′ , ω ′ ] y'=[\theta', \omega'] y=[θ,ω],据此可设计函数func

import numpy as np
def pend(y, t, b, c):
    th, om = y
    dydt = [om, -b*om - c*np.sin(th)]
    return dydt

然后调用并求解

from scipy.integrate import odeint
y0 = [np.pi-0.1, 0]
t = np.linspace(0, 10, 101)
sol = odeint(pend, y0, t, args=(0.25, 5))

然后绘制一下结果

import matplotlib.pyplot as plt
plt.plot(t, sol[:,0], label="theta")
plt.plot(t, sol[:,1], label="omega")
plt.legend()
plt.show()

在这里插入图片描述

这个形状还是比较离奇的。

  • 13
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微小冷

请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值