Bisection Method: Theory and Code Explanation
1 Theory of the Bisection Method
The Bisection Method is a numerical technique used to find a real root of a continuous
function f (x) on an interval [a, b]. The method works only if the function satisfies:
f (a) f (b) < 0,
which means the function changes sign over the interval, hence by the Intermediate
Value Theorem, at least one root exists in (a, b).
Algorithm Steps
1. Choose an initial interval [a, b] such that f (a)f (b) < 0.
2. Compute the midpoint:
a+b
c= .
2
3. Evaluate f (c): (
f (a) f (c) < 0 ⇒ root lies in [a, c],
f (c) f (b) < 0 ⇒ root lies in [c, b].
4. Replace the interval with the appropriate half.
5. Continue until |f (c)| < TOL (the tolerance).
The method converges linearly and guarantees success if the initial bracket is valid.
2 Python Code with Explanation
Original Program
"""
Program to find root of a function using Bisection Method
"""
import numpy as np
1
The triple-quoted string is a module-level description. The NumPy library is imported
for the function [Link], which checks numerical closeness.
def bisection (f , bracket , TOL , max_iter ) :
This defines the bisection method function. Arguments:
- f: function whose root is to be found - bracket: tuple (a, b) giving the starting interval
- TOL: stopping tolerance - max iter: maximum allowed iterations
a , b = bracket
f_a = f ( a )
f_b = f ( b )
The interval endpoints are unpacked into a and b. The function is evaluated at both
points.
root = a
A default value for the root (will be updated).
for iter in range ( max_iter ) :
A loop that will run up to max iter times.
c = ( a + b ) /2
f_c = f ( c )
The midpoint c is computed and the function is evaluated at c.
if np . isclose ( f_c , 0.0 , atol = TOL ) :
root = c
break
If f (c) is close to zero within tolerance, the root is accepted.
if f_a * f_c < 0:
b = c
f_b = f_c
else :
a = c
f_a = f_c
This step determines whether the root lies in [a, c] or [c, b] by checking the sign of the
product f (a)f (c).
return root , iter
Returns the root estimate and the number of iterations used.
Function whose root is sought
def func ( x ) :
return 3*( x **3) + x * x - x - 5
2
The function is:
f (x) = 3x3 + x2 − x − 5
Calling the Bisection Method
root , iter = bisection ( func , (0 ,2) , 1.0 E -6 , 100)
The root is searched in the interval [0, 2] using a tolerance 10−6 .
print ( ’ root , r = ’ , root )
print ( ’f ( r ) = ’ , func ( root ) )
print ( ’ Iterations = ’ , iter )
The root, function value at the root, and number of iterations are printed.