Back to the blog

Newton-Raphson Symbolic Method with Python

Implement the Newton-Raphson method using sympy to derive the function analytically — without approximating the derivative through finite differences. Wrapped in a reusable class.

The classical recurrence:

\[x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}\]
import sympy as sp

class NewtonRaphsonSymbolic:
    def __init__(self, f, x0):
        """
        Args:
            x: Symbolic variable
            x0: Point to start iterations
            f: Symbolic function
            df: Symbolic derivative
        """
        x = sp.symbols('x')
        self.x0 = x0
        self.f = sp.sympify(f)
        self.df = sp.diff(f, x)

    def NewtonRaphsonSolve(self, tol = 1e-10, max_iteration = 100):
        """
        Returns:
            x: Root of the function
        """
        x_previous = self.x0
        iteration = 0
        while 1:
            x = x_previous - self.f.evalf(subs = {'x': x_previous}) / self.df.evalf(subs = {'x': x_previous})

            if abs(x - x_previous) < tol or iteration >= max_iteration:
                break
            x_previous = x
            iteration = iteration + 1

        return x

function_value = NewtonRaphsonSymbolic("x**3 - 5*x**2 + 7*x - 1", 4)
root = function_value.NewtonRaphsonSolve()
print(f"The root of the function is: {root:.4f}")

Running it on \(f(x) = x^3 - 5x^2 + 7x - 1\) with \(x_0 = 4\):

The root of the function is: 0.1607

The animation follows the code's 35 iterations: at each one, the tangent at \(x_n\) crosses the axis at \(x_{n+1}\).

Newton-Raphson convergence

Even though we start from \(x_0 = 4\) (far from the only real root, which is near \(0.16\)), the method converges after several iterations. The behavior depends strongly on the local curvature: with initial points near extrema (\(f'(x) \approx 0\)) the division explodes and iterations diverge.

Advantages of the symbolic variant:

  • The derivative is exact, not a numerical approximation — useful when f involves nested exponentials, logarithms, or trigonometric functions.
  • The code does not depend on floating-point arithmetic until the evaluation step, so it maintains high precision.
  • It can be reused with any function: just pass the expression as a string.

Considerations:

  • sympy is slower than a purely numerical implementation (for example scipy.optimize.newton), so for high-performance problems it is worth differentiating once symbolically and then compiling with sp.lambdify.
  • Always verify the domain of definition before iterating: if \(f'(x_n) = 0\), the method fails.

Installation:

pip install sympy
Back to the blog