Bisection 1
Bisection 1
August 9, 2020
%matplotlib notebook
print('Solución:', solution)
fig = plt.figure()
# Base Plot
if isinstance(l, type(None)) or isinstance(r, type(None)):
l = int(left) - 0.25
r = ceil(right) + 0.25
plt.axhline(0, color='black', linewidth=1)
1
X = np.linspace(l, r, 20)
Y = [f(x) for x in X]
plt.plot(X, Y)
Y_MIN = min(f(l), f(r))
Y_MAX = max(f(l), f(r))
# Animate
l1 , v1 = plt.plot(left, Y_MAX, right, Y_MIN, linewidth=2, color= 'red')
line_anim = animation.FuncAnimation(fig,
update_line,
len(lines),
fargs=(l1, v1, lines, Y_MIN, Y_MAX),
interval=700,
repeat=False)
return line_anim
[5]: def find_intersections(l, r, eps = 0.00000001):
intersections = []
for i in range(l, r):
f_a = f(i-eps)
f_b = f(i+1-eps)
if not (abs(f_a + f_b) == abs(f_a) + abs(f_b)):
intersections.append((i-eps, i+1-eps))
return intersections
[6]: def bisection(a, b, eps, f, max_iters=100):
lines = []
f_c = 1
i = 0
f_a = f(a)
f_b = f(b)
c = (a+b)/2
f_c = f(c)
2
i += 1
return c, lines
[7]: # a = 1, b = -3, c = 1
# f = lambda x: x**2 - 3*x + 1
# f = lambda x: x**x - 100
f = lambda x: x**2 - 2**x
[8]: plot(-5, 5)
1 Solución Analítica
[9]: a = 1
b = -3
c = 1
2.618033988749895
0.3819660112501051
3
2 Bisección
[10]: intersections = find_intersections(-5, 5)
print(intersections)
[11]: solutions = []
for intersection in intersections:
l, r = intersection
solution, _ = bisection(l, r, 0.0000000001, f, max_iters=1000)
solutions.append(solution)
[12]: for solution in solutions:
print('x:', solution, '-> f(x):', f(solution))
3 Grafica Animada
Debemos graficar por cada intérvalo manualmente
[13]: # line_anim = animated_plot(-1, 0, -5, 5)
# line_anim = animated_plot(1.99999999, 2.99999999, None, None)
line_anim = animated_plot(-1.00000001, -1e-08, None, None)
HTML(line_anim.to_jshtml())
Solución: -0.7666626076562499
4
5