What is the difference between np.sum
and np.add.reduce
?
While the docs are quite explicit:
For example, add.reduce()
There is actually one difference that might bite you if you were to blindly refactor from one to the other:
>>> import numpy as np
>>> a = np.arange(4).reshape(2, 2)
>>>
>>> np.sum(a)
6
>>> np.add.reduce(a)
array([2, 4])
>>>
The axis
default values are different!
Short answer: when the argument is a numpy array, np.sum
ultimately calls add.reduce
to do the work. The overhead of handling its argument and dispatching to add.reduce
is why np.sum
is slower.
Longer answer:
np.sum
is defined in numpy/core/fromnumeric.py. In the definition of np.sum
, you'll
see that the work is passed on to _methods._sum
. That function, in _methods.py, is simply:
def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
return um.add.reduce(a, axis=axis, dtype=dtype,
out=out, keepdims=keepdims)
um
is the module where the add
ufunc is defined.