import numpy as np import matplotlib.pyplot as plt 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 def f(x): return np.sin(x) * np.exp(-0.1 * x) #first, plot the function: x = np.linspace(0, 20, 101) plt.plot(x, f(x)) plt.show() #solve f(x) = 0, for starting interval [0.1, 5] x_val, iter = bisection(f, a=0.1, b=5, eps=1E-5) print(f'Found approximate root x = {x_val:g} with f(x) = {f(x_val):g}, in {iter} iterations') """ Terminal> python halveringsmetoden.py Found approximate root x = 3.14159 with f(x) = -2.37995e-07, in 19 iterations """