[Numpy-discussion] numpy.vectorize performance

Nick Fotopoulos nvf at MIT.EDU
Thu Jul 13 19:08:19 CDT 2006

Dear all,

I often make use of numpy.vectorize to make programs read more like  
the physics equations I write on paper.  numpy.vectorize is basically  
a wrapper for numpy.frompyfunc.  Reading Travis's Scipy Book (mine is  
dated Jan 6 2005) kind of suggests to me that it returns a full- 
fledged ufunc exactly like built-in ufuncs.

First, is this true?  Second, how is the performance?  i.e., are my  
functions performing approximately as fast as they could be or would  
they still gain a great deal of speed by rewriting it in C or some  
other compiled python accelerator?

As an aside, I've found the following function decorator to be  
helpful for readability, and perhaps others will enjoy it or improve  
upon it:

def autovectorized(f):
     """Function decorator to do vectorization only as necessary.
     vectorized functions fail for scalar inputs."""
     def wrapper(input):
         if type(input) == numpy.arraytype:
             return numpy.vectorize(f)(input)
         return f(input)
     return wrapper

For those unfamiliar to the syntactic joys of Python 2.4, you can  
then use this as:

def myOtherwiseScalarFunction(*args):

and now the function will work with both numpy arrays and scalars.

Take care,

More information about the Numpy-discussion mailing list