简体   繁体   English

Python平方根不起作用

[英]Python Square Root doesn't work

How come when I run this function it prints 3 and 4 alternating an infinite number of times. 当我运行此功能时,为什么它会无限次打印3和4。 I can't understand why it keeps going, and also shouldn't it at least print 5 initially? 我不明白为什么它会继续下去,而且它不应该至少最初打印5张吗?

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. 另外,由于数字将是float请检查一些允许的精度,而不要尝试使用完全相等的形式。

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. 我可以告诉您正在使用python 2,因此/在这种情况下为整数除法。 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... 将重复...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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