Implement the Bisection Method - Implement the Bisection Method

Tell us what’s happening:

Failed:8. square_root_bisection(0.001, 1e-7, 50) should return a number between 0.03162267660168379 and 0.031622876601683794.
Failed:9. square_root_bisection(0.001, 1e-7, 50) should print The square root of 0.001 is approximately X, where X is a number between 0.03162267660168379 and 0.031622876601683794

tried so many times still getting these issues

Your code so far

def square_root_bisection(number, tolerance=1e-7, maximum=100):
    if number < 0:
        raise ValueError("Square root of negative number is not defined in real numbers")

    if number == 0 or number == 1:
        print(f"The square root of {number} is {number}")
        return number

    low = 0
    high = max(1, number)
    iterations = 0

    while iterations < maximum:
        mid = (low + high) / 2
        mid_squared = mid * mid

        # Check if we are within tolerance
        if abs(mid_squared - number) <= tolerance:
            print(f"The square root of {number} is approximately {mid}")
            return mid

        if mid_squared < number:
            low = mid
        else:
            high = mid

        iterations += 1

    # If we did not converge
    print(f"Failed to converge within {maximum} iterations")
    return None

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36

Challenge Information:

Implement the Bisection Method - Implement the Bisection Method

You haven’t implemented the tolerance correctly.

For example, if the tolerance is 0.01, the bisection method will keep halving the interval until the difference between the upper and lower bounds is less than or equal to 0.01.

Think of how this relates to your while loop.