Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I made a python script to easily find a square root but I can't stop it

I made a python script to find the square root of a number and prints out the result so far, but it uses an infinite loop and I cannot stop it. Does anybody know how to stop it when it has printed out the correct answer several times?

I am looking for a stop condition. I can stop it but down know when to stop it

Here is the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def find_root(n):
    if n < 1:
        print("error")
        return
    n1 = 1
    n2 = n
    run = True
    while run:
        hw = n1 + ((n2 - n1) / 2)
        if (hw ** 2) < n:
            n1 = hw
        else:
            n2 = hw
        print(hw)
           
inp = float(input())
find_root(inp)

>Solution :

Just a slight modification.

def find_root(n):
    if n < 1:
        print("error")
        return
    n1 = 1
    n2 = n
    run = True
    prev = -1
    while run:
        hw = n1 + ((n2 - n1) / 2)
        if (hw ** 2) < n:
            n1 = hw
        else:
            n2 = hw
        if prev == hw:
            break
        prev = hw
        print(hw)
           
inp = float(input())
find_root(inp)

That prev checks if the number that you calculated just now was seen previously. If yes, this means that you have already found the correct root!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading