Math and Science with Python

Solve Differential Equations in Python with solve_ivp

Solve ordinary differential equations with scipy.integrate.solve_ivp, from radioactive decay to a spring.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • 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
N(t) for dN/dt = -0.5 N
t = 0
1
2
3
4
100
60.65
36.79
22.31
13.53

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.

From a hike to code
decay(t, N)🪧 The signpost: which way to go from here
y0=[100]🏠 Where the hike starts
solve_ivp(decay, (0, 4), ...)🥾 Walk in small steps from t = 0 to 4
t_eval=times📸 Take a photo at these times
Start somewhere known and follow the direction of change.
In one sentence

An 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

  1. The function takes (t, y) and returns the derivatives, even if it does not use t.
  2. y0 is a list, because solve_ivp always works with a vector of values.
  3. t_eval picks the times in result.t; the values are in result.y[0].
  4. x'' = -x becomes the pair x' = v, v' = -x with 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_ivp only handles ODEs.

Example code

Open in editor →
main.py
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)
Get a Run button for this example

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.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Swapping the arguments of the function

solve_ivp calls fun(t, y), with time first.

Problem
def decay(N, t):
Fix
def decay(t, N):

Passing y0 as a single number

y0 must be a list or array, even for one equation.

Problem
solve_ivp(decay, (0, 4), 100)
Fix
solve_ivp(decay, (0, 4), [100])

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson