math4610

Routine Name: SecantMethod

Author: David Merkley

Language: Python

Description/Purpose: Approximates a root with the Secant method

Input: a function f, initial point x0, initial point x1, tolerance, max iteration

Output: Approximation of root

Implementation/Code:

def secantMethod(f, x0, x1, tol=1e-10, maxiter=1e10):
    xk1 = x1
    xk0 = x0
    f1 = f(xk1)
    f0 = f(xk0)
    error = 10 * tol
    counter = 0
    while counter in range(int(maxiter)) and error > tol:
        error = abs(xk1 - xk0)
        xk2 = xk1 - f1 / ((f1 - f0) / (xk1 - xk0))
        xk0 = xk1
        xk1 = xk2
        f0 = f1
        f1 = f(xk1)
        if error < tol:
            return xk1
    print("No root was found")