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!