gpt-3.5-turbo-0314· OpenAI
Arena Human Preference 55K
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
Sure, here's an example implementation of the bisection method in Python:
def bisection(f, a, b, tol=1e-6): """ Perform the bisection method to find a root of function f on the interval [a, b]. Returns the root x and the number of iterations required. """ fa, fb = f(a), f(b) if fa*fb > 0: raise ValueError("f(a) and f(b) must have opposite signs") x = (a + b)/2 fx = f(x) n_iter = 0 while abs(fx) > tol: n_iter += 1 if fx*fa < 0: b = x fb = fx else: a = x fa = fx x = (a + b)/2 fx = f(x) return x, n_iterThis function takes as input a function
f(which takes a single argument), the endpointsaandbof the interval to search for a root, and an optional tolerancetol(defaulting to1e-6). It returns the rootxfound and the number of iterations required. Iff(a)andf(b)have the same sign, aValueErroris raised.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.