sum accuracy

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Apr 15 05:36:02 EDT 2016


On 15 April 2016 at 10:24, Robin Becker <robin at 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



More information about the Python-list mailing list