#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 2 08:39:37 2025 @author: hundledr-local """ def bisection(f,a,b,tol): """ Bisection Method Computes an approximation to f(x)=0 given that the root is bracketed in [a,b] with f(a)f(b)<0. Will run until TOL is reached, and will output the solution xc In this version, we assume the function f is passing both the value of the function AND its derivative (so it lines up with Newton's Method') """ u=f(a) fa=u[0] u=f(b) fb=u[0] if fa*fb >= 0: print("Root may not be bracketed.") return None iter=0 while (b-a)/2>tol: iter+=1 c = (a + b)/2 u = f(c) fc=u[0] if fc==0: print("Found exact solution.") return c elif fa*fc < 0: b=c fb=fc else: a=c fa=fc print('Finished after %3d iterations.\n' % iter ) return (a + b)/2 # Example: Finding the root of f(x) = x^3 - 4x - 9 in [2, 3] def func(x): return x**3 + x - 1 root = bisection_method(func, 0, 1, 5e-5) print(f"Root found: {root:.6f}")