Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0314· OpenAIHugging Face Arena Human Preference 55K

Write a short Python program to perform the bisection method for root finding.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with GLMchatglm-6b’s answer.
  1. User

    Write a short Python program to perform the bisection method for root finding.

  2. 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_iter
    

    This function takes as input a function f (which takes a single argument), the endpoints a and b of the interval to search for a root, and an optional tolerance tol (defaulting to 1e-6). It returns the root x found and the number of iterations required. If f(a) and f(b) have the same sign, a ValueError is raised.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.