Unexpected results comparing float to Fraction

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jul 29 15:32:38 EDT 2013


On Mon, 29 Jul 2013 17:20:27 +0100, Chris Angelico wrote:

>>>> Fraction(0.3)
> Fraction(5404319552844595, 18014398509481984)
>>>> Fraction(0.33)
> Fraction(5944751508129055, 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.

Or:

py> Fraction(1/3).limit_denominator(100)
Fraction(1, 3)


I think it would be useful for Fraction.from_float() to accept an 
optional second argument, the maximum denominator:

Fraction.from_float(x, den=None)
=> nearest fraction to float 1/3, with denominator no greater than den



-- 
Steven



More information about the Python-list mailing list