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

Python自定义平方根函数返回None引发运算错误求助

问题分析与修复方案

问题根源

  1. 返回值错误:my_sqrt函数中写了return print(y),但print()函数的返回值是None,导致整个函数最终返回None,进而引发test_sqrt里diff计算时None - 数值的报错。
  2. 浮点数判断问题:用y == x判断浮点数相等存在精度误差,部分场景下会导致循环无法终止。

修复步骤

  1. 修正返回逻辑:将my_sqrt中的return print(y)改为直接返回计算结果y,输出逻辑可在test_sqrt中统一处理。
  2. 优化循环终止条件:用你定义的epsilon判断y和x的差值是否足够小,替换y == x。
  3. 避免重复计算:在test_sqrt中仅调用一次my_sqrt(num),将结果存入变量复用,减少冗余运算。

修改后的代码

import math
epsilon = 0.0000001

def my_sqrt(a):
    x = a / 2
    while True:
        y = (x + a / x) / 2
        # 用epsilon判断浮点数是否足够接近
        if abs(y - x) < epsilon:
            return y
        x = y

def test_sqrt(a):
    num = 1
    while a >= num:
        # 只调用一次my_sqrt,复用结果
        my_result = my_sqrt(num)
        math_result = math.sqrt(num)
        a_value = f"a = {num} |"
        mysqrt = f"my_sqrt(a) = {my_result} |"
        mathsqrt = f"math.sqrt(a) = {math_result} |"
        diff = f"diff = {my_result - math_result}"
        print(a_value, mysqrt, mathsqrt, diff)
        num += 1

test_sqrt(3)

说明

  • 修改后的my_sqrt会正确返回平方根数值,不再返回None。
  • abs(y - x) < epsilon的终止条件解决了浮点数精度导致的循环无法结束问题。
  • 单次调用my_sqrt(num)既提升了运行效率,也避免了重复输出的混乱。

内容的提问来源于stack exchange,提问作者Wahid Ahmad Rustaqi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:35:05