Reputation: 33
I am trying to write a program to determine the zeros of the given function (f(x) := ln((sin(x**(1/2))**3) + 2) - 1, using the bisection method. The values a and b, which are the initial values used in the bisection method, are inserted on the program already. All it neeeds to do is show the plot and determine the zeros, but I can't get it to run (it stops on line 22). Can anyone spot the error?
import matplotlib.pyplot as plt
import numpy as np
import math
t = np.arange(0.5, 6.0, 0.01)
s = np.log((np.sin(np.sqrt(t)))**3+2)-1
z = len(t)*(0.0,)
plt.plot(t, s, t, z)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('A procura do zero')
plt.grid(True)
plt.savefig("test.pdf")
plt.show()
def bisseçao(a,b):
z=(a+b)/2
while b-a>10**(-5):
if (math.log((math.sin(math.sqrt(a)))**3+2)-1)*(math.log((math.sin(math.sqrt(z)))**3+2)-1)<0:
b=(a+z)/2
if (math.log((math.sin(math.sqrt(b)))**3+2)-1)*(math.log((math.sin(math.sqrt(z)))**3+2)-1)<0:
a=(z+b)/2
return a
a1=1
b1=2
a2=4
b2=5
print("Os zeros são:",bisseçao(a1,b1),bisseçao(a2,b2))
Upvotes: 3
Views: 2350
Reputation: 23637
Here is the first problem:
z=(a+b)/2
while b-a>10**(-5):
You need to cumpute a new z
in every iteration not only at the beginning of the function.
Second problem part 1:
b=(a+z)/2
Second problem part 2:
a=(z+b)/2
Setting the upper/lower bound between lower/upper bound and center point is not correct. They should be set exactly at the center point.
Correct implementation (with a small simplification for clarity - no need to type the whole function five times over):
func = lambda x: np.log((np.sin(np.sqrt(x)))**3+2)-1
def bisseçao(a, b):
while b-a>10**(-5):
z = (a + b)/2
if func(a)*func(z)<0:
b = z
if func(b)*func(z)<0:
a = z
return a
P.S. The code will run into a problem if z
happens to fall exactly at the root. You may want to check for this condition explicitly.
P.P.S. The code will also fail if the starting interval does not contain a root. You may want to check for this condition too.
Upvotes: 3