Certainly! Here's a short Python program that implements the bisection method for finding the root of a function:
def bisection(f, a, b, tol=1e-6, max_iter=100):
"""
Finds the root of a function f(x) using the bisection method.
Parameters:
- f: The function to find the root of.
- a: The lower bound of the interval.
- b: The upper bound of the interval.
- tol: The tolerance for the root (default: 1e-6).
- max_iter: The maximum number of iterations (default: 100).
Returns:
- The approximate root of the function.
"""
if f(a) * f(b) >= 0:
raise ValueError("The function must have opposite signs at the interval endpoints.")
for i in range(max_iter):
c = (a + b) / 2
if abs(f(c)) < tol:
return c
elif f(c) * f(a) < 0:
b = c
else:
a = c
raise RuntimeError("The bisection method did not converge within the specified iterations.")
# Example usage
def f(x):
return x**3 - x - 2
root = bisection(f, 1, 2)
print(f"The approximate root is: {root}")
Explanation:
-
The bisection function takes the following parameters:
f: The function to find the root of.
a: The lower bound of the interval.
b: The upper bound of the interval.
tol: The tolerance for the root (default: 1e-6).
max_iter: The maximum number of iterations (default: 100).
-
The function first checks if the function values at the interval endpoints have opposite signs. If not, it raises a ValueError since the bisection method requires the function to have opposite signs at the interval endpoints.
-
The function then enters a loop that iterates for a maximum of max_iter iterations. In each iteration:
- It calculates the midpoint
c of the interval [a, b].
- If the absolute value of
f(c) is less than the tolerance tol, it means the root is found, and the function returns c.
- If
f(c) and f(a) have opposite signs, it updates b to c, narrowing the interval to [a, c].
- Otherwise, it updates
a to c, narrowing the interval to [c, b].
-
If the loop completes without finding the root within the specified tolerance, it raises a RuntimeError indicating that the bisection method did not converge.
-
In the example usage, the function f(x) = x^3 - x - 2 is defined, and the bisection function is called with the interval [1, 2] to find its root. The approximate root is then printed.
This program provides a basic implementation of the bisection method for root finding. You can modify the function f(x) to find the root of any desired function.