Tell us what’s happening:
The code is failing Tests 8 and 9
-
square_root_bisection(0.001, 1e-7, 50) should return a number between 0.03162267660168379 and 0.031622876601683794.
-
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.
Your code so far
def square_root_bisection(square_target, tolerance=1e-7, max_iterations=100):
if square_target < 0:
raise ValueError("Square root of negative number is not defined in real numbers")
if square_target == 0 or square_target == 1:
print(f"The square root of {square_target} is {square_target}")
return square_target
low = 0
high = max(1, square_target)
root = None
for i in range(max_iterations):
mid = (low + high) / 2
square_mid = mid**2
if abs(square_mid - square_target) < tolerance:
root = mid
break
if square_mid < square_target:
low = mid
else:
high = mid
if root is None:
print(f"Failed to converge within {max_iterations} iterations")
return None
print(f"The square root of {square_target} is approximately {root}")
return root
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