Reputation: 11
Consider the following:
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 2.0
>>> print x < 2.0
False
>>>
>>> x = 2.2
>>> x -= 0.2
>>> print x < 2.0
False
>>>
>>> x = 2.4
>>> x -= 0.2
>>> x -= 0.2
>>> print x < 2.0
True
>>> print x
2.0
Why does the 2nd last statement print True when x reduces from 2.4 to 2.0 ? What am I missing ?
Upvotes: 0
Views: 130
Reputation: 3613
As the comments mention, floating point numbers in general have inaccuracies compared to fixed point numbers. You can get a little more hint of this by asking to Python to print the number with more precision:
>>> '%0.20g' % (2.4 - 0.2 - 0.2)
'1.999999999999999778'
As you can see, this number is less than 2.
If you want to use a numeric data type with fixed precision, Python provides the Decimal data type.
>>> from decimal import Decimal
>>> Decimal('2.4') - Decimal('0.2') - Decimal('0.2')
Decimal('2.0')
>>> Decimal('2.0') < 2.0
False
But bear in mind that Decimal arithmetic will be slower than built in floating point arithmetic, so should only be used when the extra precision is required (e.g., in financial calculations)
Upvotes: 3
Reputation: 500197
You are missing the fact that neither 2.4 nor 0.2 have exact float
representations:
In [31]: '%.20f' % 2.4
Out[31]: '2.39999999999999991118'
In [32]: '%.20f' % 0.2
Out[32]: '0.20000000000000001110'
Thus:
In [33]: '%.20f' % (2.4 - 0.2 - 0.2)
Out[33]: '1.99999999999999977796'
which is less than 2.0.
This is discussed further in the tutorial (although it is worth noting that the issue is in no way Python-specific, but is a general limitation of floating-point numbers).
Upvotes: 7