Why does my code keep failing tests 8 and 9? I have exhausted all ideas.
Your code so far
def square_root_bisection(number, tolerance = 0.01, max_iteration = 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
low = 0
high = max(number, 1)
iteration = 0
while iteration < max_iteration:
mid = (low + high) / 2
squared_mid = mid * mid
if abs(squared_mid - number) <= tolerance:
print(f'The square root of {number} is approximately {mid}')
return mid
if squared_mid > number:
high = mid
else:
low = mid
iteration += 1
print(f'Failed to converge within {max_iteration} iterations')
return None
square_root_bisection(0.001, 0.01, 50)
square_root_bisection(0.25, 0.1, 50)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0
Challenge Information:
Implement the Bisection Method - Implement the Bisection Method
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.
So you saw that the results aren’t inside of the given tolerance I’m guessing?
The tolerance is on how close your answer is to true, not how close the square of the answer is to the number. That’s what’s causing your problem. Given the bisection interval, what is the largest possible error of the midpoint value?
I also misunderstood this one at first. The mistake is assuming what “tolerance” is.
Look at this line:
Look at this instruction:
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.
In other words, keep halving WHILE the difference between the upper and lower bounds (high and low) is greater than the tolerance.
Does it make more sense?
This instruction I think is misleading maybe it should be removed
The tolerance being the acceptable error margin for the result.
An “error margin” seems to imply the result will be correct within plus or minus the tolerance.
I finally get to understand the problem and the cause of it. I was comparing the tolerance to inappropriate values. I fixed it and it passed. Thank you all.