Implement the Bisection Method - Implement the Bisection Method

Tell us what’s happening:

My code is working, but not fulfilling some of the tests within the given number of iterations. I think having a different starting guess might nudge it over the finish line, but not sure what the initial guess should be.

Your code so far

def square_root_bisection(num, tolerance=0.01, max_iter=100):
    if num < 0:
        raise ValueError('Square root of negative number is not defined in real numbers')
    elif num == 0 or num == 1:
        print(f'The square root of {num} is {num}')
        return num
    else:
        root = num ** 0.5
        high = num
        low = 0
        for i in range(max_iter):
            guess = (high + low) / 2
            print(guess ** 0.5, root)
            if abs(root - guess ** 0.5) <= tolerance:
                print(f'The square root of {num} is approximately {guess ** 0.5}')
                return guess ** 0.5
            else:
                if abs(low - root) < abs(high - root):
                    high = guess
                else:
                    low = guess
        print(f'Failed to converge within {max_iter} iterations')
        return None

print(square_root_bisection(81, 1e-3, 50))

Your browser information:

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

Challenge Information:

Implement the Bisection Method - Implement the Bisection Method

never use the square root calculation in your algorithm, it makes the algorithm pointless