Write a short Python program to perform the bisection method for root finding.
- User
Write a short Python program to perform the bisection method for root finding.
- Assistant
Certainly! Here's a short Python program that implements the bisection method for root finding:
def bisection(f, a, b, tol=1e-6, max_iter=100): """ Finds the root of a function f using the bisection method. Parameters: f (function): The function to find the root of. a (float): The lower bound of the interval. b (float): The upper bound of the interval. tol (float): The tolerance for the root (default: 1e-6). max_iter (int): The maximum number of iterations (default: 100). Returns: float: 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 - 1 root = bisection(f, 1, 2) print(f"The approximate root is: {root}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.