Unexpected results comparing float to Fraction

MRAB python at mrabarnett.plus.com
Mon Jul 29 12:48:21 EDT 2013


On 29/07/2013 17:20, Chris Angelico 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)?
>
When the error drops below a certain threshold.

>>>> Fraction(0.3)
> Fraction(5404319552844595, 18014398509481984)
>>>> Fraction(0.33)
> Fraction(5944751508129055, 18014398509481984)
>>>> Fraction(0.333)
> Fraction(5998794703657501, 18014398509481984)
>>>> Fraction(0.3333333)
> Fraction(6004798902680711, 18014398509481984)
>>>> Fraction(0.3333333333)
> Fraction(6004799502560181, 18014398509481984)
>>>> Fraction(0.3333333333333)
> Fraction(6004799503160061, 18014398509481984)
>>>> Fraction(0.33333333333333333)
> Fraction(6004799503160661, 18014398509481984)
>
> Rounding off like that is a job for a cool library function (one of
> which was mentioned on this list a little while ago, I believe), but
> not IMO for the Fraction constructor.
>




More information about the Python-list mailing list