[Python-Dev] "Decimal(2) != float(2)"???

MRAB python at mrabarnett.plus.com
Sun Sep 30 03:03:11 CEST 2012


On 2012-09-30 01:43, Jan Kaliszewski wrote:
> Hello,
>
> In http://docs.python.org/release/3.2.3/reference/expressions.html#in
> we read: "[...] This can create the illusion of non-transitivity between
> supported cross-type comparisons and unsupported comparisons. For
> example, Decimal(2) == 2 and 2 == float(2) but Decimal(2) != float(2)."
>
> (The same is in the 3.3 docs).
>
> But:
>
>       Python 3.2.3 (default, Sep 10 2012, 18:14:40)
>       [GCC 4.6.3] on linux2
>       Type "help", "copyright", "credits" or "license" for more
> information.
>       >>> import decimal
>       >>> decimal.Decimal(2) == float(2)
>       True
>
> Is it a bug in the docs or in Python itself? (I checked that in 3.2,
> but it may be true for 3.3 as well)
>
It's the same in Python 3.3:

 >>> decimal.Decimal(2) == float(2)
True

Also:

 >>> decimal.Decimal(0.1) == 0.1
True
 >>> decimal.Decimal("0.1") == 0.1
False

This is because floats work in binary:

 >>> decimal.Decimal(0.1) # from a float
Decimal('0.1000000000000000055511151231257827021181583404541015625')
 >>> decimal.Decimal("0.1")
Decimal('0.1')



More information about the Python-Dev mailing list