CoCalc Public Files4 / 7 Notebook .ipynbOpen with one click!
Authors: Randy Cazales, Kaleb Cruz, Sharalee Jones
Compute Environment: Ubuntu 20.04 (Default)

Bisection Method

In [1]:
import numpy as np import matplotlib.pyplot as plt from math import exp, log, sin
In [3]:
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
In [6]:
x = np.arange(1,5,0.001) y = np.log(x)-np.sin(x) plt.plot(x,y) plt.show()
In [7]:
def f(x): return np.log(x)-np.sin(x)
In [8]:
bisection(1,5,f,0.001)
2.2197265625
In [9]:
f(2.2197265625)
0.0006532685362758972
In [ ]: