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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • 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

The problem

Numerical methods courses ask you to find roots like sqrt(2) or the solution of x**3 - x - 2 = 0 by iteration. Writing the method yourself shows how calculators and solvers really work, and why a good starting guess matters.

Think of it like this

Newton's method is like skiing down to the bottom of a slope by aiming along the slope you are standing on. You look at how steep the ground is right where you are, slide straight along that line to where it would hit the bottom, and look again from there.

From skiing to code
x⛷️ Where you are standing
df(x)📐 How steep the slope is here
x - f(x) / df(x)➡️ Slide along the slope to where it reaches zero
abs(step) < tol🏁 The step is tiny: you have arrived
Each step uses the slope at the current point.
In one sentence

The Newton-Raphson method finds a root of f by repeating x = x - f(x) / f'(x), which moves to where the tangent line at x crosses the x-axis.

Key points

  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.

When should you use it?

  • Square roots and other roots in numerical methods courses.
  • Solving equations inside simulations where speed matters.
  • Understanding how library solvers like fsolve work.

When not to use it

  • You cannot compute the derivative: use the secant or bisection method.
  • You have no good starting guess: bisection is slower but always converges on a sign change.

Example code

Open in editor →
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}")
Get a Run button for this example

Result of running the code

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

Code explanation

newton() takes the function f, its derivative df and a starting guess x0. Each round computes step = f(x) / df(x) and moves to x - step, which is where the tangent line meets the x-axis. For x**2 - 2 starting at 1.0 the guesses are 1.5, 1.4166666667 and 1.4142156863, and the step shrinks from 5.00e-01 to 1.59e-12 in five iterations. The loop stops when the step is smaller than tol, and raises an error after max_iter rounds in case the method does not converge.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  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.
Run in the Python compiler →

Common mistakes

Starting where the derivative is 0

At a flat point the tangent never crosses zero and f(x) / df(x) divides by zero.

Problem
newton(f, df, x0=0.0)
Fix
newton(f, df, x0=1.0)

Looping without a limit

If the method diverges, a plain while True never ends.

Problem
while abs(step) > tol:
Fix
for i in range(1, max_iter + 1):

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson