4

Why exactly does the latter case in Python doesn't yield the result 3.3?

>>> 1.0 + 2.3 3.3 >>> 1.1 + 2.2 3.3000000000000003 

It doesn't seem to make any sense to me what is going on here. What are the limitations here for the representation of the same result that you are getting through 1.0 + 2.3 but not through 1.1 + 2.2?

3
  • 1
    Its a tough read, but this will help you understand what is going on: docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Commented Oct 24, 2013 at 18:01
  • 4
    Floating point numbers are, generally speaking, not exact representations of decimal numbers, but approximations. To get exact representations of decimal numbers, see docs.python.org/2/library/decimal.html Commented Oct 24, 2013 at 18:01
  • 2
    @JasonSperske: I'd say that's recommended reading for anyone being able to rake in 5k in SO rep and wonder about this. Commented Oct 24, 2013 at 18:44

1 Answer 1

9

To quote the documentation:

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

And what you have stumbled upon is one of many idiosyncrasies:

>>> 1.1 + 1.1 2.2 >>> 1.1 + 2.3 3.4 >>> 1.1 + 2.2 3.3000000000000003 

In fact, its a rare one, I've had a hard time finding other occurrences. Here's another weird one:

>>> 0.1 + 0.1 + 0.1 - 0.3 5.551115123125783e-17 

Using Python's decimal class would give you better results.

Sign up to request clarification or add additional context in comments.

8 Comments

or the decimal module
I gave you +1 but numpy is not a good solution here. numpy still uses binary floats. The decimal library would provide an exact solution here, as decimal operates exactly on decimal values.
I thought python just usually uses IEE754, and numpy probably, too. Could you give an example? Maybe you were thinking of e.g. sympy.mpmath.
+1 for 0.1 + 0.1 + 0.1 - 0.3 :)
@steveha @Benjamin You guys are right. It was my mistake, I thought numpy had more precision, but that turns out to be not entirely true. Decimal is more precise, but its not all that precise either.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.