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

Nick Coghlan ncoghlan at gmail.com
Sun Mar 21 02:54:34 CET 2010

Guido van Rossum wrote:
> I think we should seriously reconsider allowing mixed arithmetic 
> involving Decimal, not just mixed comparisons.

I'm glad I'm not the only one that started wondering that. I
wasn't quite game enough to actually suggest it though :)

> There is one choice which I'm not sure about. Should a mixed 
> float/Decimal operation return a float or a Decimal? I note that 
> Fraction (which *is* properly embedded in the numeric tower) supports
>  this and returns a float result in this case. While I earlier 
> proposed to return the most "complicated" type of the two, i.e. 
> Decimal, I now think it may also make sense to return a float, being
>  the most "fuzzy" type in the numeric tower. This would also make 
> checking for accidental floats easier, since floats now propagate 
> throughout the computation (like NaN) and a simple assertion that the
>  result is a Decimal instance suffices to check that no floats were 
> implicitly mixed into the computation.

To blend a couple of different ideas from the thread reboot together:

I suggest a 'linearised' numeric tower that looks like:

int -> Decimal -> Fraction -> float -> complex

As Adam stated, this is a pragmatic tower stating which implicit
coercions are defined by the code, not a formal mathematical relationship.

Note that this would involve adding mixed Fraction/Decimal arithmetic as
well as Decimal/float arithmetic. I placed Decimal to the left of
Fraction to keep Decimal's dependencies clear and because Decimal ->
Fraction conversions appear straightforward (using power of 10
denominators) without introducing the precision issues that would arise
in Decimal -> Fraction conversions.

I also like the idea of adding the decimal context signal that Facundo
suggests (e.g. under the name ImplicitCoercionToBinaryFloat).

So "quick and dirty don't need a perfect answer" operations end up with
ordinary binary floats, while more precise code can enable the signal
trap to ensure the calculation fails noisily if binary floats are

Allowing implicit operations would also finally allow Decimal to be
registered with numbers.Real.

Whatever we decide to do will need to be codified in a PEP though.
"Cleaning Up Python's Numeric Tower" or something along those lines.

> 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.

And Mark appears to already have a good answer to that problem.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list