0

I have got a script that should calculate the square root of 2, only it currently has 2 problems that I can't seem to solve. Firstly, the while loop does not stop, even when it should stop:

(This is the first few lines of the output when I run this script, the rest is just repeating the last 4 lines.)

sqrt:  1.5
sq:  2.25
sqrt:  1.41666666667
sq:  2.00694444444
sqrt:  1.41421568627
sq:  2.0000060073
sqrt:  1.41421356237
sq:  2.0
sqrt:  1.41421356237
sq:  2.0

Also, as the square root of 2 is an infinite number, I do not understand why it stops at 1.41421356237 and does not make a bigger number.

This is my code:

import time

def sq(inp):
    a = float(inp)
    return a * a

a = 2.0
b = 1
while sq(b) != 2.0:
    b = (b + a / b) / 2
    print 'sqrt: ', b
    print 'sq: ', sq(b)
    time.sleep(0.1)
print 'Done!'

(I have put in a few extra bits to clarify, like the print 'Done' and the delay, but it does not change anything for me.)

Any help would be much appreciated. Thanks!

Kieran
  • 1
  • 2
  • You can't tell because printed floats don't display all their digits, but you're actually converging to `1.41421356237309492343001693370752036571502685546875`, which squares to `1.999999999999999555910790149937383830547332763671875`, which is not equal to 2.0, despite being displayed as "2.0" when you print it. – Kevin Mar 09 '18 at 19:38
  • 2
    John Coleman pointed you to the post that explains how floating system works. For your question, to solve this, instead of having condition to check if they are exactly equal, you should allow some small error. That means, something like `while abs(sq(b) - 2.0) > 0.00000000001:` would work. – TYZ Mar 09 '18 at 19:38

0 Answers0