繁体   English   中英

为什么while循环在python中不重复

[英]Why does while loop not repeat in python

我正在编写代码来打印平方根表。 但它不会循环。 我需要它循环。

import math
                
def test_sqrt():
    a = 1
    def my_sqrt(a):
        while True:
            x = 1
            y = (x + a/x) / 2.0
            if y == x:
                return y

    while(a < 26):
        print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
        a = a + 1
        

test_sqrt()

你快到了:

import math
            
def test_sqrt():
    a = 1
    err = 1e-6

    def my_sqrt(a):
        x=1
        while True:
            y = (x + a/x) / 2.0

            if abs(y-x)<err:
                return y
        
            x = y

    while(a < 26):
         print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
        a = a + 1
    

 test_sqrt()

笔记:

  1. x的初始值是在开始时定义的,不是每次循环
  2. x 的值需要在每个循环中更新,如果我们还没有从 function 返回
  3. 继续计算,直到足够接近,绝对差值小于err

a = 2并调用my_sqrt(2)时,您将陷入无限循环:

my_sqrt(2):
    x = 1
    y = (x + a/x) / 2.0 = 1.5

由于所有变量xay在该上下文中都是常量,因此永远不会使用if y == x:条件。 所以你一直停留在while True:循环中。

原因是python在a=2时进入死循环。 这可以通过调试器检查。

因为您在my_sqrt(a) function 中构建了一个无限循环:

def my_sqrt(a):
    while True:
        x = 1
        y = (x + a/x) / 2.0
        if y == x:
            return y

第二次运行时你有 y,= x (不相等),因此在无限循环中 y 或 x 没有变化,循环永远不会通过return y中断。

通过这个,循环:

while(a < 26):
    print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
    a = a + 1

运行一次然后卡在my_sqrt(a) function 的第二次迭代中,当 a = 2 时。

暂无
暂无

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

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