Professional Documents
Culture Documents
"""
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
def df(x):
return 3*x**2 - 2