在Python中使用delta和epsilon查找立方根

时间:2016-10-19 23:33:32

标签: python python-3.x

我正在尝试编写一个使用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)

1 个答案:

答案 0 :(得分:2)

首先,您应该使用if/elif而不是单独的if块。

请考虑以下事项: 当guess**3 > numTrue时,您通过降低其值来更新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)