[Numpy-discussion] subtract.reduce behavior

Alan G Isaac aisaac at american.edu
Fri Jul 23 10:29:47 EDT 2010


On 7/22/2010 4:00 PM, Johann Hibschman wrote:
> I'm trying to understand numpy.subtract.reduce.  The documentation
> doesn't seem to match the behavior.  The documentation claims
>
>    For a one-dimensional array, reduce produces results equivalent to:
>
>    r = op.identity
>    for i in xrange(len(A)):
>       r = op(r,A[i])
>    return r
>
> However, numpy.subtract.reduce([1,2,3]) gives me 1-2-3==-4, not
> 0-1-2-3==-6.


The behavior does not quite match Python's reduce.
The rule seems to be:
return the *right identity* for empty arrays,
otherwise behave like Python's reduce.

         >>> import operator as o
         >>> reduce(o.sub, [1,2,3], 0)
         -6
         >>> reduce(o.sub, [1,2,3])
         -4
         >>> reduce(o.sub, [])
         Traceback (most recent call last):
           File "<stdin>", line 1, in <module>
         TypeError: reduce() of empty sequence with no initial value
         >>> np.subtract.reduce([])
         0.0

Getting a right identity for an empty array is surprising.
Matching Python's behavior (raising a TypeError) seems desirable. (?)

Unfortunately Python's reduce does not make ``initializer`` a
keyword, but maybe NumPy could add this keyword anyway?
(Not sure that's a good idea.)

Alan Isaac




More information about the NumPy-Discussion mailing list