[Python-Dev] Mixing float and Decimal -- thread reboot

Mark Dickinson dickinsm at gmail.com
Mon Mar 22 10:23:00 CET 2010

On Sun, Mar 21, 2010 at 10:50 PM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Raymond Hettinger wrote:
>> Since decimal also allows arbitrary sizes, all long ints can be
>> exactly represented (this was even one of the design goals
>> for the decimal module).
> There may be something we need to clarify here. I've been
> imagining that the implicit conversions to Decimal that
> we're talking about would be done to whatever precision
> is set in the context. Am I wrong about that? Is the intention
> to always use enough digits to get an exact representation?

I've been thinking about this, too.

Currently, Decimal + integer -> Decimal converts the integer
losslessly, with no reference to the Decimal context.

But the Fraction type is going to mess this up:  for Decimal +
Fraction ->  Decimal, I don't see any other sensible option than to
convert the Fraction using the current context, since lossless
conversion isn't generally possible.

So with the above two conventions, we'd potentially end up with
Decimal('1.23') + 314159 giving a different result from
Decimal('1.23') + Fraction(314159, 1)  (depending on the context).

It may be that we should reconsider Decimal + int interactions, making
the implicit int->Decimal conversion lossy.  Decimal would then match
the way that float behaves:  float + int and float + Fraction both do
a lossy conversion of the non-Fraction argument to Fraction.  But then
we're changing established behaviour of the Decimal module, which
could cause problems for existing users.

Note that comparisons are a separate issue:  those always need to be
done exactly (at least for equality, and once you're doing it for
equality it makes sense to make the other comaprisons exact as well),
else the rule that x == y implies hash(x) == hash(y) would become
untenable.  Again, this is the pattern that already exists for
int<->float and Fraction<->float interactions: comparisons are exact,
but arithmetic operations involve a lossy conversion.


More information about the Python-Dev mailing list