Comparing float and decimal
Terry Reedy
tjreedy at udel.edu
Tue Sep 23 14:31:49 EDT 2008
Gerhard Häring wrote:
> 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?
>>
>>>>> from decimal import Decimal
>>>>> i = 10
>>>>> f = 10.0
>>>>> d = Decimal("10.00")
>>>>> i == f
>> True
>>>>> i == d
>> True
>>>>> f == d
>> False
>
> I can give you the technical answer after reading the sources of the
> decimal module: you can only compare to Decimal what can be converted to
> Decimal. And that is int, long and another Decimal.
The new fractions module acts differently, which is to say, as most
would want.
>>> from fractions import Fraction as F
>>> F(1) == 1.0
True
>>> F(1.0)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
F(1.0)
File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__
numerator = operator.index(numerator)
TypeError: 'float' object cannot be interpreted as an integer
>>> F(1,2) == .5
True
>>> .5 == F(1,2)
True
so Fraction obviously does comparisons differently.
Decimal is something of an anomaly in Python because it was written to
exactly follow an external standard, with no concessions to what would
be sensible for Python. It is possible that that standard mandates that
Decimals not compare to floats.
tjr
More information about the Python-list
mailing list