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

Guido van Rossum guido at python.org
Sat Mar 20 20:56:24 CET 2010

On Sat, Mar 20, 2010 at 4:16 AM, Mark Dickinson <dickinsm at gmail.com> wrote:
> True.  The reason I was concentrating on the hashes is that it's not
> immediately obvious that it's even *possible* to find a decent hash
> function that's efficient to compute and gives equal results for
> numerically equal inputs (regardless of type); this is especially true
> if you don't want to significantly slow down the existing hashes for
> int and float.  But once that problem is solved, it shouldn't be too
> hard to implement all the comparisons.
> It *is* kinda messy, because as far as I can see the oddities of the
> various types mean that you end up producing specialized code for
> comparing each pair of types (one block of code for float<->Fraction
> comparisons, another for float<->Decimal, yet another for
> Decimal<->Fraction, and so on), but it's doable.

I propose to reduce all hashes to the hash of a normalized fraction,
which we can define as a combination of the hashes for the numerator
and the denominator. Then all we have to do is figure fairly efficient
ways to convert floats and decimals to normalized fractions (not
necessarily Fractions). I may be naive but this seems doable: for a
float, the denominator is always a power of 2 and removing factors of
2 from the denominator is easy (just right-shift until the last bit is
zero). For Decimal, the unnormalized denominator is always a power of
10, and the normalization is a bit messier, but doesn't seem
excessively so. The resulting numerator and denominator may be large
numbers, but for typical use of Decimal and float they will rarely be
excessively large, and I'm not too worried about slowing things down
when they are (everything slows down when you're using really large
integers anyway).

--Guido van Rossum (python.org/~guido)

More information about the Python-Dev mailing list