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

Viewed 66

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:

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)
2 Answers

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!

Your code contains a while true without a break. You could try:


def find_root(n, eps = 1e-3):
    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
        if (n2-n1) < eps:
            run = False
    return hw
print(find_root(2)) # 1.4150390625
Related