Implement the Bisection Method - Implement the Bisection Method

Tell us what’s happening:

cant pass 22 and 23
22. square_root_bisection(225, 1e-7, 10) should return None.

  1. square_root_bisection(225, 1e-7, 10) should print Failed to converge within 10 iterations.

can get help in what direction i should head in (aware that the print and return c at the end is redundant i just didn’t have another place to put them for now)

Your code so far

def square_root_bisection(no,tol=1e-5,max_iter=5):
    
    if no < 0:
        raise ValueError('Square root of negative number is not defined in real numbers')
    elif no == 0 or no == 1:
        print(f'The square root of {no} is {no}')
        return no
    elif no > 0:
        cur_iter=0
        if no <1:
            a= no
            b=1
        else:
            a =1
            b = no
        while cur_iter<=max_iter:
            c=(a+b)/2
            while abs(b-a) >= tol:
                if c**2 < no:
                    a=c
                else:
                    b=c
                c=(a+b)/2
            cur_iter +=1
                 
        print(f'The square root of {no} is approximately {c}')
        return c
        print(f'Failed to converge within {max_iter} iterations' )
        return None
        
square_root_bisection(0)
square_root_bisection(0.001, 1e-7, 15)
square_root_bisection(225, 1e-7, 20)
square_root_bisection(225, 1e-7, 10)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36

Challenge Information:

Implement the Bisection Method - Implement the Bisection Method

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-bisection-method/686ccc2c8b967e17ab18d593.md at main · freeCodeCamp/freeCodeCamp · GitHub

Hi @samy_questions

Everything after the first return statement will not execute.

Happy coding

Yes im aware, but how would i implement part 2. Bulletpoint 4 of the story. I dont understand what conditions must be fulfilled to have a failed attempt at iteritating. What conditions should i check against before implementing the return None

How are you checking this condition?

while cur_iter<=max_iter:

How do you handle the situation when instead of:

cur_iter is the same as max_iter?

it exits the while loop, shouldn’t i then compare the generated answer to an expected value as a test?

After while loop you could add an ifcondition to check the variables I mentioned above.

An else statement then handles the rest.

Sounds like you should do this:

If no value meets the tolerance condition, print a failure message: Failed to converge within [maximum] iterations and return None.

However, no code is going to run after a return statement.