Creating a universal function

We can create a universal function from a Python function with the NumPy frompyfunc function.

How to do it...

The following steps let us create a universal function:

  1. Define the Python function.

    Let's define a simple Python function that just doubles the input:

    def double(a):
        return 2 * a
  2. Create the universal function.

    Create the universal function with frompyfunc. We need to specify the number of input arguments and the number of objects returned:

    import numpy
    
    def double(a):
       return 2 * a
    
    ufunc = numpy.frompyfunc(double, 1, 1)
    print "Result", ufunc(numpy.arange(4))

    The code prints the following output, when executed:

    Result [0 2 4 6]
    

How it works...

We defined a Python function, which doubles the numbers it receives. Actually, we could also have strings as input, because that is legal in Python. We created a universal function from this Python function with the NumPy frompyfunc function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset