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:

  1. Speed: It compiles to machine code. It's often faster than C++ solvers (yes, really).
  2. Automagic: It solves Ordinary Differential Equations (ODEs), Stochastic DEs (SDEs), Delay DEs (DDEs), and even Neural ODEs (machine learning mixed with physics).
  3. 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.

  1. Open your terminal/command prompt and type julia to enter the REPL (Read-Eval-Print Loop).
  2. You will see a prompt like julia>.
  3. 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:

julia
add DifferentialEquations Plots

Note: 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:

julia
using DifferentialEquations
using Plots

If 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 (dudt\frac{du}{dt}) is proportional to the current size of the population (uu).

dudt=αu\frac{du}{dt} = \alpha u

Where:

  • uu: The amount of bacteria.
  • α\alpha: The growth rate (parameter).
  • tt: 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.*

julia
# 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:

  1. Define the ODEProblem
  2. solve the Problem
  3. Analyze the ODESolution

Step 1: The Problem Container

We bundle our function, initial state, timeframe, and parameters into a struct.

julia
# Create the problem object
prob = ODEProblem(growth_model, u0, tspan, p)

Step 2: The Solver

Now we pass the problem to the solve command.

julia
# 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.

julia
# 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.

julia
# 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 width

If you run this, you will see a smooth exponential curve rising to the right.


Summary of the Workflow

  1. Function: f(u,p,t) →\to returns rate of change.
  2. Problem: ODEProblem(f, u0, tspan, p).
  3. Solve: sol = solve(prob).
  4. Analyze: sol[i] or plot(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:

  1. Prey Population Change (x):
    dxdt=αx−βxy\frac{dx}{dt} = \alpha x - \beta xy

  2. Predator Population Change (y):
    dydt=δxy−γy\frac{dy}{dt} = \delta xy - \gamma y

Where:

  • x is the population of prey.
  • y is the population of predators.
  • t is time.
  • α,β,δ,γ\alpha, \beta, \delta, \gamma are parameters representing the interaction rates.

Follow the standard Function -> Problem -> Solve workflow to implement and solve this system with the following specifications:

  1. Define the model function in the standard in-place form: lotka_volterra!(du, u, p, t). Let u[1] represent the prey x and u[2] represent the predators y.
  2. Set the initial populations (u0) to [10.0, 10.0] (10 prey and 10 predators).
  3. Define the time span (tspan) to be from 0.0 to 10.0.
  4. Use the following parameters (p): α=1.5,β=1.0,δ=3.0,γ=1.0\alpha=1.5, \beta=1.0, \delta=3.0, \gamma=1.0. They should be in a vector in that order.
  5. Construct an ODEProblem named prob.
  6. Solve the problem and assign the final ODESolution object to a variable named lotka_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, updating du[1] with the rate of change for the prey population and du[2] with the rate of change for the predator population.
  • The initial condition vector u0 must be [10.0, 10.0].
  • The time span tuple tspan must be (0.0, 10.0).
  • The parameter vector p must be [1.5, 1.0, 3.0, 1.0].
  • An ODEProblem named prob must be correctly constructed using the function, initial conditions, time span, and parameters.
  • The final line of code must call solve(prob) and assign the resulting ODESolution object to the variable lotka_volterra_solution.
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.