Lesson 14 of 18

Newton-Raphson Method

Newton's Method for Root-Finding

The Newton-Raphson method is an iterative algorithm for finding roots of equations — values of xx where f(x)=0f(x) = 0.

Starting from an initial guess x0x_0, it repeatedly improves the estimate:

x_{n+1} = x_n - rac{f(x_n)}{f'(x_n)}

def newton(f, df, x0, tol=1e-6):
    x = x0
    for _ in range(100):
        fx = f(x)
        if abs(fx) < tol:
            break
        x = x - fx / df(x)
    return round(x, 6)

# Find √2: solve x² - 2 = 0
f  = lambda x: x**2 - 2
df = lambda x: 2*x
print(newton(f, df, 1.0))   # 1.414214

Why It Works

Newton's method uses the tangent line at the current point to approximate where the function crosses zero. Each iteration gives quadratic convergence — the number of correct digits roughly doubles each step.

Convergence

The method converges quickly when:

  • The initial guess x0x_0 is close to the root
  • f(x)f'(x) is not near zero at the root

Applications

  • Root-finding in optimization (gradient = 0)
  • Solving implicit equations in physics
  • Computing square roots and logarithms in hardware

Your Task

Implement newton(f, df, x0, tol=1e-6) that returns the root of ff starting from x0x_0, rounded to 6 decimal places.

Pyodide loading...
Loading...
Click "Run" to execute your code.