You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Heron法求平方根:for循环改写为while循环

Heron法求平方根for循环转while循环实现指导

现有while版本核心错误点

  • 函数参数缺失max_iter,与for版本功能不对齐,也未初始化该变量
  • 循环变量i初始化错误:不能直接赋值为range对象,需要初始化为数值1,对应for循环的起始迭代值
  • 循环判断条件写反:应该是相对变化大于容差tol时继续迭代,原代码写的是小于才进入循环
  • 相对变化change只在循环外计算了一次,每次迭代生成新的估计值后没有更新change
  • 打印逻辑位置错误:需要每次迭代时输出当前迭代信息,而不是循环结束后才打印
  • 多余的break判断:逻辑重复,没有实际作用

for循环转while循环通用逻辑

你现在用的for i in range(1, max_iter+1, 1)转换为while循环只需要三步:

  1. 循环开始前初始化i = 1,和range的起始值一致
  2. while的判断条件加上i <= max_iter,和range的结束值对应
  3. 每次循环体执行完末尾手动执行i += 1,对应range的步长

修正后的完整while版本代码

def square_root_while(a, x0, max_iter = 10, tol=1e-14):
   """ (number, number, number) -> float

   Return an estimate of the square root of a number using the Heron's method.
       
   >>> square_root_while(5, 5)
   Iteration | Estimate         | Relative Change
   -------------------------------------------------
   1         | 3.00000000000000 | 0.4000000000000000
   2         | 2.33333333333333 | 0.2222222222222222
   3         | 2.23809523809524 | 0.0408163265306123
   4         | 2.23606889564336 | 0.0009053870529653
   5         | 2.23606797749998 | 0.0000004106060359
   6         | 2.23606797749979 | 0.0000000000000842
   7         | 2.23606797749979 | 0.0000000000000000
   2.23606797749979
   """
   
   x = [x0]
   x.append(a/x0)
 
   print('Iteration | Estimate         | Relative Change')
   print('-------------------------------------------------')
   
   # 初始化循环变量,对应for循环的起始值
   i = 1
   while i <= max_iter:
       change = (abs(x[i] - x[i-1]) / x[i-1])
       if change > tol:
           x.append(1/2 * (x[i] + (a / x[i])))
       else:
           break
       print('{}         | {:.14f} | {:.16f}'.format(i, x[i], change))
       # 手动更新循环变量,对应for循环的步长
       i += 1
   print(x[i])

运行上述代码调用square_root_while(5, 5)得到的结果和你编写的for版本完全一致。

内容的提问来源于stack exchange,提问作者ashnotallyson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:57:04