Floating Point Limitations

你说的曾经没有我的故事 提交于 2019-11-26 19:11:50
Jon Skeet

I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the decimal module.

This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.

You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.

As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.

Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library:

>>> from decimal import Decimal
>>> a = Decimal('2.3')
>>> print a
2.3

This is actually a (very) F.A.Q. for Python and you can read the answer here.


Edit: I just noticed that John Skeet already mentioned this. Oh well...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!