[Python-ideas] Yet another sum function (fractions.sum)

Paul Moore p.f.moore at gmail.com
Mon Aug 19 17:18:55 CEST 2013


On 19 August 2013 14:58, Peter Otten <__peter__ at web.de> wrote:

> You'd need another language for that -- or pypyesque magic ;)
>

Yes, that was sort of my point :-)


> If there are multiple sum functions, typically one per type of summand, how
> can you make them easily discoverable? I doubt that fsum is used in many
> places where it would be appropriate. If you make the optimizations
> available via the built-in sum() you can add a sentence like
>
> "If you provide an explicit start value sum() may pick an algorithm
> optimized for that type." # needs work
>
> to its documentation and be done.
>

having

    l = <a list of floats>

and then

    res = sum(l)
    res = sum(l, 0.0)
    res = sum(l, 0)
    res = sum(l, Decimal('0.0'))
    res = sum(l, Fraction(0, 1))

all do subtly (or maybe not so subtly!) different things, seems to me to be
a recipe for confusion, if not disaster.

Certainly sum/math.fsum/etc. are not particularly discoverable, but that
can *also* be fixed with documentation. In the documentation of sum(), add
a paragraph:

"""If your values are all of one particular type, specialised functions for
that type may be available - these may be more numerically stable, or
faster, or otherwise more appropriate. The standard library includes
math.fsum for floats, X.sum for X, ..."""

That's just as good if you're starting from "I want to sum some values".
And it's a lot *more* straightforward to find/google the documentation of
math.fsum from code that calls it, than to know where you'd find details of
the specialised algorithm used for sum(l, 0.0) if that was all you had to
go on...

Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130819/444dda7e/attachment-0001.html>


More information about the Python-ideas mailing list