You are on page 1of 1

def newton_raphson(f, df, x0, tol=1e-6, max_iter=100):

"""
Implements the Newton-Raphson method to find the root of a function.
:param f: the function to find the root of
:param df: the derivative of the function
:param x0: the initial guess for the root
:param tol: the tolerance (default 1e-6)
:param max_iter: the maximum number of iterations (default 100)
:return: the approximate root of the function
"""
x = x0
for i in range(max_iter):
fx = f(x)
if abs(fx) < tol:
return x
dfx = df(x)
if dfx == 0:
break
x = x - fx / dfx
return x

# Define the function and its derivative


def f(x):
return x**3 - 2*x - 5

def df(x):
return 3*x**2 - 2

# Set the initial guess


x0 = 2

# Find the root using the Newton-Raphson method


root = newton_raphson(f, df, x0)

# Print the result


print("The root of the function is approximately:", root)

You might also like