[SciPy-user] single elements and arrays

Anne Archibald peridot.faceted@gmail....
Tue Jul 1 00:49:23 CDT 2008


2008/6/30 Gideon Simpson <grs2103@columbia.edu>:
> foo finds a root where x is a parameter in the equation to be solved.
> If x is an array, I iterate through the elements of the array.

If you're actually *iterating*, in the sense of using a python loop to
go through every element, there will be substantial overhead -
something like a few tens or hundreds of floating-point operations for
every trip through the loop -  involved in looping. If the function
itself is reasonably fast and if you can write it in terms of vectors,
that will be much faster. It may also, with some care, operate
transparently on scalars.

However, if you can't - let's say it's a numerical root-finding using
brentq - then there's a handy tool to provide python-level looping:
the vectorize decorator:

@np.vectorize
def acos(y):
    return scipy.optimize.brentq(lambda x: y-np.cos(x),0,np.pi)

This makes acos behave a little like a ufunc from the user's point of
view: you can hand it a scalar or an array of arbitrary dimensionality
and it will iterate as appropriate. The iteration passes through
python, necessarily since the function being wrapped is in python, so
it won't be fast, but it is convenient.

Anne


More information about the SciPy-user mailing list