Home > Blockchain >  How does the following code enter an infinite loop if abs(guess**2 -x) >= epsilon (line 7)?
How does the following code enter an infinite loop if abs(guess**2 -x) >= epsilon (line 7)?

Time:09-12

I don't understand why does this code enter an infinite loop. I've tried debugging to see the problem but that didn't help much. The program keeps looping between the while and first if statement.

x = 25
epsilon = 0.01
step = 0.1
guess = 0.0

while guess <= x:
    if abs(guess**2 -x) >= epsilon:
        guess  = step

if abs(guess**2 - x) >= epsilon:
    print('failed')
else:
    print('succeeded: '   str(guess))  

CodePudding user response:

You need to add break

x = 25
epsilon = 0.01
step = 0.1
guess = 0.0

while guess <= x:
    if abs(guess**2 -x) >= epsilon:
        guess  = step
    else:
        break

if abs(guess**2 - x) >= epsilon:
    print('failed')
else:
    print('succeeded: '   str(guess))  

CodePudding user response:

Once your guess reaches a value of 5, the conditional stops being met and your guess isn't incremented anymore. After that, your program loops infinitely.

  • Related