import numpy as np
x = np.array([1, 4, 9, 16])
result = np.sqrt(x)
print(result) # [1. 2. 3. 4.]
numpy.ufunc (Universal Function) Universal functions are the computational engines powering NumPy. Instead of iterating through arrays in Python, ufuncs delegate loop execution to optimized compiled C code, delivering orders of magnitude speedups. This comprehensive guide covers unary and binary ufuncs, built-in methods (reduce, accumulate, outer, reduceat), type casting rules, preallocated output buffers, and performance best practices. For related mathematical applications, review Math & ufuncs and Broadcasting.
| Ufunc Method | Description & Purpose | Example Syntax |
|---|---|---|
.reduce(a) | Repeatedly applies binary operator along axis until single value remains | np.add.reduce([1, 2, 3]) → 6 |
.accumulate(a) | Accumulates result of applying operator across elements | np.add.accumulate([1, 2, 3]) → [1, 3, 6] |
.outer(a, b) | Applies binary operator to all pairs (cartesian product of elements) | np.multiply.outer([1, 2], [3, 4]) |
.reduceat(a, indices) | Performs specified reduced operations on input array segments | np.add.reduceat(arr, [0, 3, 5]) |
A universal function (ufunc) is an instance of the numpy.ufunc class that operates transparently on ndarrays in an element-wise fashion. They support vectorization, wrapping C loops to execute without Python interpreter overhead.
The table below highlights how legacy ufunc snippets compare against the modernized, structured implementation:
| Aspect | Legacy Implementation | Modernized Implementation |
|---|---|---|
| Structure & Markup | Basic echo output with unformatted pre tags and missing metadata. | Structured HTML5 layout, Schema TechArticle markup, and responsive tables. |
| Code Presentation | Requires scrolling past introductory text to find code examples. | Core code snippet placed right at the top for instant visitor access. |
| Verification | Unchecked print statements with manual result inspection comments. | Automated unit test assertions (assert) verifying array outputs. |
| Ecosystem Integration | Isolated code blocks with sparse navigation links. | Comprehensive cross-linking, quick-jump navigation, and runnable Colab notebooks. |
Ufuncs are categorized into unary functions (operating on a single array, e.g., np.sin, np.sqrt) and binary functions (operating on two arrays, e.g., np.add, np.power):
import numpy as np
# Unary ufunc
a = np.array([0.0, np.pi/2, np.pi])
s = np.sin(a)
print("Sine values:
", s)
# Binary ufunc
x = np.array([1, 2, 3])
y = np.array([10, 20, 30])
p = np.add(x, y)
print("Binary add:
", p)
assert np.array_equal(p, np.array([11, 22, 33]))
Expected output
Sine values:
[0.00000000e+00 1.00000000e+00 1.22464680e-16]
Binary add:
[11 22 33]
Every ufunc supports powerful specialized methods like reduce(), accumulate(), and outer():
# Reduce: sum all elements
total = np.add.reduce([1, 2, 3, 4])
print("Add reduce:", total)
# Accumulate: running totals
running = np.add.accumulate([1, 2, 3, 4])
print("Add accumulate:", running)
# Outer: multiplication table matrix
grid = np.multiply.outer([1, 2, 3], [1, 2, 3])
print("Outer product grid:
", grid)
assert total == 10
assert np.array_equal(running, np.array([1, 3, 6, 10]))
Expected output
Add reduce: 10
Add accumulate: [ 1 3 6 10]
Outer product grid:
[[1 2 3]
[2 4 6]
[3 6 9]]
Ufuncs accept optional out parameters to write results directly into preallocated memory buffers and where boolean masks for conditional evaluation:
x = np.array([1, 4, 9, 16])
out_buf = np.empty_like(x, dtype=float)
np.sqrt(x, out=out_buf)
print("Preallocated out buffer result:", out_buf)
assert np.array_equal(out_buf, np.array([1., 2., 3., 4.]))
Expected output
Preallocated out buffer result: [1. 2. 3. 4.]
ValueError.out parameter is explicitly specified.Test unary/binary ufuncs, reduce, accumulate, outer methods, preallocated buffers, and run verification test suites in our interactive Google Colab companion notebook:
Launch the notebook directly in Google Colab to run live code cells or inspect the source repository on GitHub:
View on GitHubContinue exploring related math functions: Math & ufuncs, ceil(), floor(), and Broadcasting.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.