我不清楚为什么我有以下代码的无限循环。谢谢你告诉我并回答!
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)
答案 0 :(得分:2)
问题在于即使距离最近,guess**3
和cube
之间的绝对差异仍为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.92
,guess ** 3 = 24.897
,abs(guess ** 3 - cube) == 0.103
时,epsilon
不小于0.01
。因此,您要将guess
添加到guess = 2.93
。
guess ** 3 = 25.154
,abs(guess ** 3 - cube) = 0.154
,epsilon
,也不小于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))
时,你会越走越远,所以循环会无限延续。