Skip to content
Julia

Solving ODEs with DifferentialEquations.jl

Define and numerically solve an initial-value ODE with adaptive stepping.

By EZ4Code Team
odescientificdifferential-equations

Code

using DifferentialEquations, Plots

# Logistic growth: du/dt = r*u*(1 - u/K)
function logistic!(du, u, p, t)
    r, K = p
    du[1] = r * u[1] * (1 - u[1] / K)
end

u0 = [1.0]                 # initial population
tspan = (0.0, 10.0)
p = (1.2, 100.0)           # r=1.2, K=100

prob = ODEProblem(logistic!, u0, tspan, p)
sol = solve(prob, Tsit5())  # adaptive 5th-order RK

# sol is callable & plotable
sol(0.0)            # [1.0]
sol(5.0)            # interpolated value at t=5
sol.u[end]          # final state

plot(sol, label="u(t)", xlabel="t", ylabel="population")

# Stiff system? Use a stiff solver
# sol_stiff = solve(prob, Rosenbrock23())

# Ensembles: simulate 100 perturbed runs in parallel
ensemble_prob = EnsembleProblem(prob, prob_func = (prob, i, repeat) ->
    remake(prob, u0 = [1.0 + 0.1rand()]))
sim = solve(ensemble_prob, Tsit5(), trajectories = 100)

Explanation

DifferentialEquations.jl is the canonical Julia ODE/DAE/SDE library. The pattern is: define an in-place derivative function f!(du, u, p, t), wrap it in an ODEProblem with initial state and time span, then solve with a chosen algorithm (Tsit5 for non-stiff, Rosenbrock23 for stiff). The returned solution object interpolates the trajectory and can be plotted or sampled at any t.

More Julia Snippets