I'm coding the bisection method in Python. I have set a tolerance for the error in my routine. I have two questions:
- My function should be able to find the root of an arbitrary continuous scalar-valued function. How do I pass this to
bisection_methodand use it properly? - How can I record how many iterations it takes to reach the specified tolerance?
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
x**2 - 1,bisection_method(-2, 2, 1)would say "No root found", but there are roots -1 and 1.