""" Simple implentation of the bisection method. The function takes a tolerance as argument in addition to the function f and the interval bounds a and b, and returns the approximate solution x and the number of iterations used. """ def bisection(f, a, b, eps): fa = f(a) if fa * f(b) > 0: return None, 0 # Alternativ: raise ValueError( # f'Ingen fortegnsskifte i [{a:g},{b:g}]') i = 0 # iterasjonsteller while b - a > eps: i += 1 m = (a + b)/2.0 fm = f(m) if fa * fm <= 0: b = m # roten er i venstre halvdel av [a,b] else: a = m # roten er i høyre halvdel av [a,b] fa = fm return m, i #solve the linear equation 2x - 3 = 0 print(bisection(f=lambda x: 2 * x - 3, a=0, b=10, eps=1E-5))