Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Matt Wheeler Newsgroups: comp.lang.python Subject: Re: sum accuracy Date: Fri, 15 Apr 2016 18:04:14 +0100 Lines: 28 Message-ID: References: <570E78F9.8050409@chamonix.reportlab.co.uk> <1460567110.3933817.577783969.165F6097@webmail.messagingengine.com> <5710B365.5040903@chamonix.reportlab.co.uk> <87d1prw5b7.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 X-Trace: news.uni-berlin.de 186PIdr8U3yCgIc/UUux4wgVvYU+mTc29UJz6cRP6hzw== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.016 X-Spam-Evidence: '*H*': 0.97; '*S*': 0.00; 'float': 0.05; 'rounding': 0.09; 'def': 0.13; '2016': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'to:name:python list': 0.16; 'wrote:': 0.16; 'numerical': 0.18; 'input': 0.18; 'fraction': 0.22; 'import': 0.24; 'header:In-Reply-To:1': 0.24; 'message- id:@mail.gmail.com': 0.27; 'errors.': 0.27; 'convert': 0.29; 'objects': 0.29; 'error.': 0.31; 'received:google.com': 0.35; 'could': 0.35; 'but': 0.36; 'received:209.85': 0.36; 'to:addr :python-list': 0.36; 'subject:: ': 0.37; 'expect': 0.37; 'received:209': 0.38; 'build': 0.40; 'to:addr:python.org': 0.40; 'still': 0.40; 'skip:n 40': 0.72; 'from:addr:m': 0.84 X-Virus-Scanned: Debian amavisd-new at membrane.funkyhat.net X-Gm-Message-State: AOPr4FXbHJOn/rnInQSXumRYsnCQyHzjQ9EXHw46n8SRYlaBoElMizMa1eDn2jDBLGUeD64W9MPKylEKBU9IVg== X-Received: by 10.112.221.129 with SMTP id qe1mr9685279lbc.118.1460739874112; Fri, 15 Apr 2016 10:04:34 -0700 (PDT) In-Reply-To: <87d1prw5b7.fsf@bsb.me.uk> X-Gmail-Original-Message-ID: X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: X-Mailman-Original-References: <570E78F9.8050409@chamonix.reportlab.co.uk> <1460567110.3933817.577783969.165F6097@webmail.messagingengine.com> <5710B365.5040903@chamonix.reportlab.co.uk> <87d1prw5b7.fsf@bsb.me.uk> Xref: csiph.com comp.lang.python:107066 So we could build on this On 15 April 2016 at 11:10, Ben Bacarisse wrote: >> from fractions import Fraction >> >> def exact_sum(nums): >> return sum(map(Fraction, nums)) >> >> This will give you the exact result with precisely zero rounding >> error. You can convert it to float at the end. > > Just a word of warning for people new to numerical work: there's no > rounding error, but unless you start with Fraction objects you still > have input or conversion errors. The uninitiated might expect > > exact_sum([0.3, 0.7]) > > to be 1. and make def not_exact_but_probably_the_sum_you_wanted(nums): return sum(map(lambda x:Fraction(x).limit_denominator(), nums)) -- Matt Wheeler http://funkyh.at