# 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 $�\left(�\right)$ and you want to find the value of $�$ such that $�\left(�\right)=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 $�\left(�\right)$ at the point ${�}_{�}$ to predict a better guess ${�}_{�+1}$ for the root.

### Mathematical Formulation

Given a function $�\left(�\right)$, the Newton-Raphson method iteratively updates the current guess ${�}_{�}$ using the formula:

${�}_{�+1}={�}_{�}-\frac{�\left({�}_{�}\right)}{{�}^{\mathrm{\prime }}\left({�}_{�}\right)}$

Where:

• ${�}^{\mathrm{\prime }}\left({�}_{�}\right)$ is the derivative of $�\left(�\right)$ 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)