简体   繁体   中英

Python Square Root doesn't work

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

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

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM