Implement the Bisection Method - Implement the Bisection Method

Tell us what’s happening:

Hello, I think I solved the challenge but it does not complete test any of the tests after number 7, but I don’t understand what I did wrong, can someone spot where I made a mistake?

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:
        iterations = 0
        low = 0
        if number < 1:
            high = 1
        else:
            high = number
        while iterations < max_it:
            mid = (low + high) / 2
            iterations += 1
            square = mid ** 2
            if abs(square - number) <= tolerance:
                return f'The square root of {number} is approximately {square}'
                return square
            elif square > number:
                high = mid
            else:
                low = mid
        return f'Failed to converge within {max_it} iterations'
        return None
        
print(square_root_bisection(0.001, 1e-7, 50))


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

Hi @lucca.homann ,

Is this code in line with this instruction?

…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

Happy coding!

I see, i tried fixing it now but then it just goes straight to the ‘Failed to converge within X iterations’ with each function-run.

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
        if number < 1:
            high = 1
        else:
            high = number
        while (high - low) <= tolerance:
            for its in range(max_it):
                mid = (low + high) / 2
                square = mid ** 2
                if abs(square - number) <= tolerance:
                    return f'The square root of {number} is approximately {square}'
                elif square > number:
                    high = mid
                else:
                    low = mid
        
        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-7, 10))