Implement the Bisection Method

For some reason in the challenge: Implement the Bisection Method, I cant get past steps 8 and 9.

8. square_root_bisection(0.001, 1e-7, 50) should return a number between 0.03162267660168379 and 0.031622876601683794.

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.

Here is my code:

def square_root_bisection(value, tolerance = 0, max_iter = 0):

if value < 0:

    raise ValueError('Square root of negative number is not defined in real numbers')



if value == 0:

    print(f"The square root of {value} is {value}")

    return value



if value == 1:

    print(f"The square root of {value} is {value}")

    return value



low = 0

high = max(1, value)

counter = 0



while (high - low) >= tolerance or counter <= max_iter:

    mid = (low + high) / 2

    

    if abs(value-mid\*\*2) <= tolerance:

        print(f"The square root of {value} is approximately {mid}")

        return mid

    

    elif mid\*\*2 > value:

        high = mid

    

    else:

        low = mid



    counter += 1



print('Failed to converge within 10 iterations')

return None

Hi there,

This line is suspect. In your while loop, you check high - low against the tolerance, but here you are not checking “the difference between the upper and lower bounds” against the tolerance.

Happy coding!

Thank you, this was very helpful

Thanks! I changed my code and it worked. But I was wondering why checking the high - low against the tolerance rather the value - mid squared is the correct solution because I thought my way worked too.