Unexpected results comparing float to Fraction

Chris Angelico rosuav at gmail.com
Mon Jul 29 13:14:00 EDT 2013


On Mon, Jul 29, 2013 at 5:40 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> 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.

I imagine it is, and that's where the problem comes in. The true value
is somewhere between (X-0.5)/2**n and (X+0.5)/2**n, or whatever the
actual range is, and finding a "nice" fraction in that range isn't an
instant and direct translation. It's a useful feature, but not IMO
necessary for the constructor.

ChrisA



More information about the Python-list mailing list