Math and Science with Python
Integrals in Python: SciPy quad and SymPy integrate
Get the area under a curve as a number with scipy.integrate.quad, or the exact antiderivative with SymPy.
Ce que vous allez apprendre
- Numerical integration with quad
- Infinite limits and functions with no antiderivative
- Exact integrals with sympy.integrate
quad(lambda x: x**2, 0, 3)
- 1
f(x) = x**2The curve - 2
[0, 3]The interval - 3
9.000000Area under the curve
Two ways to integrate
Découvrez Integrals in Python with SciPy and SymPy avec un exemple pratique modifiable et exécutable en ligne.
Points clés
quad(f, a, b)returns a pair: the value and an estimate of its error.- The function can be a
lambdaor any Python function of one number. - Use
math.infas a limit for an integral to infinity. sp.integrate(expr, x)gives the antiderivative;sp.integrate(expr, (x, a, b))gives an exact number.
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
from scipy.integrate import quad
import sympy as sp
# Numerical: integrate x**2 from 0 to 3 with SciPy
area, error = quad(lambda x: x**2, 0, 3)
print(f"quad x**2 on [0, 3]: {area:.6f}")
print("Error estimate below 1e-10:", error < 1e-10)
# A function with no simple antiderivative: exp(-x**2) from 0 to 1
value, _ = quad(lambda x: math.exp(-x**2), 0, 1)
print(f"quad exp(-x**2) on [0, 1]: {value:.6f}")
# Infinite limits work too
value, _ = quad(lambda x: math.exp(-x), 0, math.inf)
print(f"quad exp(-x) on [0, inf): {value:.6f}")
# Exact: SymPy gives the antiderivative and the definite integral
x = sp.symbols("x")
print("Antiderivative of x*sin(x):", sp.integrate(x * sp.sin(x), x))
print("Exact integral of x**2 on [0, 3]:", sp.integrate(x**2, (x, 0, 3)))
Résultat de l’exécution
quad x**2 on [0, 3]: 9.000000
Error estimate below 1e-10: True
quad exp(-x**2) on [0, 1]: 0.746824
quad exp(-x) on [0, inf): 1.000000
Antiderivative of x*sin(x): -x*cos(x) + sin(x)
Exact integral of x**2 on [0, 3]: 9
Explication du code
Cet exemple montre Integrals in Python with SciPy and SymPy 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.