Core Concepts of Ordinary Differential Equations (ODEs)

6 min read

Welcome back, numerical explorer! 🔭

Now that you have your environment set up, it's time to stop calculating 1 + 1 and start simulating reality.

In this module, we are going to tackle the "Hello World" of DifferentialEquations.jl. We aren't just solving math problems here; we are building the foundation for simulating chemical reactions, orbital mechanics, or how fast a rumor spreads on social media.

Let's dive in. 🌊


1. Defining an ODEProblem: Out-of-place vs. In-place Syntax 🏗️

The Definition

In the context of this library, an ODE is defined by a function ff such that:

u′=f(u,p,t)u' = f(u, p, t)

Where:

  • uu: The state (what changes).
  • pp: The parameters (constants, like gravity or decay rates).
  • tt: The independent variable (usually time).

The Problem

Computers handle memory in two ways when calculating math:

  1. New Allocation: Creating a brand new array for every calculation result.
  2. Mutation: Overwriting an existing array in memory.

If you are simulating a system with 1,000,000 variables, creating a new array 1,000 times a second will crash your RAM faster than a Chrome tab with a memory leak. If you are simulating just 3 variables, creating new arrays is actually faster and cleaner.

The Solution: Two Syntax Styles

DifferentialEquations.jl allows you to choose based on your needs.

A. Out-of-Place (OOP) Syntax 📄

Best for: Small systems, prototyping, using StaticArrays.

You write a function that returns the derivative. It looks exactly like the math equation.

julia
using DifferentialEquations

# f(u, p, t) returns the derivative
function exponential_growth(u, p, t)
    # math: du/dt = α * u
    α = p
    return α * u
end

Here, the function returns a new number (or array). It's clean and functional.

B. In-Place (IIP) Syntax ⚡

Best for: Large systems, high-performance loops, reducing garbage collection.

You write a function that modifies the first argument du. Note the ! in the function name—that's a Julia convention for "this function changes its input."

julia
# f!(du, u, p, t) updates du
function exponential_growth!(du, u, p, t)
    α = p
    # We update the first element of du
    du[1] = α * u[1]
end

Industry Standard:

  • Use Out-of-Place if your state vector u has fewer than ~100 elements.
  • Use In-Place if your state vector is large (like in discretized PDEs or neural networks).

2. Configuring Time Spans and Initial Conditions ⏳

The Problem

A differential equation describes how something changes, but it doesn't say where it starts or when to stop looking. Without boundaries, the solver runs forever (or errors out).

The Solution

We must provide u0 (Initial Condition) and tspan (Time Span) to bundle everything into an ODEProblem.

Setting u0 (Initial Condition)

This represents the state of the world at t=0t=0.

  • For scalar problems (single variable), use a number: u0 = 1.0
  • For systems (multiple variables), use an array: u0 = [1.0, 0.5, 0.0]

Setting tspan (Time Span)

This is a tuple defining (start_time, end_time).

  • Example: tspan = (0.0, 10.0)

⚠️ Important: Always use floating-point numbers (e.g., 10.0 instead of 10) for time spans in Julia. Using integers can sometimes force the solver into "integer arithmetic mode," which might cause type instabilities or errors when decimals are inevitably introduced during solving.

Putting it together

Let's define the problem object. This doesn't solve it yet; it just packages the math.

julia
# 1. Define the physics
function decay(u, p, t)
    return -p * u
end

# 2. Define the data
u0 = 100.0        # Start with 100 items
tspan = (0.0, 5.0) # Run from t=0 to t=5
p = 0.5           # Decay rate

# 3. Create the Problem
prob = ODEProblem(decay, u0, tspan, p)

Fun Fact: Under the hood, DifferentialEquations.jl uses type dispatch. It looks at the types of u0 and tspan to compile a specialized solver just for your specific equation structure. It's like having a tailor-made suit for your math problem. 👔


3. Extracting and Plotting the Solution Data 📊

The Problem

You have the prob object, but you need the numbers. You run sol = solve(prob), but printing sol dumps a massive wall of text that looks like Matrix code.

The Solution

The solve function returns a solution object (usually called sol) that acts like a smart container.

Solving

julia
# Solve the problem
# Tsit5() is the default solver for non-stiff problems. 
# It's an industry legend for balancing speed and accuracy.
sol = solve(prob)

Extracting Data

The solution object holds two main arrays:

  1. sol.t: The time points where the solver stopped.
  2. sol.u: The values of the state u at those time points.
