Bisection
Bisection
import numpy as np
import matplotlib.pyplot as plt
def bisection(f,a,b,tol):
if a >= b or f(a)*f(b) >= 0 or tol <=0 :
print("Bisection method fails.")
return None
n = math.ceil(math.log(b-a,2)-math.log(tol,2))
print(n)
for k in range(n):
p = (a+b)/2
fp = f(p)
if(fp * f(a) < 0):
b = p
fb = fp
else:
a = p
fa = fp
p = (a+b)/2
return p
tol = 0.000000001
f = lambda x: x**3 - 30*x**2 + 2552
a = 0
b = 20
print(bisection(f, a, b, tol))
t = np.linspace(0,20,num=1000)
y = t**3 - (30)*(t**2) + 2552
fig = plt.figure(num=0,dpi=120)
plt.plot(t,y,label= 'f(x)')
plt.title("Biseccion")
plt.show()