Nonlinear equation I

Bound the solution

Procedures

Once you have a bracket refine the root

Bisection

nonlinear

Error

Regula Falsi

nonlinear

Convergence

Consider: nonlinear

Bisection example

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

function bisection(f, a, b, tol=1E-5, maxit=10000)
    
    fa = f(a)
    fb = f(b)
    
    if fa==0 return a, 0 end
    if fb==0 return b, 0 end
    
    if (fa>=0 && fb>=0) || (fa<=0 && fb<=0)
        println("Error, a and b don't bracket the root")
        return NaN, -1
    end
    
    for nit in 1:maxit
        
        c = 0.5*(a+b)
        fc = f(c)
        if fc == 0 return c, nit end
        
        if (fc > 0 && fa < 0) || (fc < 0 && fa > 0)
            b = c
            fb = fc
        else
            a = c
            fa = fc
        end

        if (abs(fc) <= tol) || (abs((b-a)/c) <= tol)
            return c, nit
        end
    end
    
    println("Warning, no convergence in $maxit iterations")
    c, maxit
end
        
#--------------------        

func1(x) = (x-2.)^2 - 1.

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

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

println("Solution x = $x found in $nit iterations")
println("f(x) = $(func1(x))")
Solution x = 3.0000000074505806 found in 26 iterations
f(x) = 1.4901161193847656e-8

Compare with nlsolve

import NLsolve: nlsolve

function func1!(F,x)
    F[1] = (x[1] - 2.0)^2 - 1.0 
end

xguess  = [20.]
results = nlsolve(func1!, xguess)

println("Solution x = $(results.zero)")
Solution x = [3.000000000000861]