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.

**Sections**

What Is The Bisection Method? (Brief)

The Bisection Method In Python

**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 .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# 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 # http://code.activestate.com/recipes/578417-bisection-method-in-python/ # https://stackoverflow.com/questions/6289646/python-function-as-a-function-argument def f(x): return(x**2 - 7) 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) |

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.

The output from the bisection method would be the approximate solution to the function. This approximate solution would be off from the exact solution by less than the tolerance.

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.

1 2 3 4 |
answer = bisection_method(-1, 5, 0.0001) >>> print("Answer:", round(answer, 3)) Answer: 2.646 |

**References**

- Tim Sauer – Numerical Analysis Second Edition
- https://stackoverflow.com/questions/6289646/python-function-as-a-function-argument
- http://code.activestate.com/recipes/578417-bisection-method-in-python/