Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #107037

Re: sum accuracy

From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Newsgroups comp.lang.python
Subject Re: sum accuracy
Date 2016-04-15 10:36 +0100
Message-ID <mailman.11.1460712984.6324.python-list@python.org> (permalink)
References <570E78F9.8050409@chamonix.reportlab.co.uk> <1460567110.3933817.577783969.165F6097@webmail.messagingengine.com> <5710B365.5040903@chamonix.reportlab.co.uk> <CAHVvXxSub2Z2j6eedm3zQr7v2aYWMhmGYzXTtx+SPrcAFgXFtw@mail.gmail.com>

Show all headers | View raw


On 15 April 2016 at 10:24, Robin Becker <robin@reportlab.com> wrote:
> On 13/04/2016 18:05, Random832 wrote:
> .........
>>
>>
>> No, it doesn't. Sum works on any type that can be added (except
>> strings), it can't make any assumptions about the characteristics of
>> floating point types. For non-numeric types, the addition operator may
>> not be semantically commutative or associative.
>>
> I thought as much. My problem was that the sum of an array of small floats
> was being used to compute a grid of points by subtraction like this
>
> height = sum(H)
> pos = [height]
> for h in H:
>         height -= h
>         pos.append(height)
>
> the value of height[0] came out negative which was a problem. I could reduce
> the error by using Kahan summation instead of sum, but that required Kahan
> style subtraction as well. In the end it just seemed better to reverse the
> loop and compute pos by addition.
>
>
>> Look at
>>
>> http://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/
>> for an example of a more accurate algorithm, but note that, for example,
>> this algorithm wouldn't work on complex numbers (you'd have to sum the
>> real and imaginary components separately)
>>
> yes indeed summation is hard :(

Not with Fraction it isn't:

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.

--
Oscar

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: sum accuracy Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-04-15 10:36 +0100
  Re: sum accuracy Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-04-15 11:10 +0100
    Re: sum accuracy Tony van der Hoff <tony@vanderhoff.org> - 2016-04-15 11:39 +0100
      Re: sum accuracy Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-04-15 14:31 +0300
    Re: sum accuracy Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-04-15 08:11 -0400
    Re: sum accuracy Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-04-15 14:49 +0100
      Re: sum accuracy Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-04-15 17:54 +0100
    Re: sum accuracy Matt Wheeler <m@funkyhat.org> - 2016-04-15 18:04 +0100

csiph-web