julia
println("Time points: ", sol.t)
println("Values: ", sol.u)

# Accessing the 5th step
println("At time $(sol.t[5]), the value is $(sol.u[5])")

Plotting

Because DifferentialEquations.jl has a "recipe" for the Plots.jl library, you don't need to manually pass X and Y arrays. You just plot the solution object directly!

julia
using Plots

# The library knows sol.t is x-axis and sol.u is y-axis
plot(sol, 
     title="Radioactive Decay", 
     xaxis="Time (t)", 
     yaxis="Quantity (u)", 
     linewidth=3,
     label="My Simulation")

Pro Tip: If your system has multiple variables (e.g., rabbits and foxes), plot(sol) will automatically plot all of them as separate lines. 🐰🦊


4. Handling Interpolation: Evaluating Solutions at Specific Times 🎯

The Problem

Solvers are "adaptive." They take big steps when nothing is happening and tiny steps when things change fast.

  • The solver might give you data at t=0.1t=0.1 and t=0.5t=0.5.
  • But your boss asks: "What was the value exactly at t=0.35t=0.35?"

You check sol.t and 0.350.35 isn't there. Panic? No.

The Solution: Dense Output

By default, DifferentialEquations.jl enables Dense Output. This means the solution object sol is not just an array of data; it is a continuous function.

You can treat sol like a function!

julia
# Get the value at t = 0.35
exact_val = sol(0.35)

println("Value at t=0.35 is $exact_val")

You can even pass an array of times to get interpolated values:

julia
# Get values at specific intervals
times_i_need = 0.0:0.1:1.0
interpolated_values = sol(times_i_need)

Why is this better than saveat?

You might see an option called saveat in the docs, which forces the solver to save at specific steps.

  • Use saveat if you only need specific points and want to save memory.
  • Use Interpolation sol(t) if you want the solver to be as accurate as possible, but you want to query the result anywhere afterwards. This is usually preferred for high-accuracy analysis.

🧪 Hands-On Challenge

Try this in your REPL (Read-Eval-Print Loop). We will model a simple harmonic oscillator (a pendulum).

x′=vx' = vv′=−xv' = -x

This needs a system of 2 equations.

julia
using DifferentialEquations, Plots

# 1. Define the In-Place function
# u[1] is position (x), u[2] is velocity (v)
function pendulum!(du, u, p, t)
    du[1] = u[2]      # dx/dt = v
    du[2] = -u[1]     # dv/dt = -x
end

# 2. Setup
u0 = [1.0, 0.0]       # Start at x=1, v=0
tspan = (0.0, 10.0)   # 10 seconds

# 3. Create Problem and Solve
prob = ODEProblem(pendulum!, u0, tspan)
sol = solve(prob)

# 4. Check the value at t=3.5 without re-solving
println("Position at t=3.5 is ", sol(3.5)[1])

# 5. Plot
plot(sol, label=["Position" "Velocity"])

If you see a sine wave and a cosine wave, congratulations! You just simulated physics. 🚀


📚 References & Further Reading

Challenge

Challenge: In-Place Modeling of Predator-Prey Dynamics

You are tasked with modeling the Lotka-Volterra equations, a classic model for predator-prey dynamics. The system is described by two coupled ordinary differential equations:

  • Prey population (x): dx/dt = α*x - β*x*y
  • Predator population (y): dy/dt = δ*x*y - γ*y

Your goal is to implement this system, solve it over a given time period, and then use the solution's dense output feature to find the system's state at a specific point in time.

Your tasks:

  1. Define a function lotka_volterra!(du, u, p, t) that calculates the derivatives for the system. You must use the memory-efficient in-place syntax, where du is modified directly.
    • u will be a 2-element array representing [x, y].
    • p will be a 4-element array of parameters [α, β, δ, γ].
  2. Set the initial conditions to 1.0 for both prey and predators.
  3. Define the parameters as α=1.5, β=1.0, δ=3.0, and γ=1.0.
  4. Set the simulation time span to run from t=0.0 to t=15.0.
  5. Construct the ODEProblem with the function, initial conditions, time span, and parameters.
  6. Use the solve function to find the solution.
  7. Finally, use the resulting solution object to find the interpolated state (both prey and predator populations) at exactly t = 7.25.

Expected result

Your code should correctly define and solve the Lotka-Volterra ODEProblem using the in-place syntax.

The final variable, state_at_7_25, should contain a 2-element array-like object. The first element will be the interpolated prey population (x) and the second element will be the interpolated predator population (y) at t=7.25.

julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.