views:

289

answers:

3

>>> float(str(0.65000000000000002))

0.65000000000000002

>>> float(str(0.47000000000000003))

0.46999999999999997 ???

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

I am using python 2.5.4 on windows.

+3  A: 

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

Alex
+9  A: 

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.

RC
Thanks, good to know!
Klerk
Note: Use decimal here not only for precision but also for exactness.
Joey
I am not sure, but I perceive "precision" and "exactness" as synonyms, precision being the usual term.
ΤΖΩΤΖΙΟΥ
See http://en.wikipedia.org/wiki/Precision_vs._accuracy - the numbers discussed are very precise but the problem discussed is that they are inaccurate.
gravitystorm
+2  A: 

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.

Nick Craig-Wood