Hi, obviously, my code does not work, and I do not understand why. Normally, when I type square_root_bisection(225, 1e-7, 10), it should give me None because it should not be able to find 15 in 10 iterations, but it gives me 15. Can you please put me in the right direction?
Your code so far
def square_root_bisection(number, tolerance=0.1, max_iterations=100):
if number < 0:
raise ValueError("Square root of negative number is not defined in real numbers")
if number == 0 or number == 1:
print(f'The square root of {number} is {number}')
return number
if number < 1:
Min = 0
Max = 1
for i in range(max_iterations):
Mid = (Min+Max)/2
square = Mid **2
if square > number:
Max = Mid
elif square < number:
Min = Mid
if square == number or abs(Max-Min) <= tolerance:
print(f'The square root of {number} is approximately {Mid}')
return Mid
else:
print(f"Failed to converge within {max_iterations} iterations")
return None
Min = 1
Max = number
for i in range(max_iterations):
Mid = (Min + Max)/2
square = Mid **2
if square > number:
Max = Mid
elif square < number:
Min = Mid
if square == number or abs(Max - Min) < tolerance:
print(f'The square root of {number} is approximately {Mid}')
return Mid
else:
print(f"Failed to converge within {max_iterations} iterations")
return None
print(square_root_bisection(0))
square_root_bisection(225, 1e-7, 10)
print(square_root_bisection(225, 1e-7, 10))
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/18.3.1 Safari/605.1.15
Challenge Information:
Implement the Bisection Method - Implement the Bisection Method
have you tried any debugging (you didn’t say if you had).
Debugging like: adding print statements to your code to investigate the values of various variables at different points and trace how they change as the program runs.
For example, if the tolerance is 0.01 , the bisection method will keep halving the interval until the difference between the upper and lower bounds is less than or equal to 0.01 .
Is your code doing what this instruction says it should?
Actually, what I do not understand is why square_root_bisection(0.001, 1e-7, 50) stops after 16 iterations while it should iterate 50 times. Can you please explain what I did wrong?
I still do not get it. It should iterate 50 times (or less) until it coverages to a value within the specified tolerance. Here it stops iterating while it is not yet within the specified tolerance. I am stuck.
Yes, as you can see, I tested different cases, and in one case (square root bisection 0.001), iterations stop after 16 iterations while it is not yet within the specified tolerance. I do not understand why. Normally, it should continue iterating until it gets within the tolerance or issue a message that it failed to converge within the max number of iterations.