On 7/29/2013 11:50 AM, Ian Kelly wrote:
On Mon, Jul 29, 2013 at 9:43 AM, Steven D'Aprano
<steve+comp.lang.pyt...@pearwood.info> wrote:
Comparing floats to Fractions gives unexpected results:
# Python 3.3
py> from fractions import Fraction
py> 1/3 == Fraction(1, 3)
False
but:
py> 1/3 == float(Fraction(1, 3))
True
I expected that float-to-Fraction comparisons would convert the Fraction
to a float, but apparently they do the opposite: they convert the float
to a Fraction:
py> Fraction(1/3)
Fraction(6004799503160661, 18014398509481984)
Am I the only one who is surprised by this? Is there a general rule for
which way numeric coercions should go when doing such comparisons?
Any float can be precisely represented as a Fraction. Not so in the
other direction.
In other words, there can be multiple unequal Franctions that have the
same float value: for instance, Fraction(1,3) and
Fraction(6004799503160661, 18014398509481984)
> So from that standpoint it makes sense to me to cast to
> Fraction when comparing.
Otherwise, == becomes non-transitive
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list