Unexpected results comparing float to Fraction
MRAB
python at mrabarnett.plus.com
Mon Jul 29 18:09:24 CEST 2013
On 29/07/2013 16:43, Steven D'Aprano 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?
>
I'm surprised that Fraction(1/3) != Fraction(1, 3); after all, floats
are approximate anyway, and the float value 1/3 is more likely to be
Fraction(1, 3) than Fraction(6004799503160661, 18014398509481984).
More information about the Python-list
mailing list