Hello there. This page is on using Python to find approximate roots with the bisection method.
For more details on the bisection method click here.
What Is The Bisection Method? (Brief)
The Bisection Method belongs to a class of numerical methods found in applied/computational mathematics. There are cases when the exact answer to a question cannot be found. Approximate solutions (with a small acceptable margin of error) are used instead.
The Bisection Method In Python
In the Python code, I define one function as an example. This function is .
# Bisection Method In Python
# Goal: Finding Roots to Polynomials
# Inputs: Function, a and b for interval [a, b], a guess in [a, b]
# Output: Roots/Zeroes To Polynomials
# Reference: Tim Sauer - Numerical Analysis Second Edition
return(x**2 - 7)
def bisection_method(a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
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
a = midpoint
In the bisection method function, I have the inputs as a, b from the interval [a, b], and the tolerance (margin of error allowed) represented by tol.
Instead of c, I use the variable midpoint.
Here is a function call of the bisection method with with the interval and a tolerance of 0.0001. The round function is used to limit the number of decimals.
>>> print("Answer", round(bisection_method(-1, 3, 0.0001), 3))
- Tim Sauer – Numerical Analysis Second Edition