Tell us what’s happening:
Hello,
My algorithm can’t pass following tests and I think that’s because of a logical error in my last if that I can’t find it. (that if condition is always true somehow.)
here’s the errors:
22. square_root_bisection(225, 1e-7, 10) should return None.
23. square_root_bisection(225, 1e-7, 10) should print Failed to converge within 10 iterations.
Your code so far
def square_root_bisection(number, tolerance = 0.01, maximum = 100):
if number < 0:
raise ValueError("Square root of negative number is not defined in real numbers")
elif number == 0 or number == 1:
print(f"The square root of {number} is {number}")
return number
else:
low = 0
if number < 1:
high = 1
else:
high = number
mid = (low + high) / 2
iterations = 100
result = 0
for i in range(iterations):
mid = (low + high) / 2
if (high - low) <= tolerance:
break
elif mid**2 > number:
high = mid
else:
low = mid
result = mid
if (high - low) <= tolerance:
print(f"The square root of {number} is approximately {result}")
return result
else:
print(f"Failed to converge within the {maximum} iterations")
return None
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0
Challenge Information:
Implement the Bisection Method - Implement the Bisection Method