SciPy Differential Equations
A differential equation describes how something changes: a cup of tea cools at a rate proportional to how much hotter it is than the room; a population grows faster when it is larger; a pendulum accelerates back towards the centre. Instead of giving the quantity directly, the equation gives its rate of change. Solving it means recovering the quantity over time.
SciPy's solve_ivp() (solve an initial value problem) handles ordinary differential equations (ODEs) of the form
dy/dt = f(t, y), y(t0) = y0You provide the function f, the time span and the starting value; SciPy steps forward in time.
A first example: cooling tea
Newton's law of cooling says dT/dt = -k (T - T_room). Tea starts at 90 °C in a 20 °C room with k = 0.1 per minute:
import numpy as np
from scipy.integrate import solve_ivp
def cooling(t, T, k, room):
return -k * (T - room)
sol = solve_ivp(cooling, t_span=(0, 30), y0=[90], args=(0.1, 20),
t_eval=[0, 5, 10, 20, 30])
for t, T in zip(sol.t, sol.y[0]):
print(f"t = {t:4.0f} min T = {T:5.1f} C")
print("solver status:", sol.message)t = 0 min T = 90.0 C
t = 5 min T = 62.4 C
t = 10 min T = 45.8 C
t = 20 min T = 29.5 C
t = 30 min T = 23.5 C
solver status: The solver successfully reached the end of the integration interval.
Key points of the call:
| Argument / field | Meaning |
|---|---|
fun(t, y, *args) |
Returns dy/dt. y is always an array, even for one equation |
t_span=(t0, t1) |
Start and end time |
y0 |
Initial values, one per equation |
t_eval |
Times at which you want the solution stored |
args |
Extra parameters passed to fun |
sol.t, sol.y |
Output times and values; sol.y has one row per equation |
Checking accuracy
This equation has an exact solution, T(t) = room + (T0 - room) e^(-kt), so we can measure the solver's error and see the effect of tighter tolerances (rtol, atol):
import numpy as np
from scipy.integrate import solve_ivp
def cooling(t, T):
return -0.1 * (T - 20)
exact = 20 + 70 * np.exp(-0.1 * 30)
for rtol in [1e-3, 1e-6, 1e-9]:
sol = solve_ivp(cooling, (0, 30), [90], rtol=rtol, atol=1e-12)
error = abs(sol.y[0, -1] - exact)
print(f"rtol={rtol:.0e}: steps={len(sol.t):3d}, error={error:.1e}")rtol=1e-03: steps= 6, error=8.3e-03
rtol=1e-06: steps= 15, error=6.4e-06
rtol=1e-09: steps= 46, error=6.0e-09
Tighter tolerances take more steps but give more accurate answers. The defaults (rtol=1e-3) are fine for plotting but too loose for precise numbers.
Systems of equations
Many models have several interacting quantities. The classic predator–prey (Lotka–Volterra) model tracks rabbits r and foxes f: rabbits multiply, foxes eat rabbits, foxes starve without them. Return one derivative per variable:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
def predator_prey(t, z, a, b, c, d):
r, f = z
return [a * r - b * r * f, # rabbits
c * r * f - d * f] # foxes
t = np.linspace(0, 40, 400)
sol = solve_ivp(predator_prey, (0, 40), [20, 5], args=(0.5, 0.05, 0.01, 0.4),
t_eval=t, rtol=1e-8)
rabbits, foxes = sol.y
plt.plot(t, rabbits, label="rabbits")
plt.plot(t, foxes, label="foxes")
plt.xlabel("time")
plt.ylabel("population")
plt.legend()
plt.show()
print(f"rabbits range: {rabbits.min():.1f} to {rabbits.max():.1f}")
print(f"foxes range : {foxes.min():.1f} to {foxes.max():.1f}")rabbits range: 13.3 to 89.7
foxes range : 3.8 to 20.8
The two populations rise and fall in repeating cycles, with the fox peak lagging behind the rabbit peak.
Higher-order equations
solve_ivp only accepts first-order equations, but any higher-order equation can be rewritten as a system. A pendulum obeys θ'' = -(g/L) sin θ. Introduce the angular velocity ω = θ', and you get two first-order equations: θ' = ω and ω' = -(g/L) sin θ.
import numpy as np
from scipy.integrate import solve_ivp
g, L = 9.81, 1.0
def pendulum(t, state):
theta, omega = state
return [omega, -(g / L) * np.sin(theta)]
# Released from 30 degrees; detect each time it swings through the bottom
def crosses_zero(t, state):
return state[0]
crosses_zero.direction = -1 # only count crossings going downwards
sol = solve_ivp(pendulum, (0, 10), [np.radians(30), 0], events=crosses_zero,
rtol=1e-9, atol=1e-9)
times = sol.t_events[0]
print("first crossings (s):", np.round(times[:3], 3))
print(f"period = {np.diff(times).mean():.4f} s")
print(f"small-angle formula 2*pi*sqrt(L/g) = {2 * np.pi * np.sqrt(L / g):.4f} s")first crossings (s): [0.51 2.551 4.592]
period = 2.0410 s
small-angle formula 2*pi*sqrt(L/g) = 2.0061 s
Events let the solver find the exact moments when a function of the state crosses zero — here, each time the pendulum passes through the vertical in the same direction, which is once per period. The real period at 30° is slightly longer than the small-angle formula predicts.
Choosing a method
| Method | Type | Use for |
|---|---|---|
"RK45" (default) |
explicit Runge–Kutta | Most everyday problems |
"DOP853" |
high-order explicit | Very high accuracy |
"Radau", "BDF" |
implicit | Stiff problems (very fast and very slow processes together) |
"LSODA" |
automatic switching | When you don't know whether it's stiff |
Tip: If
solve_ivpcrawls with thousands of tiny steps, your problem is probably stiff — trymethod="BDF"or"Radau".
Test yourself
What shape does sol.y have for a system of 2 equations evaluated at 100 times?
- (100, 2)
- (2, 100)
- (100,)
- (2,)
How do you solve a second-order ODE such as θ'' = -sin θ with solve_ivp?
- Pass order=2
- Rewrite it as two first-order equations (θ' = ω, ω' = -sin θ)
- Call solve_ivp twice
- It's not possible
Which method should you try for a stiff problem?
- RK45
- DOP853
- BDF
- Nelder-Mead