Create Your Own ufunc

πŸ› οΈ Creating Your Own ufunc in NumPy

NumPy allows you to create custom universal functions (ufuncs), which can then operate element-wise on NumPy arrays just like built-in ufuncs.
There are two main ways:

  1. Using np.vectorize() (Python-level, slower, but easy)

  2. Using NumPy C-API or Numba (fast, compiled, advanced)

Here, we focus on np.vectorize(), which is sufficient for most Python use-cases.


βœ… 1. Using np.vectorize()

np.vectorize() wraps a Python function so it can be applied element-wise to arrays.

import numpy as np

# Regular Python function
def my_func(x):
return x**2 + 2*x + 1 # (x+1)^2

# Convert to ufunc
my_ufunc = np.vectorize(my_func)

# Apply to array
arr = np.array([0, 1, 2, 3, 4])
result = my_ufunc(arr)

print(result) # [1 4 9 16 25]

  • Works element-wise

  • Can handle any Python function


βœ… 2. Using Lambda Function

my_ufunc2 = np.vectorize(lambda x: x**3 + 1)
result2 = my_ufunc2(arr)
print(result2) # [1 2 9 28 65]
  • Compact and convenient for simple functions


βœ… 3. Using otypes Parameter

You can specify output type with otypes to avoid type inference issues.

def square_root_plus_one(x):
return (x**0.5) + 1

ufunc3 = np.vectorize(square_root_plus_one, otypes=[float])
print(ufunc3(np.array([0, 1, 4, 9])))
# [1. 2. 3. 4.]


βœ… 4. Using Multiple Inputs

def add_multiply(x, y):
return x + 2*y

ufunc_multi = np.vectorize(add_multiply)
a = np.array([1,2,3])
b = np.array([4,5,6])

print(ufunc_multi(a, b)) # [9 12 15] -> 1+2*4, 2+2*5, 3+2*6

  • Supports multiple array inputs

  • Element-wise operations are performed


βœ… 5. Example: Conditional Function ufunc

def classify(x):
if x < 0:
return "Negative"
elif x == 0:
return "Zero"
else:
return "Positive"

ufunc_classify = np.vectorize(classify)
arr = np.array([-2, 0, 3, -1, 5])
print(ufunc_classify(arr))
# ['Negative' 'Zero' 'Positive' 'Negative' 'Positive']

  • Useful for categorical transformations


🧠 Notes

  • np.vectorize() is not truly compiled; it’s essentially a for loop in Python.

  • For high-performance ufuncs, consider Numba’s @vectorize decorator or Cython.

  • Can handle scalars, arrays, multiple inputs, and different output types.


🎯 Practice Exercises

  1. Create a ufunc that computes f(x) = x^3 – x + 2 for an array.

  2. Create a ufunc that classifies numbers as even/odd.

  3. Create a ufunc with two inputs that computes x^2 + y^2.

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *