Reputation: 206
I'm coding the bisection method in Python. I have set a tolerance for the error in my routine. I have two questions:
bisection_method
and use it properly?Code:
def f(x):
return(x**2 - 11)
def bisection_method(a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(midpoint) == 0:
return(midpoint) #The midpoint is the x-intercept/root.
elif f(a)*f(midpoint) < 0: # Increasing but below 0 case
b = midpoint
else:
a = midpoint
return(midpoint)
answer = bisection_method(-1, 5, 0.0001)
print("Answer:", answer)
which gives the following output:
Answer: 3.31671142578125
Upvotes: 1
Views: 5570
Reputation: 77837
For the function, simply pass the function name as an argument. I've changed your function's name to root11
and made it the first argument to the bisection.
For the count ... you should have been able to look this up on line. Just count iterations as you would before you learned the for
statement. Return this with the final answer.
Note that I removed your check for an exact answer: you'll find it on the next iteration, anyway.
def root11(x):
return(x**2 - 11)
def bisection_method(f, a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
iter = 0
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(a)*f(midpoint) < 0: # Increasing but below 0 case
b = midpoint
else:
a = midpoint
iter += 1
return(midpoint, iter)
answer, iterations = bisection_method(root11, -1, 5, 0.0001)
print("Answer:", answer, "\nfound in", iterations, "iterations")
import math
answer, iterations = bisection_method(math.cos, 0, 2, 0.0001)
print("Answer:", answer, "\nfound in", iterations, "iterations")
Output:
Answer: 3.31671142578125
found in 15 iterations
Answer: 1.5706787109375
found in 14 iterations
Upvotes: 1