Python float - str - float weirdness

落爺英雄遲暮 提交于 2019-11-26 02:38:47

问题


>>> float(str(0.65000000000000002))

0.65000000000000002

>>> float(str(0.47000000000000003))

0.46999999999999997     ???

What is going on here? How do I convert 0.47000000000000003 to string and the resultant value back to float?

I am using Python 2.5.4 on Windows.


回答1:


str(0.47000000000000003) give '0.47' and float('0.47') can be 0.46999999999999997. This is due to the way floating point number are represented (see this wikipedia article)

Note: float(repr(0.47000000000000003)) or eval(repr(0.47000000000000003)) will give you the expected result, but you should use Decimal if you need precision.




回答2:


float (and double) do not have infinite precision. Naturally, rounding errors occur when you operate on them.




回答3:


This is a Python FAQ

The same question comes up quite regularly in comp.lang.python also.

I think reason it is a FAQ is that because python is perfect in all other respects ;-), we expect it to perform arithmetic perfectly - just like we were taught at school. However, as anyone who has done a numerical methods course will tell you, floating point numbers are a very long way from perfect.

Decimal is a good alternative and if you want more speed and more options gmpy is great too.




回答4:


by this example I think this is an error in Python when you devide

    >>> print(int(((48/5.0)-9)*5))
    2

the easy way, I solve this problem by this

    >>> print(int(round(((48/5.0)-9)*5,2)))
    3


来源:https://stackoverflow.com/questions/1778368/python-float-str-float-weirdness

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