[英]while loop, in python, how to compare only 3 decimal points to cease execution
全新的編程,python,我想讓這個 while 循環在值相等時停止執行,但只保留 3 個小數點。 感謝幫助!
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
count = 0
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
count = 1 + count
return (approx, count)
print(newtonSqrt(10))
將值四舍五入到 3 個小數位(他們在那個鏈接中做了 2 個,但你可以只做 3 個),然后比較它們。 例如:
while round(better, 3) != round(approx, 3):
由於二進制表示錯誤,您不應該直接比較浮點數是否相等。 四舍五入可能有效,但看起來很黑。
相反,使用類似while abs(better-approx) < error:
with error
set to 0.001
的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.