Python立方根近似函数调试求助:调用时陷入死循环
问题分析与修复
你的代码陷入死循环的核心原因是初始搜索区间设置错误:当cube > 1时,你把low设为cube/2,导致这个区间不包含真实的立方根,二分法永远无法找到满足精度要求的结果,进而无限循环。
比如调用approximate_cube_root(8, 0.01)时,cube=8,你设置low=4、high=8,但8的立方根是2,不在[4,8]区间内,区间内所有数的立方都≥64,永远无法满足abs(guess**3 - cube) <= 0.01的条件,循环会一直运行。
修复步骤
1. 修正初始区间
将cube > 1分支的low从cube/2改为0,确保搜索区间包含真实立方根:
# for cube > 1 if cube > 1: low = 0 # 修正此处 high = cube # for cube <= 1 else: low = 0 high = 1
2. 优化循环条件(可选)
原循环中的low <= high条件是多余的,因为二分法过程中low始终≤high,且精度达标时会自动退出,可移除该条件让逻辑更简洁:
while abs(guess**3 - cube) > epsilon:
修复后的完整代码
def approximate_cube_root(x, epsilon=0.01): cube = abs(x) # for cube > 1 if cube > 1: low = 0 # 修正初始low值 high = cube # for cube <= 1 else: low = 0 high = 1 guess = (low + high)/2 guesses = 1 # 移除多余的low <= high条件 while abs(guess**3 - cube) > epsilon: if guess**3 < cube: low = guess else: high = guess guess = (low + high) / 2 guesses += 1 if x < 0: guess = -guess if abs(guess**3 - x) > epsilon: print("Couldn't approximate with this precision, please increase epsilon") return False else: print(f"Found root cube as {guess} for {x} after {guesses} guesses") return True
测试验证
调用approximate_cube_root(8, 0.01)会输出:
Found root cube as 2.0 for 8 after 1 guesses
完全符合预期,且不会再出现死循环。
内容的提问来源于stack exchange,提问作者Cipher
相关产品推荐
相关产品推荐

