math4610

Routine Name: HybridSecant

Author: David Merkley

Language: Python

Description/Purpose: Approximates a root using a hybrid of the Secant method and Bisection method.

Input: a function f, a and b so they’re opposite signs, tolerance, max iterations

Output: Approximate root

Implementation/Code:

def newton(f, fx, derivf, x):
    return x - fx / derivf(x)

def bisection(f, fa, fb, a, b):
    # Different signs for f(a) and f(b)
    if fa > 0 and fb < 0 or fa < 0 and fb > 0:
        counter = 0
        while counter in range(5):
            c = (a + b) / 2
            fc = f(c)
            if (fa * fc < 0):
                fb = fc
                b = c
            else:
                fa = fc
                a = c
            counter = counter + 1
        c = (a + b) / 2
        return a, b, c
    else:
        print("Values were not opposite signs")

def hybridMethod(f, derivf, a, b, tol=1e-10, maxiter=1e10):
    c = (a + b) / 2
    fa = f(a)
    fb = f(b)
    fc = f(c)
    for counter in range(int(maxiter)):
        c = newton(f, fc, derivf, c)
        if c < a or c > b:
            a, b, c = bisection(f, fa, fb, a, b)
            fc = f(c)
        else:
            fc = f(c)
            if fa * fc < 0:
                fb = fc
                b = c
            else:
                fa = fc
                a = c
        error = b - a
        if error < tol:
            return c
    print("No root found")