For some reason in the challenge: Implement the Bisection Method, I cant get past steps 8 and 9.
8. square_root_bisection(0.001, 1e-7, 50) should return a number between 0.03162267660168379 and 0.031622876601683794.
9. 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.
Here is my code:
def square_root_bisection(value, tolerance = 0, max_iter = 0):
if value < 0:
raise ValueError('Square root of negative number is not defined in real numbers')
if value == 0:
print(f"The square root of {value} is {value}")
return value
if value == 1:
print(f"The square root of {value} is {value}")
return value
low = 0
high = max(1, value)
counter = 0
while (high - low) >= tolerance or counter <= max_iter:
mid = (low + high) / 2
if abs(value-mid\*\*2) <= tolerance:
print(f"The square root of {value} is approximately {mid}")
return mid
elif mid\*\*2 > value:
high = mid
else:
low = mid
counter += 1
print('Failed to converge within 10 iterations')
return None