Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news2.arglkargh.de!news.mixmin.net!rt.uk.eu.org!newsfeed.xs4all.nl!newsfeed1.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.002 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'mrab': 0.05; 'float': 0.07; 'constructor': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.12; 'received:80.91.229.3': 0.16; 'received:plane.gmane.org': 0.16; 'true:': 0.16; 'all,': 0.19; '>>>': 0.22; 'header:User-Agent:1': 0.23; 'fraction': 0.24; 'header:X-Complaints-To:1': 0.27; 'header:In-Reply-To:1': 0.27; "i'm": 0.30; 'guess': 0.33; '8bit%:86': 0.38; 'to:addr:python- list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'break': 0.61; 'more': 0.64; 'subject:results': 0.91 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Serhiy Storchaka Subject: Re: Unexpected results comparing float to Fraction Date: Mon, 29 Jul 2013 22:34:04 +0300 References: <51f68d9c$0$30000$c3e8da3$5496439d@news.astraweb.com> <51F693B4.9000201@mrabarnett.plus.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Gmane-NNTP-Posting-Host: 37.19.137.81 User-Agent: Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/20130623 Thunderbird/17.0.7 In-Reply-To: <51F693B4.9000201@mrabarnett.plus.com> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 29 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1375126459 news.xs4all.nl 15931 [2001:888:2000:d::a6]:45877 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:51478 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.