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.
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
- 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].
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)
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.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Traceur de courbes en ligne : tracer des points et des fonctionsTracez des points, un tableau collé ou des fonctions comme sin(x) en ligne et téléchargez le graphique en PNG. Traceur gratuit qui vous donne aussi le code Python avec Matplotlib.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.
- Exercices Python corrigés : s'entraîner en ligne gratuitementExercices Python corrigés pour débutants et défis vérifiés automatiquement, du plus facile au plus difficile. À faire dans le navigateur, sans installation.