Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 337
Image: ubuntu2004
Kernel: Python 3 (system-wide)

Bisection Method

import numpy as np import matplotlib.pyplot as plt from math import exp, log, sin
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
x = np.arange(1,5,0.001) y = np.log(x)-np.sin(x) plt.plot(x,y) plt.show()
Image in a Jupyter notebook
def f(x): return np.log(x)-np.sin(x)
bisection(1,5,f,0.001)
2.2197265625
f(2.2197265625)
0.0006532685362758972