Implement the Bisection Method - Implement the Bisection Method

Tell us what’s happening:

I implemented the square_root_bisection function using the stop condition based on interval size (high - low). When run square_root_bisection(225, 1e-7, 10), the function sometimes returns an approximate root before reaching 10 iterations instead of printing “Failed to converge within 10 iterations.” This causes test case 23 to fail. I suspect the stop condition or iteration limit causes premature convergence. Please help me verify if my stopping criteria are correct and how to ensur

Your code so far

def square_root_bisection(number, tolerance=1e-7, max_iterations=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)
    iteration = 0
    
    while (high - low) > tolerance and iteration < max_iterations:
        mid = (low + high) / 2
        mid_squared = mid * mid
        
        if mid_squared < number:
            low = mid
        else:
            high = mid
        
        iteration += 1
    
    if (high - low) <= tolerance:
        approx_root = (low + high) / 2
        print(f"The square root of {number} is approximately {approx_root}")
        return approx_root
    else:
        print(f"Failed to converge within {max_iterations} iterations.")
        return None

print(square_root_bisection(225, 1e-7, 10))

Your browser information:

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

Challenge Information:

Implement the Bisection Method - Implement the Bisection Method

Welcome to the forum @Akats-99 ,

Are you printing the exact message requested for “Failed to converge…”? Look closely. You have included an extra character.

Happy coding!

1 Like

Thanks, I’ve fixed it and it works now!