Math and Science with Python
Interpolation in Python: np.interp and CubicSpline
Estimate values between measured points with linear interpolation, or draw a smooth curve through them with a cubic spline.
Ce que vous allez apprendre
- Linear interpolation with np.interp
- What happens outside the data range
- Smooth curves with scipy CubicSpline
Temperature at 4.5 h
np.interp
- 13.75
- straight line
CubicSpline
- 13.20
- smooth curve
Filling in between the points
Découvrez Interpolation in Python with NumPy and SciPy avec un exemple pratique modifiable et exécutable en ligne.
Points clés
np.interp(4.5, hours, temps)gives 13.75, halfway between 12.5 and 15.0.- The x values
xpmust be in increasing order. - Outside the range,
np.interpreturns the first or last value instead of extrapolating. CubicSplinegives a smooth curve, so 4.5 h becomes 13.20 instead of 13.75.
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.interpolate import CubicSpline
# Temperature measured every 3 hours
hours = np.array([0, 3, 6, 9, 12])
temps = np.array([14.0, 12.5, 15.0, 21.0, 24.5])
# Linear interpolation: straight lines between the points
print(f"np.interp at 4.5 h: {np.interp(4.5, hours, temps):.2f}")
print("np.interp at [1, 7, 10]:", np.interp([1, 7, 10], hours, temps).round(2).tolist())
# Outside the range np.interp repeats the end values
print("np.interp at 15:", float(np.interp(15, hours, temps)))
# Cubic spline: a smooth curve through the same points
spline = CubicSpline(hours, temps)
print(f"CubicSpline at 4.5 h: {float(spline(4.5)):.2f}")
print("CubicSpline at [1, 7, 10]:", spline([1, 7, 10]).round(2).tolist())
Résultat de l’exécution
np.interp at 4.5 h: 13.75
np.interp at [1, 7, 10]: [13.5, 17.0, 22.17]
np.interp at 15: 24.5
CubicSpline at 4.5 h: 13.20
CubicSpline at [1, 7, 10]: [13.11, 16.82, 22.81]
Explication du code
Cet exemple montre Interpolation in Python with NumPy and SciPy 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.