Consider:
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)
if abs(a-b) <= tol
return c, nit
end
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
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.9999999990686774 found in 29 iterations f(x) = -1.862645149230957e-9
fsolve
¶import NLsolve: nlsolve
function func1!(F,x)
F[1] = func1(x[1])
end
xguess = [2.]
results = nlsolve(func1!, xguess)
println("Solution x = $(results.zero)")
Solution x = [2.0]