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

Python中while循环未按预期运行:平方根计算报错排查

问题分析与解决

错误原因

你遇到的UnboundLocalError是因为:当输入的数不是任何0.1倍数的平方时(比如6.5),循环里的if tempAns * tempAns == num1条件永远不会触发,answer变量根本没被赋值,最后print时自然找不到这个变量。

另外还有个隐藏问题:浮点数的存储精度限制,比如0.1在计算机里实际是近似值,它的平方并不是严格的0.01,直接用==比较两个浮点数相等本身就非常不可靠。


修复与优化方案

方案1:改进步长逼近法(解决错误+优化精度判断)

先初始化answer,同时用误差范围替代严格相等判断,避免浮点数精度坑:

num1 = 6.5
answer = None
tempAns = 0.1
precision = 0.0001  # 允许的误差范围,可按需调整

while tempAns <= num1:
    square = tempAns * tempAns
    # 用误差范围判断是否接近目标值
    if abs(square - num1) < precision:
        answer = tempAns
        break
    # 提前终止:当前平方已经超过目标值,没必要继续循环
    if square > num1:
        break
    tempAns += 0.1

if answer is not None:
    print(f'The answer is: {answer}')
else:
    # 输出近似值(最后一个平方小于目标值的tempAns)
    print(f'Approximate square root: {tempAns - 0.1}')

方案2:牛顿迭代法(更高效+更高精度)

步长逼近法效率很低,尤其对于大数或需要高精度的场景,推荐用牛顿迭代法,收敛速度快得多:

def square_root(num):
    if num < 0:
        return None  # 负数无实数平方根
    guess = num / 2  # 初始猜测值
    precision = 1e-6  # 精度阈值
    while abs(guess * guess - num) > precision:
        # 牛顿迭代核心公式
        guess = (guess + num / guess) / 2
    return guess

num1 = 6.5
result = square_root(num1)
if result is not None:
    print(f'The answer is: {result}')
else:
    print('Cannot calculate square root of negative number.')

关键注意点

  • 变量使用前必须初始化,避免未定义错误;
  • 浮点数比较永远不要用==,要用误差范围判断;
  • 牛顿迭代法是计算平方根的工业级常用方法,比步长逼近效率高几个量级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:20:36