[Numpy-discussion] ufunc.accumulate question

Chris Withers chris@simplistix.co...
Tue Oct 5 07:53:22 CDT 2010


Hi All,

I can't find any docs on this behavior.

So, I have a python function. To keep it simple, lets just do addition:

def add(x,y):
   print x,y
   retun x+y

So, I can turn this into a ufunc as follows:

uadd = np.frompyfunc(add,2,1)

Now, I can apply it to an array:

 >>> uadd.accumulate(np.arange(3,10))
3 4
7 5
12 6
18 7
25 8
33 9
array([3, 7, 12, 18, 25, 33, 42], dtype=object)

Okay, but where did the initial 3 come from?
http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html#numpy.ufunc.accumulate 
suggests that:

r = np.empty(len(A))
t = op.identity        # op = the ufunc being applied to A's  elements
for i in xrange(len(A)):
     t = op(t, A[i])
     r[i] = t
return r

...but:

 >>> print uadd.identity
None

...and:

 >>> add(None,3)
None 3
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 3, in add
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

So, where is the reason that the 3 ends up in the output array documented?

Also, what if I want to specify the identity of my newly created ufunc?
I have a case where I want to specify it as zero:

 >>> uadd.identity = 0
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: attribute 'identity' of 'numpy.ufunc' objects is not 
writable

Any help gratefully received!

Chris


More information about the NumPy-Discussion mailing list