Reputation: 27
How come when I run this function it prints 3 and 4 alternating an infinite number of times. I can't understand why it keeps going, and also shouldn't it at least print 5 initially?
a = 15
x = 5
while True:
print x
y = (x + a/x) / 2
if y == x:
break
x = y
Upvotes: 0
Views: 178
Reputation: 579
I hope this small code trace will help you see the error:
First Loop
y= (5 + (15/5) ) /2
y= (5 + 3) /2
y=4
4 !=5
x=4
second loop
y= (4+(15/4))/2
y= (4+3)/2
y=3
3!=4
x=3
third loop
y=(3+(15/3)) /2
y=(3+5) /2
y=8/2
y=4
4!=3
x=4
will repeat...
Upvotes: 1
Reputation: 86174
I can tell you are using python 2, so /
in this case integer division. In order to force floating point division, there are a few ways you could do it, but this is probably the easiest.
y = (x + 1.0 * a / x) / 2
Upvotes: 1
Reputation: 118021
You are doing integer division. Change your constants to
a = 15.0
x = 5.0
Also, since the numbers will be float
check for some allowable precision, instead of trying to use exact equality.
while True:
print x
y = (x + a/x)/2
if abs(y - x) < 0.0001:
break
x = y
Output
5
4.0
3.875
3.87298387097
Upvotes: 1