CestBeau
- There are 21 roots of the function f(x) = cos(x) on the
interval [0, 65]. To which root will the bisection method
converge, starting with a = 0 and b = 65?
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
def f(x): return np.cos(x)
x=np.linspace(0, 65, 1000)
y=f(x)
plt.plot(x, y)
import numpy as np
def bisection(f,a,b,return_cnt = False):
y1 = f(a)
if y1 == 0:
return a
y2 = f(b)
if y2 == 0:
return b
if np.sign(y1)*np.sign(y2) > 0:
raise Exception('function has same signs at the endpoints')
cnt = 0
while abs(a-b) > a*10**(-15) and cnt < 100:
c = (a+b)/2
y3 = f(c)
if y3 == 0:
if return_cnt:
return c,cnt
else:
return c
if np.sign(y1)*np.sign(y3) < 0:
b = c
y2 = y3
elif np.sign(y2)*np.sign(y3) < 0:
a = c
y1 = y3
cnt = cnt+1
if return_cnt:
return c,cnt
else:
return c
bisection(f, 0, 65, True)
(58.11946409141122, 50)
From the code above it appears that, using values a=0 and b=65, the bisection method converges to the root 58.11946409141122. It does so in 50 iterations.