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.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
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

  1. h is the interval width and n must be even, or the function raises ValueError.
  2. Odd-numbered points get weight 4 and even-numbered inner points weight 2.
  3. For sin(x) from 0 to pi the error falls from 9.4e-02 at n = 2 to 1.1e-08 at n = 100.
  4. 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}")
Obtenir un bouton Run pour cet exemple

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.

  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