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

Mark Dickinson dickinsm at gmail.com
Sat Mar 20 00:13:29 CET 2010


Just a couple of quick side comments on this;  I haven't got my head
around the whole mixed-operations idea yet.

On Fri, Mar 19, 2010 at 9:50 PM, Guido van Rossum <guido at python.org> wrote:
> There is one choice which I'm not sure about. Should a mixed
> float/Decimal operation return a float or a Decimal?

I'll just say that it's much easier to return a Decimal if you want to
be able to make guarantees about rounding behaviour, basically because
floats can be converted losslessly to Decimals.  I also like the fact
that the decimal module offers more control (rounding mode, precision,
flags, wider exponent range) than float.

In general, the correct semantics for an arithmetic operation are to
produce a result that's equivalent to what would have been obtained by
performing the operation to infinite precision and then doing a single
round to fit that result into the output type format.  This is
trivially easy to do if mixed float and Decimal operations produce
Decimal, and much much harder if they produce floats;  if mixed-type
operations produced floats we'd probably have to go with algorithms
that involve two rounds (i.e., first coerce the Decimal to a float,
then do the operation as usual on the two floats), and there would
likely be some (small) numeric surprises as a result.

> The implementation of __hash__ will be complicated, and it may make
> sense to tweak the hash function of float, Fraction and Decimal to
> make it easier to ensure that for values that can be represented in
> either type the hash matches the equality. But this sounds a
> worthwhile price to pay for proper embedding in the numeric tower.

I don't think this is going to be a problem.  I've implemented most of
the scheme I outlined earlier (it's working for ints, floats and
Decimals;  still need to implement it for Fractions and complex
numbers) and it seems to work just fine, with essentially no more code
than was there before.  I'll post a proof-of-concept patch when I've
filled in the missing bits.

Mark


More information about the Python-Dev mailing list