Bisection Method in Python
Trap a root between two points and halve the interval until it is as small as you need.
- The sign-change rule f(a) * f(b) < 0
- Halving the interval in a loop
- How many steps a tolerance needs
- 1
[1, 2]f(1) < 0, f(2) > 0 - 2
[1.5, 2]f(1.5) < 0: keep the right half - 3
[1.5, 1.75]f(1.75) > 0: keep the left half - 4
1.521380after 19 steps
Halve the interval every step
Découvrez Bisection Method in Python avec un exemple pratique modifiable et exécutable en ligne.
Points clés
f(a) * f(b) > 0means no sign change, so the function raisesValueError.- Each step computes
midand keeps either[a, mid]or[mid, b]. - The interval halves every step, so
tol=1e-6takes 19 steps andtol=1e-12takes 39. - The answer is the middle of the final interval.
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
def bisection(f, a, b, tol=1e-6):
if f(a) * f(b) > 0:
raise ValueError("f(a) and f(b) must have opposite signs")
steps = 0
while (b - a) / 2 > tol:
mid = (a + b) / 2
steps += 1
if f(a) * f(mid) <= 0: # the root is in the left half
b = mid
else: # the root is in the right half
a = mid
return (a + b) / 2, steps
# Root of x**3 - x - 2 between 1 and 2
f = lambda x: x**3 - x - 2
root, steps = bisection(f, 1, 2)
print(f"Root: {root:.6f} after {steps} steps")
print(f"f(root) = {f(root):.2e}")
# The same interval to a tighter tolerance needs more steps
root, steps = bisection(f, 1, 2, tol=1e-12)
print(f"Root: {root:.12f} after {steps} steps")
try:
bisection(f, 2, 3)
except ValueError as error:
print("Error:", error)
Résultat de l’exécution
Root: 1.521380 after 19 steps
f(root) = 4.27e-06
Root: 1.521379706805 after 39 steps
Error: f(a) and f(b) must have opposite signs
Explication du code
Cet exemple montre Bisection Method 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.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
Tous les défisOutils 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.