Solve Differential Equations in Python with solve_ivp
Solve ordinary differential equations with scipy.integrate.solve_ivp, from radioactive decay to a spring.
- Writing an ODE as a function f(t, y)
- t_span, y0 and t_eval
- Turning a second-order ODE into two first-order ones
Step the solution forward in time
The problem
Physics, chemistry and biology describe change with differential equations: decay, cooling, population growth, springs and circuits. Most of them cannot be solved by hand, and even when they can, a numerical solution is a quick check.
Think of it like this
Solving an ODE is like following directions on a hike where each signpost only tells you which way to go from where you stand. You start at a known place and keep taking small steps in the direction the signposts give.
decay(t, N)🪧 The signpost: which way to go from herey0=[100]🏠 Where the hike startssolve_ivp(decay, (0, 4), ...)🥾 Walk in small steps from t = 0 to 4t_eval=times📸 Take a photo at these timesAn ordinary differential equation gives the rate of change dy/dt as a function of t and y. scipy.integrate.solve_ivp(fun, t_span, y0) solves it numerically from the starting value y0.
Key points
- The function takes
(t, y)and returns the derivatives, even if it does not use t. y0is a list, becausesolve_ivpalways works with a vector of values.t_evalpicks the times inresult.t; the values are inresult.y[0].x'' = -xbecomes the pairx' = v,v' = -xwith the state[x, v].
When should you use it?
- Radioactive decay, cooling and population models.
- Motion with forces: springs, pendulums, projectiles with air resistance.
- Chemical reaction rates and circuits.
When not to use it
- The equation has a simple exact solution you need as a formula: try
sympy.dsolve. - Partial differential equations (several variables):
solve_ivponly handles ODEs.
Example code
import numpy as np
from scipy.integrate import solve_ivp
# Radioactive decay: dN/dt = -k * N, with N(0) = 100
k = 0.5
def decay(t, N):
return -k * N
times = [0, 1, 2, 3, 4]
result = solve_ivp(decay, t_span=(0, 4), y0=[100], t_eval=times, rtol=1e-8)
print("t solve_ivp exact")
for t, N in zip(result.t, result.y[0]):
exact = 100 * np.exp(-k * t)
print(f"{t:.0f} {N:9.4f} {exact:8.4f}")
# Second-order ODE as two first-order ones: x'' = -x (a spring)
def spring(t, state):
x, v = state
return [v, -x]
sol = solve_ivp(spring, (0, np.pi), [1, 0], t_eval=[np.pi / 2, np.pi], rtol=1e-8)
print("Spring x at pi/2 and pi:", (sol.y[0].round(4) + 0.0).tolist())
print("Status:", sol.message)
Result of running the code
t solve_ivp exact
0 100.0000 100.0000
1 60.6531 60.6531
2 36.7879 36.7879
3 22.3130 22.3130
4 13.5335 13.5335
Spring x at pi/2 and pi: [0.0, -1.0]
Status: The solver successfully reached the end of the integration interval.
Code explanation
decay(t, N) returns dN/dt = -k * N; solve_ivp needs the time span (0, 4), the starting value y0=[100] and, with t_eval, the times to report. The results match the exact solution 100 * exp(-k * t) to four decimals, for example 60.6531 at t = 1. A second-order equation like x'' = -x is split into two first-order ones, x' = v and v' = -x, so the state is [x, v]. The spring starts at x = 1, is at 0.0 after pi/2 and at -1.0 after pi.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Swapping the arguments of the function
solve_ivp calls fun(t, y), with time first.
def decay(N, t):
def decay(t, N):
Passing y0 as a single number
y0 must be a list or array, even for one equation.
solve_ivp(decay, (0, 4), 100)
solve_ivp(decay, (0, 4), [100])
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.