Nonlinear equation I

Bound the solution

Procedures

Once you have a bracket refine the root

Bisection

bisection 2

Error

Regula Falsi

RF2

Convergence

Consider: convergence

Bisection example

Find root of $f(x)=(x-2)^2 - 1$.

import numpy as np
def bisection(f, a, b, tol=1E-5, maxit=10000):
    
    fa = f(a)
    fb = f(b)

    if fa==0: return a, 0
    if fb==0: return b, 0

    if fa*fb > 0.0:
        print("a, b don't bracket the root, try again")
        return np.nan, -1

    for k in range(1,maxit+1):

        c = 0.5*(a+b)
        fc = f(c)
        if fc==0: return c, k

        if fa*fc <= 0: 
            b = c
        else:
            a = c

        if np.abs(fc) <= tol or np.abs((b-a)/c) <= tol:
            return c, k

    print(f"no convergence in {maxit} iterations")
    return c, maxit
        
#--------------------        

def func1(x):
    return (x-2)**2 - 1

#--------------------        

x, nit = bisection(func1, 2., 3.5, tol=1E-8, maxit=100)

print(f"Solution x = {x} found in {nit} iterations")
print(f"f(x) = {func1(x)}")
Solution x = 3.0000000074505806 found in 26 iterations
f(x) = 1.4901161193847656e-08

Compare with fsolve

from scipy.optimize import fsolve

xguess = 2
x = fsolve(func1, xguess)[0]

print(f"Solution x = {x}")
Solution x = 3.0