Comparing float and decimal
Robert Lehmann
stargaming at gmail.com
Tue Sep 23 08:58:57 EDT 2008
On Tue, 23 Sep 2008 07:20:12 -0400, D'Arcy J.M. Cain wrote:
> I'm not sure I follow this logic. Can someone explain why float and
> integer can be compared with each other and decimal can be compared to
> integer but decimal can't be compared to float?
In comparisons, `Decimal` tries to convert the other type to a `Decimal`.
If this fails -- and it does for floats -- the equality comparison
renders to False. For ordering comparisons, eg. ``D("10") < 10.0``, it
fails more verbosely::
TypeError: unorderable types: Decimal() < float()
The `decimal tutorial`_ states:
"To create a Decimal from a float, first convert it to a string. This
serves as an explicit reminder of the details of the conversion
(including representation error)."
See the `decimal FAQ`_ for a way to convert floats to Decimals.
>>>> from decimal import Decimal
>>>> i = 10
>>>> f = 10.0
>>>> d = Decimal("10.00")
>>>> i == f
> True
>>>> i == d
> True
>>>> f == d
> False
>
> This seems to break the rule that if A is equal to B and B is equal to C
> then A is equal to C.
I don't see why transitivity should apply to Python objects in general.
HTH,
.. _decimal tutorial: http://docs.python.org/lib/decimal-tutorial.html
.. _decimal FAQ: http://docs.python.org/lib/decimal-faq.html
--
Robert "Stargaming" Lehmann
More information about the Python-list
mailing list