Newton Raphson Method in Python

 

Newton-Raphson Method in Python

Newton's method, also known as the Newton-Raphson method, is a powerful numerical technique used for finding the roots of a real-valued function. Named after Sir Isaac Newton and Joseph Raphson, this method is based on the idea of linear approximation. In this blog post, we'll explore the Newton-Raphson method, its mathematical formulation, and how it can be implemented in Python.



Understanding the Newton-Raphson Method

Imagine you have a function �(�) and you want to find the value of � such that �(�)=0. The Newton-Raphson method starts with an initial guess �0 and iteratively refines this guess to get closer to the root. It uses the tangent line to the graph of �(�) at the point �� to predict a better guess ��+1 for the root.

Mathematical Formulation

Given a function �(�), the Newton-Raphson method iteratively updates the current guess �� using the formula:

��+1=��−�(��)�′(��)

Where:

  • �′(��) is the derivative of �(�) at the point ��.

This process is repeated until the difference between consecutive approximations is within a specified tolerance level.

Implementing the Newton-Raphson Method in Python


Code :

def newton_raphson(func, derivative, initial_guess, tol=1e-6, max_iter=100):

    """

    Find the root of a function using the Newton-Raphson method.


    Args:

    - func (callable): The function for which to find the root.

    - derivative (callable): The derivative of the function.

    - initial_guess (float): Initial guess for the root.

    - tol (float): Tolerance for the root approximation (default: 1e-6).

    - max_iter (int): Maximum number of iterations (default: 100).


    Returns:

    - float: Approximation of the root.

    """

    x = initial_guess

    for _ in range(max_iter):

        fx = func(x)

        if abs(fx) < tol:

            return x

        x -= fx / derivative(x)

    raise ValueError("Newton-Raphson method did not converge")


# Example usage

def f(x):

    return x**2 - 4


def df(x):

    return 2*x


root = newton_raphson(f, df, 3)

print("Approximate root:", root)


Post a Comment

0 Comments