NumPy: Universal Functions (ufunc)

Last updated: 2026-08-26

1. What You'll Learn



2. Key Concepts

(1) What Is a ufunc

A ufunc (universal function) is a C-level function that operates element-wise on ndarrays. All arithmetic operators call ufuncs under the hood.

PYTHON
import numpy as np

# Operators are ufuncs
print(np.add)        # ufunc 'add'
print(np.multiply)   # ufunc 'multiply'
print(np.sin)        # ufunc 'sin'

# ufunc attributes
print(np.add.nin)    # 2 (number of inputs)
print(np.add.nout)   # 1 (number of outputs)
print(np.add.ntypes)  # number of supported type combinations

(2) ufunc Methods

PYTHON
a = np.array([1, 2, 3, 4, 5])

# reduce: apply repeatedly to reduce to single value
print(np.add.reduce(a))     # 15 (sum)
print(np.multiply.reduce(a))  # 120 (product)

# accumulate: running result
print(np.add.accumulate(a))  # [1 3 6 10 15]

# outer: apply to all pairs
print(np.multiply.outer([1, 2, 3], [10, 20, 30]))
# [[10 20 30]
#  [20 40 60]
#  [30 60 90]]
TEXT 📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

▶ Example: ufunc attributes (Difficulty ⭐)

PYTHON
import numpy as np

print("add:", np.add)
print("multiply:", np.multiply)
print("sin:", np.sin)

print(f"np.add.nin: {np.add.nin}")
print(f"np.add.nout: {np.add.nout}")
print(f"np.add.ntypes: {np.add.ntypes}")

Output:

TEXT 📖 Display only
add: ufunc 'add'
multiply: ufunc 'multiply'
sin: ufunc 'sin'
np.add.nin: 2
np.add.nout: 1
np.add.ntypes: 22

▶ Example: ufunc reduce and accumulate (Difficulty ⭐⭐)

PYTHON
import numpy as np

a = np.array([1, 2, 3, 4, 5])

# reduce: apply repeatedly to get a single value
print("add.reduce:", np.add.reduce(a))
print("multiply.reduce:", np.multiply.reduce(a))

# accumulate: running result
print("add.accumulate:", np.add.accumulate(a))
print("multiply.accumulate:", np.multiply.accumulate(a))

Output:

TEXT 📖 Display only
add.reduce: 15
multiply.reduce: 120
add.accumulate: [ 1  3  6 10 15]
multiply.accumulate: [  1   2   6  24 120]

▶ Example: ufunc outer (Difficulty ⭐⭐)

PYTHON
import numpy as np

# Outer product: multiply every pair
x = np.array([1, 2, 3])
y = np.array([10, 20, 30, 40])
print("outer:\n", np.multiply.outer(x, y))

# Comparison outer
a = np.array([1, 3, 5])
b = np.array([2, 4, 6])
print("greater.outer:\n", np.greater.outer(a, b))

Output:

TEXT 📖 Display only
outer:
 [[ 10  20  30  40]
 [ 20  40  60  80]
 [ 30  60  90 120]]
greater.outer:
 [[False False False]
 [ True False False]
 [ True  True False]]

Q What's the difference between a ufunc and a regular function?
A A ufunc operates element-wise, handles broadcasting, type promotion, and output buffering automatically. It's implemented in C, making it much faster than Python functions.
Q How do I create a custom ufunc?
A Use np.frompyfunc(func, nin, nout) to wrap a Python function. The resulting ufunc handles broadcasting but is still Python-level, so performance is limited.
Q What is reduceat?
A np.add.reduceat(a, indices) applies reduce at specific slices — useful for segmented sums or grouped operations.

❓ FAQ

Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.

📖 Summary



📝 Exercises

  1. Beginner (Difficulty ⭐): List the attributes of np.add — nin, nout, ntypes, types. Explain what each means.

  2. Intermediate (Difficulty ⭐⭐): Use np.add.reduce to sum an array, np.add.accumulate to compute running sum, and np.multiply.outer to create a multiplication table.

  3. Advanced (Difficulty ⭐⭐⭐): Use np.frompyfunc to create a custom ufunc that returns the larger of two numbers. Apply it to two arrays and compare with np.maximum.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