Unexpected results comparing float to Fraction

Ian Kelly ian.g.kelly at gmail.com
Mon Jul 29 18:40:52 CEST 2013

On Mon, Jul 29, 2013 at 10:20 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Mon, Jul 29, 2013 at 5:09 PM, MRAB <python at mrabarnett.plus.com> wrote:
>> 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).
> At what point should it become Fraction(1, 3)?

At the point where the float is exactly equal to the value you get
from the floating-point division 1/3.  If it's some other float then
the user didn't get there by entering 1/3, so it's not worth trying to
pretend that they did.

We do a similar rounding when formatting floats to strings, but in
that case one only has to worry about divisors that are powers of 10.
I imagine it's going to take more time to find the correct fraction
when any pair of relatively prime integers can be a candidate
numerator and denominator.  Additionally, the string rounding only
occurs when the float is being formatted for display; we certainly
don't do it as the result of numeric operations where it could result
in loss of precision.

More information about the Python-list mailing list