OrdinaryDiffEq.jl
OrdinaryDiffEq.jl 是 DifferentialEquations 生态系统中的一个组件包。它包含 常微分方程求解器和实用工具。虽然它完全独立 且可单独使用,但希望使用此 功能的用户应查看 DifferentialEquations.jl。
安装
假设您已经正确安装了 Julia,只需以标准方式导入 OrdinaryDiffEq.jl 即可:
import Pkg;
Pkg.add("OrdinaryDiffEq");
v7 破坏性变更
OrdinaryDiffEq v7 升级至 SciMLBase v3 和 RecursiveArrayTools v4,所有子库均包含破坏性变更。请参阅 NEWS.md 获取完整的迁移指南。
API
OrdinaryDiffEq.jl 是 SciML 通用接口的一部分,但也可以独立于 DifferentialEquations.jl 使用。唯一的要求是用户向 solve 传递一个 OrdinaryDiffEq.jl 算法。例如,我们可以使用 Tsit5() 算法求解 文档中的 ODE 教程:
using OrdinaryDiffEq
f(u, p, t) = 1.01 * u
u0 = 1 / 2
tspan = (0.0, 1.0)
prob = ODEProblem(f, u0, tspan)
sol = solve(prob, Tsit5(), reltol = 1e-8, abstol = 1e-8)
using Plots
plot(sol, linewidth = 5, title = "Solution to the linear ODE with a thick line",
xaxis = "Time (t)", yaxis = "u(t) (in μm)", label = "My Thick Line!") # legend=false
plot!(sol.t, t -> 0.5 * exp(1.01 * t), lw = 3, ls = :dash, label = "True Solution!")
该示例使用了非原地语法 f(u,p,t),而原地语法(对于方程组更高效)在 Lorenz 示例中展示:
using OrdinaryDiffEq
function lorenz!(du, u, p, t)
du[1] = 10.0 * (u[2] - u[1])
du[2] = u[1] * (28.0 - u[3]) - u[2]
du[3] = u[1] * u[2] - (8 / 3) * u[3]
end
u0 = [1.0; 0.0; 0.0]
tspan = (0.0, 100.0)
prob = ODEProblem(lorenz!, u0, tspan)
sol = solve(prob, Tsit5())
using Plots;
plot(sol, idxs = (1, 2, 3))
非常快速的静态数组版本可以专门编译为适合您模型大小的尺寸。例如:
using OrdinaryDiffEq, StaticArrays
function lorenz(u, p, t)
SA[10.0 * (u[2] - u[1]), u[1] * (28.0 - u[3]) - u[2], u[1] * u[2] - (8 / 3) * u[3]]
end
u0 = SA[1.0; 0.0; 0.0]
tspan = (0.0, 100.0)
prob = ODEProblem(lorenz, u0, tspan)
sol = solve(prob, Tsit5())
对于“精细 ODE”,如动力学方程和 SecondOrderODEProblems,请参阅 DiffEqDocs。例如,可以使用辛方法求解谐振子方程。谐振子由以下方程描述:
$$\ddot{x} + \omega^2 x = 0$$
这等价于以下一阶系统:
$$\dot{x} = v$$ $$\dot{v} = -\omega^2 x$$
using OrdinaryDiffEq
function harmonic_oscillator!(dv, v, u, p, t)
ω = p[1]
dv[1] = -ω^2 * u[1]
end
ω = 2.0 # angular frequency
initial_position = [1.0]
initial_velocity = [0.0]
tspan = (0.0, 10.0)
prob = SecondOrderODEProblem(harmonic_oscillator!, initial_velocity, initial_position, tspan, [ω])
sol = solve(prob, VelocityVerlet(), dt = 1 / 100)
using Plots
plot(sol, idxs = (1, 2), label = "Phase space", xaxis = "Position", yaxis = "Velocity")
对于更复杂的动力系统,例如 Hénon-Heiles 势,辛积分器能够保持哈密顿动力学的结构。在 DiffEqTutorials.jl 中,我们展示了如何求解这些运动方程:
function HH_acceleration!(dv, v, u, p, t)
x, y = u
dx, dy = dv
dv[1] = -x - 2 * x * y
dv[2] = y^2 - y - x^2
end
initial_positions = [0.0, 0.1]
initial_velocities = [0.5, 0.0]
prob = SecondOrderODEProblem(HH_acceleration!, initial_velocities, initial_positions, tspan)
sol2 = solve(prob, KahanLi8(), dt = 1 / 10);
其他精炼形式包括 IMEX 和半线性 ODE(用于指数积分器)。
可用求解器
有关可用求解器的列表,请参阅 DifferentialEquations.jl ODE Solvers、Dynamical ODE Solvers 以及 Split ODE Solvers 页面。