Unexpected results comparing float to Fraction

Ian Kelly ian.g.kelly at gmail.com
Mon Jul 29 22:35:21 CEST 2013


On Jul 29, 2013 1:37 PM, "Serhiy Storchaka" <storchaka at gmail.com> wrote:
>
> 29.07.13 19:09, MRAB написав(ла):
>
>> 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).
>
>
> >>> def approximate_fraction(f):
>     prev_numer, numer = 0, 1
>     prev_denom, denom = 1, 0
>     r = f
>     while True:
>         i = math.floor(r)
>         prev_numer, numer = numer, i * numer + prev_numer
>         prev_denom, denom = denom, i * denom + prev_denom
>         if i == r or numer / denom == f:
>             break
>         r = 1 / (r - i)
>
>     return Fraction(numer, denom)
>
> >>> approximate_fraction(1/3)
> Fraction(1, 3)
> >>> approximate_fraction(1e-17)
> Fraction(1, 100000000000000000)
> >>> approximate_fraction(math.pi)
> Fraction(245850922, 78256779)
>
> I guess the Fraction constructor is more faster than this function.

You might be able to speed it up a bit with numpy and the observation that
the update is a matrix multiplication. But I don't think that you can get
away from it being an iterative algorithm.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130729/42d3b06d/attachment.html>


More information about the Python-list mailing list