import numpy as np
import matplotlib.pyplot as plt
#----------------
def bisection(f, a, b, tol=1E-4, 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 np.abs(fc) <= tol or np.abs((b-a)/c) <= tol:
return c, k
if fa*fc <= 0:
b = c
fb = fc
else:
a = c
fa = fc
print(f"no convergence in {maxit} iterations")
return c, maxit
#----------------
def f(x): return (x-2.0)**2 - 1.0
x,k = bisection(f, 2.0, 100.0)
print(x,k)
print(f(x))
3.0000228881835938 18
4.577689105644822e-05