2

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)
Concode
  • 23
  • 6

2 Answers2

2

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!

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ravi Prakash
  • 136
  • 4
  • It's probably worth doing the `prev == hw` comparison earlier to avoid unecessary calculations. It might also be worth replacing the `while` with a limited loop (e.g. `for _ in range(100)` if there is any possibility of it never 'settling'. – match Dec 22 '21 at 18:03
0

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
cvanelteren
  • 1,633
  • 9
  • 16