Newton-Raphson Method in Python
Find a root by following tangent lines, and watch the number of correct digits double with every iteration.
- The Newton step x - f(x) / f'(x)
- A stopping rule with a tolerance
- Why it converges so fast, and when it fails
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.
x⛷️ Where you are standingdf(x)📐 How steep the slope is herex - f(x) / df(x)➡️ Slide along the slope to where it reaches zeroabs(step) < tol🏁 The step is tiny: you have arrivedThe 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
- Each iteration needs both
f(x)and the derivativedf(x). - The loop stops when the step is smaller than
tol. - Near the root the correct digits roughly double: the step goes from
8.33e-02to2.45e-03to2.12e-06. max_iterstops 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
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}")
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.
- 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.
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.
newton(f, df, x0=0.0)
newton(f, df, x0=1.0)
Looping without a limit
If the method diverges, a plain while True never ends.
while abs(step) > tol:
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 challengesTools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.