Comparing float and decimal

Mark Dickinson dickinsm at gmail.com
Tue Sep 30 07:42:52 EDT 2008


On Sep 30, 9:21 am, Terry Reedy <tjre... at udel.edu> wrote:
> If no one beats me to it, I will probably file a bug report or two, but
> I am still thinking about what to say and to suggest.

I can't see many good options here.  Some possibilities:

(0) Do nothing besides documenting the problem
somewhere (perhaps in a manual section entitled
'Infrequently Asked Questions', or
'Uncommon Python Pitfalls').  I guess the rule is
simply that Decimals don't mix well with other
numeric types besides integers:  if you put both
floats and Decimals into a set, or compare a
Decimal with a Fraction, you're asking for
trouble.  I suppose the obvious place for such
a note would be in the decimal documentation,
since non-users of decimal are unlikely to encounter
these problems.

(1) 'Fix' the Decimal type to do numerical comparisons
with other numeric types correctly, and fix up the
Decimal hash appropriately.

(2) I wonder whether there's a way to make Decimals
and floats incomparable, so that an (in)equality check
between them always raises an exception, and any
attempt to have both Decimals and floats in the same
set (or as keys in the same dict) also gives an error.
(Decimals and integers should still be allowed to
mix happily, of course.) But I can't see how this could
be done without adversely affecting set performance.

Option (1) is certainly technically feasible, but I
don't like it much: it means adding a whole load
of code to the Decimal module that benefits few users
but slows down hash computations for everyone.
And then any new numeric type that wants to fit in
with Python's rules had better worry about hashing
equal to ints, floats, Fractions, complexes, *and*
Decimals...

Option (2) appeals to me, but I can't see how to
implement it.

So I guess that just leaves updating the docs.
Other thoughts?

Mark



More information about the Python-list mailing list