我正在尝试编写一个使用delta和epsilon查找立方根的程序,但我被卡住了因为我无法弄清楚为什么我的程序在无限循环中运行
num = 100
epsilon = 0.01
guess = num/3.0
while abs(guess**3 - num) >= epsilon:
delta = abs(guess**3 - num)/100
if guess**3 > num:
guess = (guess - delta)
if guess**3 < num:
guess = (guess + delta)
print("Guess:", guess)
答案 0 :(得分:2)
首先,您应该使用if/elif
而不是单独的if
块。
请考虑以下事项:
当guess**3 > num
为True
时,您通过降低其值来更新guess
,以便guess**3 < num
(下一个if条件)再次变为True
,这会颠倒初始更新。总之,guess
的值在该循环中永远不会改变,并且循环旋转到无穷大。
其次你要规范delta
值(惩罚它),因为随着num
的值增加,它可能会变得惊人。
num = 100
epsilon = 0.01
guess = num/3.0
while abs(guess**3 - num) >= epsilon:
delta = abs(guess**3 - num)/num
if guess**3 > num:
guess = (guess - delta*epsilon**0.5)
elif guess**3 < num:
guess = (guess + delta*epsilon**0.5)
print("Guess:", guess)