| Hosted by CoCalc | Download
Kernel: Python 3 (system-wide)

Use the Bisection Method to find a root of the function f(x) = ln(x)-sin(x) in the interval (2,4) with an error bound of 0.001. Hint: Use a graphical method (like using Matplotlib, say) to get an idea of what values to use as the starting choices for a and b in the algorithm.

import numpy as np import matplotlib.pyplot as plt
x = np.linspace(2,4,100) y = np.log(x)-np.sin(x)
plt.plot(x,y,label='$f(x)$') plt.legend() plt.xlabel('x') plt.ylabel('y') plt.title('Bisection Method') plt.show()
Image in a Jupyter notebook
def bisection(a,b,f,err): c = (a+b)/2 while c-a>err: if f(c) == 0: return c elif f(a)*f(c) > 0: a = c else: b = c c = (a+b)/2 return c
bisection(2,2.5,p,0.001)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-5-55a8616adfcc> in <module> ----> 1 bisection(2,2.5,p,0.001) NameError: name 'p' is not defined