Math and Science with Python

Newton-Raphson Method in Python

Find a root by following tangent lines, and watch the number of correct digits double with every iteration.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • The Newton step x - f(x) / f'(x)
  • A stopping rule with a tolerance
  • Why it converges so fast, and when it fails
Guesses for sqrt(2)
1.0
1.5
1.41667
1.414216
1.4142136

Follow the tangent to the root

Découvrez Newton-Raphson Method in Python avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. Each iteration needs both f(x) and the derivative df(x).
  2. The loop stops when the step is smaller than tol.
  3. Near the root the correct digits roughly double: the step goes from 8.33e-02 to 2.45e-03 to 2.12e-06.
  4. max_iter stops the loop if the method never converges.

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 newton(f, df, x0, tol=1e-10, max_iter=50):
    x = x0
    for i in range(1, max_iter + 1):
        step = f(x) / df(x)       # tangent line hits zero at x - step
        x = x - step
        print(f"{i:>4}  {x:.10f}  {abs(step):.2e}")
        if abs(step) < tol:
            return x
    raise RuntimeError("Newton's method did not converge")

# Square root of 2: solve f(x) = x**2 - 2 = 0
f = lambda x: x**2 - 2
df = lambda x: 2 * x

print("iter  x             step")
root = newton(f, df, x0=1.0)
print(f"sqrt(2) = {root:.10f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

iter  x             step
   1  1.5000000000  5.00e-01
   2  1.4166666667  8.33e-02
   3  1.4142156863  2.45e-03
   4  1.4142135624  2.12e-06
   5  1.4142135624  1.59e-12
sqrt(2) = 1.4142135624

Explication du code

Cet exemple montre Newton-Raphson 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