适当解决方案中的无限循环

时间:2017-10-04 19:04:24

标签: python loops

我不清楚为什么我有以下代码的无限循环。谢谢你告诉我并回答!

cube = 25
epision = 0.01
guess = 0
increment = 0.01
while abs(guess**3 - cube) >= epision:
    guess += increment
if abs(guess**3 - cube) >= epision:
    print("Failed on cube root of", cube)
else:
    print (guess, 'is close to the cube root of',cube)

2 个答案:

答案 0 :(得分:2)

问题在于即使距离最近,guess**3cube之间的绝对差异仍为0.10291200000046885,因此大于epsilon

要解决此问题,您可以:

  • 使用较大的epsilon或更小的increment
  • 或将绝对差异与上一次迭代中的差异进行比较,并将break一旦它再次升起来进行比较
  • 或者只是检查是否guess**3 > cube,因为您无论如何都要从0进行测试,而不是二进制搜索

或者,实际上使用 binary search;它是一个更好的算法,更快地收敛到目标,并且(几乎)任意小的epsilon,而不是那么难实现:

lower, upper = 0, cube # cube root has to be between these two numbers
while abs(guess**3 - cube) >= epision:
    if guess**3 > cube:
        guess, upper = (guess + lower) / 2, guess
    else:
        guess, lower = (guess + upper) / 2, guess

答案 1 :(得分:0)

25的立方根约为2.92402

guess = 2.92guess ** 3 = 24.897abs(guess ** 3 - cube) == 0.103时,epsilon不小于0.01。因此,您要将guess添加到guess = 2.93

guess ** 3 = 25.154abs(guess ** 3 - cube) = 0.154epsilon,也不小于0.01

当你不断向guess添加import keras.backend as K import numpy as np numpyA = np.array(define A correctly here, with 2 dimensions) def multA(x): A = K.variable(numpyA) return K.dot(x,A) model.add(Lambda(multA)) 时,你会越走越远,所以循环会无限延续。