Differential Equations: Initial & Boundary Value Problems
Dynamic systems in physics and engineering—heat flow, chemical kinetics, vibrations, and orbital mechanics—are modeled as ordinary differential equations (ODEs).
1. Initial Value Problems: solve_ivp
scipy.integrate.solve_ivp is the standard solver for systems of the form:
dy/dt = f(t, y), y(t0) = y0
Note the parameter order in solve_ivp: fun(t, y) takes time t first, then state vector y. (The older deprecated odeint took y first).
Selecting the Right Integration Method
| Solver | Family | Order | When to Use |
|---|---|---|---|
'RK45' | Explicit Runge-Kutta | 5(4) | Default for smooth, non-stiff systems |
'DOP853' | Explicit Dormand-Prince | 8 | High-precision non-stiff simulations (rtol < 1e-7) |
'Radau' | Implicit Runge-Kutta | 5 | Stiff systems, chemical reactions, high accuracy |
'BDF' | Backward Differentiation | 1 to 5 | Stiff systems, large finite-difference ODE systems |
'LSODA' | Adams/BDF hybrid | Adaptive | Auto-switches between stiff and non-stiff modes |
Solving a Damped Harmonic Oscillator
Convert the second-order equation into a first-order system with state :
Example
Output:
2. Event Detection: Stopping at Exact Crossings
Events allow you to locate when a condition occurs—such as a bouncing ball hitting the ground or a cooling tank reaching target temperature:
Example
Output:
3. Stiff Differential Equations (Radau, BDF)
A system is stiff when fast and slow dynamics occur simultaneously. An explicit solver like 'RK45' is forced to take tiny steps to stay numerically stable, requiring hundreds of thousands of steps. Implicit solvers ('Radau', 'BDF') step over fast decaying transients safely:
Example
Output:
4. Boundary Value Problems: solve_bvp
In BVPs, boundary conditions are specified at multiple spatial locations. scipy.integrate.solve_bvp uses fourth-order collocation on an adaptive mesh:
Solve with and (analytical solution ):
Example
Output:
5. Try It Yourself
Problem: Radioactive Decay with solve_ivp
A radioisotope decays according to with decay constant . Starting from atoms at , compute the population at .
Show solution
import numpy as np
from scipy.integrate import solve_ivp
lam = 0.2
sol = solve_ivp(lambda t, N: [-lam * N[0]], (0.0, 5.0), [500.0], method='RK45')
print(f"Population at t=5s: {sol.y[0, -1]:.2f}")