#97 Finding roots on an interval with the bisection method.

One of the simplest algorithms for solving equations of the form f(x)=0 is called the bisection method.

from math import exp
def bisection(f,a,b,tol= 1e-3):
    if f(a)*f(b) > 0:
        print(f'No roots or more than one root in [{a},{b}]')
        return
    m = (a+b)/2

    while abs(f(m)) > tol:
        if f(a)*f(m) < 0:
            b = m
        else:
            a = m
        m = (a+b)/2
    return m

#call the method for f(x)= x**2-4*x+exp(-x)
f = lambda x: x**2-4*x+exp(-x)
sol = bisection(f,-0.5,1,1e-6)
print(f'x = {sol:g} is an approximate root, f({sol:g}) = {f(sol):g}')

Output:

x = 0.213348 is an approximate root, f(0.213348) = -3.41372e-07

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading