Introduction to DifferentialEquations.jl
6 min read
Welcome to the start of your journey into Scientific Machine Learning (SciML)! 🚀
If you are reading this, you probably realized that the world isn't static. Stocks change, chemical reactions happen, planets orbit, and coffee cools down. To understand how things change over time, we use Differential Equations. To solve them without losing your mind, we use Julia.
This guide is designed to take you from "What is a terminal?" (okay, maybe slightly more advanced than that) to solving your first differential equation simulation.
1. Welcome to SciML: Why DifferentialEquations.jl?
The Problem
You have a mathematical model describing how a system evolves.
- Doing it by hand? Only works for textbook problems. Real-life equations (like climate models or robotics) are "unsolvable" analytically.
- Python (
scipy.integrate)? It's great for basics, but once you get into complex systems (stiff equations, stochastic noise), it hits a performance wall. - C++ / Fortran? Blazing fast, but do you really want to write 500 lines of boilerplate code just to test a hypothesis?
The Solution: DifferentialEquations.jl
Part of the SciML ecosystem, this package is widely considered the "best-in-class" solver suite across any programming language.
Why industry professionals choose it:
- Speed: It compiles to machine code. It's often faster than C++ solvers (yes, really).
- Automagic: It solves Ordinary Differential Equations (ODEs), Stochastic DEs (SDEs), Delay DEs (DDEs), and even Neural ODEs (machine learning mixed with physics).
- Composability: You can differentiate through the solver. This is massive for finance and AI backpropagation.
Fun Fact: The creators of this library optimized it so heavily that in some benchmarks, it solves equations faster than the time it takes Python to just start the interpreter. 🏎️
2. Setting up the Julia Environment and Package
Before we calculate anything, we need the tools. We will stick to the modern, standard industry practice: Juliaup.
Step A: Install Julia
If you haven't installed Julia yet, do not download the specific version binaries manually. Use the multiplexer.
- Mac/Linux: Open your terminal and type:bash
curl -fsSL https://install.julialang.org | sh - Windows: Open PowerShell (as Administrator usually helps) and type:powershell
winget install julia -s msstore
Step B: The REPL and Package Mode
Julia has a unique package manager built right into the terminal.
- Open your terminal/command prompt and type
juliato enter the REPL (Read-Eval-Print Loop). - You will see a prompt like
julia>. - Press the
]key. The prompt will change to(@v1.x) pkg>. You are now in Package Mode.
Step C: Install DifferentialEquations.jl
In the pkg mode, run:
add DifferentialEquations PlotsNote: We are adding Plots because numbers are boring; graphs are cool.
☕ Coffee Break: The first time you add and import these packages, Julia does something called "Precompilation". It looks at the code and translates it into machine instructions specific to your CPU. This might take a minute or two. Don't panic; it's just getting ready to be fast later.
Step D: Verify Installation
Press Backspace to leave package mode (return to julia>), then type:
using DifferentialEquations
using PlotsIf it runs without red error text, you are golden! ✨
3. Your First ODE: Modeling Exponential Growth
Let's model something tangible: Bacteria Growth. 🧫
The Definition
An Ordinary Differential Equation (ODE) relates a function to its derivative.
For simple growth, the rate of change of the population () is proportional to the current size of the population ().
Where:
- : The amount of bacteria.
- : The growth rate (parameter).
- : Time.
The Code Implementation
In DifferentialEquations.jl, we define the system using a specific function signature: f(u, p, t).
u: The current state (User).p: Parameters (Params).t: Time (Time).
*Mnemonic: U Post Tweaks.*
# 1. Define the Problem Function
# u: current population
# p: growth rate (alpha)
# t: current time
function growth_model(u, p, t)
return p * u
end
# 2. Define Initial Conditions
u0 = 1.0 # We start with 1 bacterium (or 1 million, depending on units)
# 3. Define Time Span
# Tuple of (start_time, end_time)
tspan = (0.0, 10.0)
# 4. Define Parameters
p = 0.98 # It grows fast!Wait, what happens under the hood?
When you define this function, you aren't calculating values. You are defining the topology of the problem. You are telling Julia: "If you give me a state and a time, I will tell you the slope." The solver will later use this slope to step forward in time.
4. Understanding the Core Workflow: Problem, Solver, and Solution
This is the most important section. In SciML, we strictly separate the Definition of the problem from the Algorithm that solves it.
This workflow consists of three steps:
- Define the
ODEProblem solvethe Problem- Analyze the
ODESolution
Step 1: The Problem Container
We bundle our function, initial state, timeframe, and parameters into a struct.
# Create the problem object
prob = ODEProblem(growth_model, u0, tspan, p)Step 2: The Solver
Now we pass the problem to the solve command.
# Solve it!
sol = solve(prob)Industry Standard Magic: 🧙♂️
Notice we didn't specify how to solve it? We didn't say "Use Runge-Kutta 4" or "Use Euler's method".DifferentialEquations.jl uses an automated system called PolyAlgorithm. It analyzes your equation properties (Is it stiff? Is it linear?) and automatically selects the most efficient numerical method for you.
- For this problem, it likely chose
Tsit5(Tsitouras 5/4 Runge-Kutta), which is the industry standard for non-stiff problems.
Step 3: The Solution
The object sol is powerful. It acts like an array, but it also handles continuous interpolation.
# Check the value at the final time
println("Population at end time: ", sol[end])
# Check the population at exactly t = 4.3 (Interpolation)
# The solver didn't necessarily step exactly at 4.3, but it knows the math to estimate it.
println("Population at t=4.3: ", sol(4.3))Visualizing the Result
Finally, let's see our bacteria take over the world.
# The plot recipe automatically handles the solution object
plot(sol,
title="Exponential Bacteria Growth",
xaxis="Time (t)",
yaxis="Population (u)",
label="Bacteria Count",
lw=3) # lw = line widthIf you run this, you will see a smooth exponential curve rising to the right.
Summary of the Workflow
- Function:
f(u,p,t)returns rate of change. - Problem:
ODEProblem(f, u0, tspan, p). - Solve:
sol = solve(prob). - Analyze:
sol[i]orplot(sol).
🧠 Did You Know?
In Python or MATLAB, solving loops explicitly often leads to massive slowdowns. In Julia, because the solver logic compiles down to native code, you can actually put the solve command inside another loop (like an optimization loop to find the best p) and it remains incredibly fast. This is why it's used for Pharmacometrics (figuring out drug dosage) and Climate Science.
📚 References & Further Reading
- Official Documentation: SciML / DifferentialEquations.jl Docs
- Julia Installation: Juliaup GitHub
- The SciML Ecosystem: SciML.ai
- Paper: Rackauckas, C., & Nie, Q. (2017). DifferentialEquations.jl – A Performant and Feature-Rich Ecosystem for Solving Differential Equations in Julia. Journal of Open Research Software.
Next up, we will look at Systems of Equations (what happens when the bacteria start eating food?). Stay tuned! 📺
Challenge
Challenge: Modeling Predator-Prey Dynamics
Your task is to model the classic Lotka-Volterra predator-prey system using DifferentialEquations.jl. This system describes the population dynamics of two interacting species: prey (e.g., rabbits) and predators (e.g., foxes).
The dynamics are governed by the following system of coupled ordinary differential equations:
Prey Population Change (
x):Predator Population Change (
y):
Where:
xis the population of prey.yis the population of predators.tis time.- are parameters representing the interaction rates.
Follow the standard Function -> Problem -> Solve workflow to implement and solve this system with the following specifications:
- Define the model function in the standard in-place form:
lotka_volterra!(du, u, p, t). Letu[1]represent the preyxandu[2]represent the predatorsy. - Set the initial populations (
u0) to[10.0, 10.0](10 prey and 10 predators). - Define the time span (
tspan) to be from0.0to10.0. - Use the following parameters (
p): . They should be in a vector in that order. - Construct an
ODEProblemnamedprob. - Solve the problem and assign the final
ODESolutionobject to a variable namedlotka_volterra_solution.
Expected result
Your code should correctly set up and solve the Lotka-Volterra system.
- The
lotka_volterra!function must correctly implement the two differential equations, updatingdu[1]with the rate of change for the prey population anddu[2]with the rate of change for the predator population. - The initial condition vector
u0must be[10.0, 10.0]. - The time span tuple
tspanmust be(0.0, 10.0). - The parameter vector
pmust be[1.5, 1.0, 3.0, 1.0]. - An
ODEProblemnamedprobmust be correctly constructed using the function, initial conditions, time span, and parameters. - The final line of code must call
solve(prob)and assign the resultingODESolutionobject to the variablelotka_volterra_solution.