Menu Close

Bisection Method | Python

The bisection method is a root-finding algorithm that applies to equations in the form of f(x) = 0.

It works by repeatedly bisecting the interval between the current lower and upper bounds, and selecting the subinterval where the function changes sign as the new search interval.

The algorithm terminates when the size of the interval is smaller than a specified tolerance.

Bisection method in Python:

  • Function

f(x) = $x^{2} – x – 1$

				
					def bisect(f, a, b, tol=1e-9):

    """
    f: a function that takes a single argument
    a: lower bound of the interval
    b: upper bound of the interval
    tol: tolerance for the stopping criterion
    """
    
    # Bisection Method [By Bottom Science]
    
    while (b-a) > tol:
        c = (a+b) / 2
        if f(c) == 0:
            return c
        elif f(a)*f(c) < 0:
            b = c
        else:
            a = c
    return (a+b)/2

# Test
def f(x):
    return x**2 - x - 1

root = bisect(f, 0, 2, 1e-6)
print(root)
# Output: 1.61803399

				
			

More Related Stuff