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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Solve Differential Equations in Python with solve_ivp avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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].

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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)
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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.

Explication du code

Cet exemple montre Solve Differential Equations in Python with solve_ivp en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon