Solver Selection and Tolerances
7 min read
Welcome back! 🧪 You have defined your Ordinary Differential Equations (ODEs), set up your ODEProblem, and run solve(). It probably worked. But in the engineering and financial world, "it probably works" is usually followed by "why is it taking 3 days to run?" or "why did the bridge collapse in the simulation?"
In this module, we are going to pop the hood of the solve() command. We will stop treating it like a black box and start driving it like a Ferrari.
1. Understanding the Default Algorithm Automation
The Definition
When you run sol = solve(prob) without specifying an algorithm, you aren't running a single, static piece of code. You are triggering a Polyalgorithm.
The Problem it Solves
Differential equations come in different flavors. Some vary slowly (moon orbits), some explode instantly (chemical combustion). Using a "slow and steady" solver on an explosion results in garbage data. Using a "robust, heavy-duty" solver on a simple orbit wastes hours of compute time.
How it works
DifferentialEquations.jl analyzes your problem before solving it. It checks:
- Is the time span long or short?
- Did you provide a mass matrix?
- Does the function imply stiffness (more on this later)?
- What are the requested tolerances?
Based on these heuristics, it automatically selects the most efficient solver for you.
Industry Fact: In 90% of casual use cases, the default
solve(prob)is faster and more accurate than a human trying to guess the algorithm. The defaults are chosen based on extensive benchmarks.
using DifferentialEquations
# A simple decay problem
f(u, p, t) = 1.01 * u
u0 = 0.5
tspan = (0.0, 1.0)
prob = ODEProblem(f, u0, tspan)
# The "Magic" Default
sol = solve(prob)
println("Algorithm used: ", sol.alg)If you run this, you will likely see Tsit5 or CompositeAlgorithm depending on the version and inputs.
2. Choosing Non-Stiff Solvers: Tsit5, BS3, and DP5
Sometimes, you need to manually specify a solver to ensure consistency across benchmarks or to interface with specific hardware (like GPUs). For "normal" problems, we use Non-Stiff solvers.
What is a "Non-Stiff" Problem?
Imagine driving a car on a smooth highway. You can steer gently, and the car reacts predictably. You don't need to correct your steering wheel every millisecond.
- Mathematical Definition: The solution curve is smooth, and there are no disparate time scales (e.g., you don't have one variable changing in nanoseconds while another changes in years).
The Industry Standards
1. Tsit5 (Tsitouras 5/4 Runge-Kutta)
- The Go-To: This is the default for most non-stiff problems.
- Why: It is a 5th-order method. It is generally more efficient than the classic Runge-Kutta 4 (RK4) you might have learned in school. It creates "free" interpolations, meaning you can plot smooth lines between steps without extra computation.
- Use Case: 99% of standard engineering simulations.
2. BS3 (Bogacki-Shampine 3/2)
- The Speedster: A lower order (3rd order) method.
- Why: It takes fewer calculations per step. However, it is less accurate.
- Use Case: When you need a result fast and an error of ~1% () is acceptable. Great for real-time visuals or games.
3. DP5 (Dormand-Prince 5/4)
- The Legacy: This is the specific algorithm behind MATLAB's famous
ode45. - Why: It is very similar to
Tsit5. - Use Case: If you are porting code from MATLAB/Python
scipy.integrateand need to reproduce the results exactly bit-for-bit (or close to it). Otherwise,Tsit5is usually slightly faster in Julia.
Hands-on Example
# 1. The Standard (High accuracy, standard speed)
sol_tsit = solve(prob, Tsit5())
# 2. The Quick & "Dirty" (Low accuracy, high speed)
sol_bs3 = solve(prob, BS3())
# 3. The MATLAB Legacy
sol_dp5 = solve(prob, DP5())3. Understanding Stiffness and Stiff Solvers
The Problem: Stiffness
Imagine you are walking through a room.
- Non-Stiff: You take regular steps.
- Stiff: You are walking through a room, but the floor is made of lava that cools and heats up randomly every microsecond. If you take a standard step, you burn. You have to take microscopic steps to survive.
Real world scenario: Chemical Kinetics.
You have a reaction where Substance A turns into B in 1 second, but Substance B explodes into Substance C in seconds.
If the solver takes a time step of 0.1 seconds, it completely misses the explosion dynamics. The simulation becomes unstable and the values oscillate towards infinity.
To fix this, non-stiff solvers reduce the step size to be tiny (). The simulation that should take 1 second now takes 10 years to compute.
The Solution: Implicit Solvers
Stiff solvers (Implicit methods) predict the future state and then "correct" it using linear algebra (Jacobians). They can take giant steps even when things are changing fast, because they are mathematically "stable."
The Heavy Hitters
1. Rodas5P (Rosenbrock)
- The Workhorse: The standard solver for stiff problems in Julia.
- Use Case: Small to medium systems ( < 1000 variables) that are stiff. Electrical circuits, standard chemical reactions.
- Note: If
Tsit5fails or freezes, tryRodas5P.
2. QNDF / FBDF (BDF Methods)
- The Scaler: Similar to
ode15sin MATLAB. - Use Case: Large systems (thousands of variables). Often used in discretized Partial Differential Equations (PDEs). BDF methods have less overhead per step than Rosenbrock methods for massive equations.
Simulation: The Van der Pol Oscillator (Classic Stiff Problem)
This is a standard test case. It represents an electrical circuit with a non-linear damping term.
function vanderpol!(du, u, p, t)
μ = 1000.0 # High stiffness parameter
du[1] = u[2]
du[2] = μ * ((1 - u[1]^2) * u[2]) - u[1]
end
u0 = [2.0, 0.0]
tspan = (0.0, 3000.0)
prob_stiff = ODEProblem(vanderpol!, u0, tspan)
# BAD IDEA: Using a non-stiff solver
# This will likely freeze or take forever because dt becomes tiny
# sol = solve(prob_stiff, Tsit5()) <--- Don't run this unless you have coffee ready.
# GOOD IDEA: Using a stiff solver
sol_stiff = solve(prob_stiff, Rodas5P())
println("Solved stiff problem with success!")4. Controlling Numerical Accuracy: abstol and reltol
In math class, answers are exact (). In numerical computing, answers are "close enough." You define what "close enough" means using tolerances.
The Concepts
reltol (Relative Tolerance)
- Definition: The allowed error as a percentage of the current value.
- Example:
reltol = 1e-3means "I want the answer to be accurate within 0.1%." - Behavior: If your variable is , an error of is acceptable. If your variable is , an error of is acceptable.
abstol (Absolute Tolerance)
- Definition: The absolute noise floor.
- The Problem it solves: If your variable crosses zero,
reltolbreaks (because of is ). You need a fixed threshold below which you don't care about precision anymore. - Example:
abstol = 1e-6. If the value is , the solver won't sweat trying to get it perfect.
Industry Standards vs. High Precision
- Default:
reltol=1e-3,abstol=1e-6. Good for plotting and general engineering. - High Precision:
reltol=1e-8,abstol=1e-8. Required for orbital mechanics (landing a rover on Mars) or chaotic systems.
⚠️ Warning: Tightening tolerances (making them smaller) drastically increases computation time. Only ask for the precision you actually need.
Practical Implementation
# Standard Engineering Accuracy (Fast)
sol_fast = solve(prob, Tsit5(), reltol=1e-3, abstol=1e-6)
# Scientific/High-Fidelity Accuracy (Slower)
sol_precise = solve(prob, Tsit5(), reltol=1e-9, abstol=1e-9)
# Tip: You can pass an array to abstol if different variables have different scales!
# Variable 1 is huge, Variable 2 is tiny
sol_scaled = solve(prob, Tsit5(), abstol=[1e-3, 1e-9])📝 Summary Checklist
- Start Default: Use
solve(prob). It uses a polyalgorithm to guess the best method. - Non-Stiff: If you need fixed performance, use
Tsit5(). - Stiff: If the simulation freezes or variables change at vastly different speeds, use
Rodas5P(). - Tolerances: The default (
1e-3) is fine for looking at the screen. Use1e-6or1e-8for physics and papers.
🔗 References & Further Reading
Challenge
Challenge: Solving a Stiff System with High Precision
You are tasked with solving a stiff differential equation that models the Van der Pol oscillator, which is pre-configured in the initial code as prob.
Your goal is to write the single line of code required to solve this problem according to the following specifications:
- The problem is known to be stiff. Do not use the default polyalgorithm or a non-stiff solver. Select the most appropriate solver for a small-to-medium sized stiff system.
- The solution requires a high degree of accuracy. Set the relative tolerance for the solver to
1e-8. - The two variables in the system have different precision requirements. You must set the absolute tolerance to
1e-10for the first state variable and1e-7for the second state variable.
Expected result
The correct solution involves specifying the Rodas5P algorithm for stiff systems and setting the tolerances as keyword arguments. The absolute tolerance abstol must be passed as an array to apply different values to each state variable.
sol = solve(prob, Rodas5P(), reltol=1e-8, abstol=[1e-10, 1e-7])Rodas5P(): This is the recommended workhorse solver for small-to-medium sized stiff ODE systems.reltol=1e-8: This sets the relative tolerance for the entire solution.abstol=[1e-10, 1e-7]: This provides a vector of absolute tolerances, applying1e-10to the first component (u[1]) and1e-7to the second (u[2]).