[SciPy-user] addition of vectors of different lengths

Dan Christensen jdc at uwo.ca
Wed Aug 3 09:11:37 CDT 2005


One solution to my problem is to use Numeric instead of numarray.
Here's some more timing information (2GHz, P4 laptop).

First I'll repeat the previous info, which was with python 2.4
and numarray 1.3.3:

addarray(a1, a2)    126   usec
addarray(a2, a2)     20   usec
addlist(l1, l2)      96.2 usec
addlist(l2, l2)      95.8 usec

Here is python 2.4 with Numeric 23.8:

addarray(a1, a2)     15   usec
addarray(a2, a2)      4.6 usec

So even when concatenation is needed, Numeric beats numarray!  It'd be
nice to understand my numarray does so poorly at this.

For kicks, I tried using weave.inline with Numeric, and that
took about 30 usec in both cases.  If I knew more about Numeric's
C API, I could probably do better, but 15 usec is pretty good
and I prefer a pure python solution.  

As a general question, I wonder if it would be reasonable to allow
ufuncs to be applied to arrays of different sizes.  When one of the
arrays is missing data, the ufunc could be given None for that
argument, and decide whether to raise an exception or to use a default
value.  Is this something that was thought about but not done for 
some reason?

Dan

-----

For the tests above, I used:

#from numarray import *
from Numeric import *

def addarray(v1, v2):
    l1 = len(v1)
    l2 = len(v2)
    if l1 == l2:
        v = v1+v2
    elif l1 < l2:
        v = concatenate((v1+v2[:l1], v2[l1:]))
    else:
        v = concatenate((v1[:l2]+v2, v1[l2:]))
    return v

def addlist(v1, v2):
    l1 = len(v1)
    l2 = len(v2)
    if l1 == l2:
        v = map(operator.add, v1, v2)
    elif l1 < l2:
        v = map(operator.add, v1, v2[:l1])+v2[l1:]
    else:
        v = map(operator.add, v1[:l2], v2)+v1[l2:]
    return v

import weave
def addarrayinline(v1, v2):
    l1 = len(v1)
    l2 = len(v2)
    lm = min(l1,l2)
    l = max(l1,l2)
    v = zeros(l)
    code = """
           for(int i=0; i<lm; i++)
               v(i) = v1(i)+v2(i);
           if(l1 < l2)
               for(int i=lm; i<l; i++)
                   v(i) = v2(i);
           else if(l2 < l1)
               for(int i=lm; i<l; i++)
                   v(i) = v1(i);
           """
    weave.inline(code, ['l1', 'l2', 'l', 'lm', 'v1', 'v2', 'v'],
                 type_converters=weave.converters.blitz,
                 compiler = 'gcc')
    return v

l1=range(236)
a1=array(l1)
l2=range(256)
a2=array(l2)



More information about the SciPy-user mailing list