鉴于avg_guess中的.5 - 我是否需要所有浮动(arg)规范?
# Heron of Alexandria method for approximating
# the square root of a number
def heron(num, guess, tolerance):
print "Your guess squared:",guess**2
if guess**2 != num:
print "When squared, the guess:", guess, "is",abs(float(num) - float(guess)**2), "away from", num, "\n"
if abs(float(num) - float(guess)**2) > float(tolerance):
avg_guess = 0.5 * (float(guess) + (float(num) / float(guess)))
return heron(num, avg_guess, tolerance)
print "Given your tolerance, this is Heron's best guess:", guess, "\n"
else:
print guess, "is correct!\n"
我注意到一定的容差,这个函数将返回5.0作为答案......不确定为什么?
heron(25, 3, .00000001)
从"返回5.0;否则:"条件,但
heron(25, 3, .0000001)
终止于初始嵌套的容差" if:"条件,印刷: 鉴于你的宽容,这是Heron的最佳猜测:5.00000000233。