[Numpy-discussion] Vectorizing a function
Scott Ransom
sransom at nrao.edu
Wed Jan 30 08:20:54 EST 2008
On a side note, given that I've seen quite a few posts about
vectorize() over the past several months...
I've written hundreds or thousands of functions that are intended
to work with numeric/numpy arrays and/or scalars and I've _never_
(not once!) found a need for the vectorize function. Python's
duck-typing has almost always allowed things to work without any
(or sometimes with only minor) changes to the function. For
example:
In [12]: def foo(x, y):
....: return 2.0*x + y
In [13]: foo(3.0, 5.0)
Out[13]: 11.0
In [14]: foo(arange(4), ones(4)+3.0)
Out[14]: array([ 4., 6., 8., 10.])
In [15]: foo(arange(4), 3.0)
Out[15]: array([ 3., 5., 7., 9.])
That works fine with arrays, scalars, or array/scalar mixes in the
calling. I do understand that more complicated functions might
require vectorize(), however, I wonder if sometimes it is used
when it doesn't need to be?
Scott
On Wed, Jan 30, 2008 at 10:22:15AM +0100, Gael Varoquaux wrote:
> On Wed, Jan 30, 2008 at 12:49:44AM -0800, LB wrote:
> > My problem is that the complexe calculations made in calc_0d use some
> > parameters, which are currently defined at the head of my python file.
> > This is not very nice and I can't define a module containing theses
> > two functions and call them with different parameters.
>
> > I would like to make this cleaner and pass theses parameter as
> > keyword argument, but this don't seems to be possible with vectorize.
> > Indeed, some of theses parameters are array parameters and only the x
> > and y arguments should be interpreted with the broadcasting rules....
>
> > What is the "good way" for doing this ?
>
> I don't know what the "good way" is, but you can always use functional
> programming style (Oh, no, CaML is getting on me !):
>
> def calc_0d_params(param1, param2, param3):
> def calc_0d(x, y):
> # Here your code making use of param1, param2, param3)
> ...
>
> return calc_0d(x, y)
>
> you call the function like this:
>
> calc_0d_params(param1, param2, param3)(x, y)
>
> To vectorize it you can do:
>
> calc_0d_vect = lambda *params: vectorize(calc_0d_params(*params))
>
> This is untested code, but I hope you get the idea. It all about partial
> evaluation of arguments. By the way, the parameters can now be keyword
> arguments.
>
> HTH,
>
> Gaël
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
--
--
Scott M. Ransom Address: NRAO
Phone: (434) 296-0320 520 Edgemont Rd.
email: sransom at nrao.edu Charlottesville, VA 22903 USA
GPG Fingerprint: 06A9 9553 78BE 16DB 407B FFCA 9BFA B6FF FFD3 2989
More information about the NumPy-Discussion
mailing list