Feature suggestion: sum() ought to use a compensated summation algorithm

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 4 20:14:15 EDT 2008


En Sun, 04 May 2008 12:58:25 -0300, Duncan Booth <duncan.booth at invalid.invalid> escribió:

> Szabolcs Horvát <szhorvat at gmail.com> wrote:
>
>> I thought that it would be very nice if the built-in sum() function used
>> this algorithm by default.  Has this been brought up before?  Would this
>> have any disadvantages (apart from a slight performance impact, but
>> Python is a high-level language anyway ...)?
>
> There's a thread you might find interesting:
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/9eda29faf92f532e/027cef7d4429aa3a
>
> In that thread I suggested that Python ought to implement sum by adding
> together each pair of values, then each pair of results and so on. This
> means that for input values of a similar magnitude the intermediate results
> stay balanced. The implementation doesn't actually do all the first level

Python doesn't require __add__ to be associative, so this should not be used as a general sum replacement. But if you know that you're adding floating point numbers you can use whatever algorithm best fits you. Or use numpy arrays; I think they implement Kahan summation or a similar algorithm.

-- 
Gabriel Genellina




More information about the Python-list mailing list