2
我試圖用牛頓法返回k的平方根的最小值。Python 3.3,在while循環中返回最小值
k=float(input("Number? "))
x = k/2
def newton(x):
while abs(x**(1/2)- k) >= 10**(-10):
if k >= 0:
x = (x+k/x)/(2)
return x
elif k < 0:
raise ValueError ("Cannot take the square root of a negative number")
print ("The approximate square root of", k, "is", newton(k))
print ("The error is", abs(x**(1/2)- k))
但是,上面的代碼只返回第一次迭代。例如,如果k是2,則牛頓法的精確平方根應該是1.41422,這是第三次迭代。但是,代碼目前正在返回1.5,這是第一次迭代。我如何返回更精確的平方根1.41422而不是1.5?同樣,錯誤也需要反映這種變化。
究竟做什麼你期望的時候會發生,在第一次迭代循環中,'return x'(用'x = 1.5')命中? – Ben