[Python-Dev] Decimal & amp; lt; -& amp; gt; float comparisons in py3k.

Nick Coghlan ncoghlan at gmail.com
Sat Mar 20 05:20:49 CET 2010


Glenn Linderman wrote:
> The same person that would expect both
> 
> 0 == "0"
> 0.0 == "0.0"
> 
> to be False... i.e. anyone that hasn't coded in Perl for too many years.

Completely different - that is comparing numbers to strings. What this
discussion is about is comparison between the different kinds of real
number in the interpreter core and standard library (ints, floats,
decimal.Decimal, fractions.Fraction).

For arithmetic, decimal.Decimal deliberately fails to interoperate with
binary floating point numbers (hence why it isn't registered as an
example of the numbers.Real ABC).

For comparison, it only sort of fails to interoperate - it gives either
an exception or silently returns the wrong answer, depending on Python
version and the exact operator involved.

Fractions are nowhere near as purist about things - they will happily
allow themselves to be implicitly converted to floating point values.

So currently (for arithmetic):

int op int -> int (or potentially float due to division)
int op float, float op int -> float
int op Fraction, Fraction op int -> Fraction
int op Decimal, Decimal op int -> Decimal

Fraction op Fraction -> Fraction
Fraction op float, float op Fraction -> float
Fraction op Decimal, Decimal op Fraction -> TypeError

Decimal op Decimal -> Decimal
Decimal op float, float op Decimal -> TypeError

float op float -> float

Nobody is arguing in this thread for any changes to that. I just want to
contrast it with the situation for the comparison operators:

int op int -> bool
int op float, float op int -> bool
int op Fraction, Fraction op int -> bool
int op Decimal, Decimal op int -> bool

Fraction op Fraction -> bool
Fraction op float, float op Fraction -> bool
Fraction op Decimal, Decimal op Fraction -> TypeError

Decimal op Decimal -> bool
Decimal op float, float op Decimal -> TypeError

float op float -> bool

In the case of floats and Decimals, there's no ambiguity here that
creates any temptation to guess - to determine a true/false result for a
comparison, floats can be converted explicitly to Decimals without any
loss of accuracy. For Fractions, the precedent has already been set by
allowing implicit (potentially lossy) conversion to binary floats - a
lossy conversion to Decimal wouldn't be any worse.

Cheers,
Nick.

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


More information about the Python-Dev mailing list