Tell us what’s happening:
Hello, I have tried completing the challenge but my code won’t pass any of the tests past number 7 and the console prints the wrong answer, but I can’t figure out what I did wrong?
Your code so far
def square_root_bisection(number, tolerance=1e-6, max_it=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.0
if number < 1:
high = 1
else:
high = number
for iterations in range(max_it):
mid = (low + high) / 2
square = mid * mid
if square > number:
high = mid
elif square < number:
low = mid
elif abs(high - low) <= tolerance:
break
if abs(square - number) <= tolerance:
return f'The square root of {number} is approximately {square}'
return square
else:
return f'Failed to converge within {max_it} iterations'
return None
print(square_root_bisection(0.001, 1e-7, 50))
print(square_root_bisection(225, 1e-5, 100))
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15
Challenge Information:
Implement the Bisection Method - Implement the Bisection Method
