Math and Science with Python

Bisection Method in Python

Trap a root between two points and halve the interval until it is as small as you need.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • The sign-change rule f(a) * f(b) < 0
  • Halving the interval in a loop
  • How many steps a tolerance needs
x**3 - x - 2 on [1, 2]
  1. 1[1, 2]f(1) < 0, f(2) > 0
  2. 2[1.5, 2]f(1.5) < 0: keep the right half
  3. 3[1.5, 1.75]f(1.75) > 0: keep the left half
  4. 41.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

  1. f(a) * f(b) > 0 means no sign change, so the function raises ValueError.
  2. Each step computes mid and keeps either [a, mid] or [mid, b].
  3. The interval halves every step, so tol=1e-6 takes 19 steps and tol=1e-12 takes 39.
  4. 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

main.py
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)
Obtenir un bouton Run pour cet exemple

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.

  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.

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éfis

Outils pour cette leçon