How to Pass Function as Parameter in Python (Numpy)?


If you want to compute x2 you can easily write a function in Python like this:

def sqr(x):
    return x * x  # or  x ** 2

If you want to compute sin2(x) you can invoke sqr(sin(x)). However, if the input is a list (or vector), the above function doesn’t work.

The workaround is to re-define the sqr function that takes the first parameter as a function.

def sqr(fn, x):
    y = fn(x)
    return y * y

Then, we can call the function like this:

print sqr(sin, 0.5)
0.229848847066

Or, if input x is array (vector, list):

x = [i*pi/180 for i in xrange(5)]
print sqr(sin, x)

This also works for numpy.

print sqr(np.sin, np.linspace(0, 2*np.pi, 10))
[  0.00000000e+00   4.13175911e-01   9.69846310e-01   7.50000000e-01
   1.16977778e-01   1.16977778e-01   7.50000000e-01   9.69846310e-01
   4.13175911e-01   5.99903913e-32]

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
206 words
Last Post: How to Delete Trash File from Your Windows System using Batch Script?
Next Post: How to Compute Numerical integration in Numpy (Python)?

The Permanent URL is: How to Pass Function as Parameter in Python (Numpy)?

Leave a Reply