Nonlinear 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 (abs(fc) <= tol) || (abs((b-a)/c) <= tol)
            return c, nit
        end
        
        if (fc > 0 && fa < 0) || (fc < 0 && fa > 0)
            b = c
            fb = fc
        else
            a = c
            fa = fc
        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 = 2.9999999962747097 found in 27 iterations
f(x) = -7.450580596923828e-9