[SciPy-User] How to numpy.vectorize functions with keyword arguments?
Christoph Deil
deil.christoph at googlemail.com
Tue Jun 21 06:53:18 EDT 2011
Hi,
I have some functions that use if and for statements such as the simplified
example find_x below and would like to use them on numpy arrays.
Question 1: Is there a way to write an iterative algorithm with a stopping
condition (such as find_x) without if and for, only using numpy methods (I
need speed!) ?
Question 2: numpy.vectorized functions don't like being called with keyword
arguments, the first line in __main__ raises a TypeError.
Why does this happen? What is the standard method to make vectorized
functions callable with keyword arguments?
I found that writing a wrapper (wrapped_find_x) works, but I'd rather not
litter my code with many such wrapper functions.
In the example below it would be ok just using positional arguments, but I
have many functions, each with ~10 keyword arguments.
Christoph
import numpy as np
@np.vectorize
def cost(x, scale='square'):
"""Some complicated function that is supplied by the user"""
if scale == 'square':
return x ** 2
elif scale == 'cube':
return x ** 3
else:
return 0
@np.vectorize
def find_x(a, f, scale='square', maxiter=100):
"""Uses an iterative algorithm to determine a result"""
x = 1
# just to avoid possibly infinite loop, maxiter should never be reached
for _ in range(maxiter):
if f(x, scale) > a:
break
x *= 2
return x
def wrapped_find_x(a, f, scale='square', maxiter=100):
return find_x(a, f, scale, maxiter)
if __name__ == '__main__':
print find_x(np.array([10, 100, 1000]), cost, scale='cube') # TypeError
print wrapped_find_x(np.array([10, 100, 1000]), cost, scale='cube') # OK
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20110621/b56eaf05/attachment.html>
More information about the SciPy-User
mailing list