Hi, I am in the midst of doing the new Beta Full Stack Developer Python course, I am encountering a problem understanding what is wrong with my code in this challenge.
def square_root_bisection(number,tolerance=1e-6,max_iterations=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:
iterations = 0
if number < 1:
upper_bound = 1
else:
upper_bound = number
lower_bound = 0
while iterations < max_iterations:
iterations += 1
mid = (upper_bound + lower_bound)/2
mid_square = mid ** 2
if abs(mid_square - number) <= tolerance:
print(f'The square root of {number} is approximately {mid}')
return mid
elif mid_square > number:
upper_bound = mid
else:
lower_bound = mid
print(f'Failed to converge within {max_iterations} iterations')
return None
if __name__ == '__main__':
import math
test = 0.001
tolerance = 1e-7
max_iterations = 50
root = square_root_bisection(test,tolerance,max_iterations)
print(math.sqrt(test))
print(root)
print(root**2)
My code is failing these test cases
-
8.
square_root_bisection(0.001, 1e-7, 50)should return a number between0.03162267660168379and0.031622876601683794. -
9.
square_root_bisection(0.001, 1e-7, 50)should printThe square root of 0.001 is approximately X, whereXis a number between0.03162267660168379and0.031622876601683794.
I understand there could be a issue when you compare abs(mid_square - number) <= tolerance, because the intended tolerance would be changed when you square the mid number to compare with the original number, but how would the math change and how to account for it in my code?
Any feedback on how to improve is appreciated, thanks!
Edit: My code passes when I change abs(mid_square - number) <= tolerance to abs(mid - number**0.5) <= tolerance, but that just defeats the purpose of using this algorithm, so how would I calculate this properly? Thanks for any help!
