NaN comparisons - Call For Anecdotes

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 9 03:04:56 CEST 2014


On Tue, 08 Jul 2014 13:57:30 -0600, Ian Kelly wrote:

>>>> Decimal(2) == Fraction(2)
> False
> 
> I'm not sure exactly when this bug was fixed, but it works as expected
> in 3.4.0.

It isn't a bug, it's a missing feature. The problem is that in Python 
2.7, neither Decimal nor Fraction are aware of the other:

py> Decimal(2).__eq__(Fraction(2))
NotImplemented
py> Fraction(2).__eq__(Decimal(2))
NotImplemented


The obvious, but wrong, solution is to coerce both into floats:

py> a = Decimal("2.000000000000000000000000000001")
py> b = Fraction(2) - Fraction(1, 2)**100
py> a > 2 > b  # a and b are certainly not equal
True
py> float(a) == float(b)
True

Some time by Python 3.3, Decimal appears to have become aware of how to 
compare exactly with Fraction.


-- 
Steven



More information about the Python-list mailing list