python 浮點數出現長串0 錯誤位數

https://stackoverflow.com/questions/10403434/floating-point-in-python-gives-a-wrong-answer

>>> float(10.0-9.2)
0.800000000000000*7*

注意到 n*0.001 有時也會出現類似的問題,

>>> 817*0.001
0.8170000000000001
 

這是一個Python 內置的錯誤:

Floating point arithmetic has built-in problems as it's based on a binary approximation of numbers.

There is a good explanation of this in the Python docs.

You can check out the decimal module if you need more exact answers.

採用round 可以解決這個問題。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章