math4610

Routine Name: NewtonRoot

Author: David Merkley

Language: Python

Description/Purpose: Uses Newton’s method to approximate a root

Input: a function f, derivative derivf, starting point x0, tolerance, max iteration

Output: Approximation of root

Implementation/Code:

def newtonMethod(f, derivf, x0, tol=1e-10, maxiter=1e5):
    fx = f(x0)
    error = 10 * tol
    counter = 0
    while counter in range(int(maxiter)) and error > tol:
        x = x0 - fx / derivf(x0)
        error = abs(x - x0)
        fx = f(x)
        if error < tol:
            return x
        x0 = x
    print("No root was found")