Python float - str - float weirdness
Asked Answered
D

4

11
>>> 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.

Dramaturgy answered 22/11, 2009 at 10:28 Comment(3)
RC: I think many many people (yes, programmers too) don't eevn know that IEEE 754 defines floating-point numbers (not everyone reads language specifications :-)). So I'd actually think that the "floating-point" tag would be a better choice unless there are specific questions about the standard itself.Bickerstaff
surely those that ask these kind of questions don't know what ieee-754 is...Destefano
wasn't aware of the floating point tag but sure it's better than the name of the spec.Rearm
R
16

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.

Rearm answered 22/11, 2009 at 10:35 Comment(3)
Note: Use decimal here not only for precision but also for exactness.Bickerstaff
I am not sure, but I perceive "precision" and "exactness" as synonyms, precision being the usual term.Kinakinabalu
See en.wikipedia.org/wiki/Precision_vs._accuracy - the numbers discussed are very precise but the problem discussed is that they are inaccurate.Ambrosial
S
3

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

Sleigh answered 22/11, 2009 at 10:34 Comment(0)
G
2

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.

Galbanum answered 22/11, 2009 at 11:41 Comment(0)
B
0

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
Bluenose answered 30/4, 2015 at 9:10 Comment(1)
How is this relevant?Booze

© 2022 - 2024 — McMap. All rights reserved.