[Python-Dev] Decimal <-> float comparisons in py3k.

Steven D'Aprano steve at pearwood.info
Tue Mar 16 23:32:08 CET 2010

On Wed, 17 Mar 2010 03:23:30 am Mark Dickinson wrote:
> On Tue, Mar 16, 2010 at 4:11 PM, Mark Dickinson <dickinsm at gmail.com>
> wrote: [...]
> >>>> Decimal.from_float(1.1) == 1.1
> >
> > False
> Whoops.  To clarify, this is the pre-patch behaviour;  post-patch,
> this gives True.

Whew! You had me worried there for a second. Just to clarify, you are 

Decimal.from_float(1.1) == 1.1
Decimal.('1.1') != float('1.1')

+1 on this behaviour, even in the absence of supporting mixed Decimal 
and float arithmetic operations.

Both Decimals and floats are representations of real numbers, and not 
being able to compare two numbers is just weird: refusing to compare 
(say) Decimal(1) with float(1) makes as little sense to me as refusing 
to compare int(1) with float(1).

But mixed arithmetic runs into the problem, what do you want the result 
type to be? Given (say) decimal+float, returning either a Decimal or a 
float will be the wrong thing to do some of the time, so better to 
prohibit mixed arithmetic and let folks handle their own conversions. 
So +1 on continuing to prohibit mixed arithmetic.

But no such problems arise with comparisons, which will always return a 
bool, and will avoid the current ... interesting ... behaviour. In 3.1:

>>> Decimal(1) == 1 == 1.0
>>> Decimal(1) == 1.0
>>> Decimal.from_float(1.0) == 1 == 1.0
>>> Decimal.from_float(1.0) == 1.0

Replacing False with an exception doesn't make it any less bizarre.

Steven D'Aprano

More information about the Python-Dev mailing list