Math and Science with Python
Simpson's Rule in Python
Write composite Simpson's rule yourself, watch the error shrink as n grows, and compare with scipy.integrate.simpson.
Ce que vous allez apprendre
- The weights 1, 4, 2, 4, ..., 4, 1
- Why n must be even
- scipy.integrate.simpson for sampled data
Weights for n = 6
1
4
2
4
2
4
1
Parabolas instead of straight lines
Découvrez Simpson's Rule in Python avec un exemple pratique modifiable et exécutable en ligne.
Points clés
his the interval width and n must be even, or the function raisesValueError.- Odd-numbered points get weight 4 and even-numbered inner points weight 2.
- For
sin(x)from 0 to pi the error falls from9.4e-02at n = 2 to1.1e-08at n = 100. scipy.integrate.simpson(y, x=x)works on sampled values instead of a function.
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 math
import numpy as np
from scipy.integrate import simpson
def simpson_rule(f, a, b, n):
if n % 2:
raise ValueError("n must be even")
h = (b - a) / n
total = f(a) + f(b)
for i in range(1, n):
total += (4 if i % 2 else 2) * f(a + i * h) # weights 1 4 2 4 ... 4 1
return total * h / 3
# Integral of sin(x) from 0 to pi is exactly 2
for n in [2, 4, 10, 100]:
approx = simpson_rule(math.sin, 0, math.pi, n)
print(f"n = {n:>3} {approx:.10f} error {abs(approx - 2):.1e}")
# SciPy's simpson works on sampled points
x = np.linspace(0, math.pi, 101) # 101 points = 100 intervals
print(f"scipy simpson: {simpson(np.sin(x), x=x):.10f}")
Résultat de l’exécution
n = 2 2.0943951024 error 9.4e-02
n = 4 2.0045597550 error 4.6e-03
n = 10 2.0001095173 error 1.1e-04
n = 100 2.0000000108 error 1.1e-08
scipy simpson: 2.0000000108
Explication du code
Cet exemple montre Simpson's Rule in Python 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.