One of NumPy’s greatest features is “Universal Functions” (abbreviated as ufunc), which allow you to apply a function to all elements of an array at once.
Compared to calculating each item one by one using standard Python for loops, ufuncs process data overwhelmingly faster and make the code much simpler.
Executable Sample Code
The following code is an example of applying trigonometric functions (sin), square roots (sqrt), and exponential functions (exp) to an entire array.
import numpy as np
def ufunc_demo():
print("=== 1. Calculation of Trigonometric Functions (User Example) ===")
# Create an array from 0 to 9
x = np.arange(0, 10)
print(f"Original x: {x}")
# Calculate sin for all elements of the array
# While standard Python's math.sin(x) would raise an error, np.sin(x) works
y = np.sin(x)
print(f"np.sin(x): {y}")
print("\n=== 2. Other Mathematical Functions ===")
# Square Root
x2 = np.array([1, 4, 9, 16])
print(f"Original x2: {x2}")
print(f"np.sqrt(x2): {np.sqrt(x2)}") # [1. 2. 3. 4.]
# Exponential function (e^x)
print(f"np.exp(x2): {np.exp(x2)}")
print("\n=== 3. Operations Between Arrays (Arithmetic ufuncs) ===")
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
# Standard operators are processed as ufuncs (e.g., np.add) internally
print(f"a + b: {a + b}") # Same as np.add(a, b)
print(f"a * b: {a * b}") # Same as np.multiply(a, b)
print(f"a ** 2: {a ** 2}") # Same as np.power(a, 2)
if __name__ == "__main__":
ufunc_demo()
Explanation: Benefits of Universal Functions
1. Element-wise Calculation
Simply by writing np.sin(x), the sin calculation is performed for all of x[0], x[1], etc. This is called “element-wise calculation.”
2. High-Speed Processing (Vectorization)
While Python’s for loops are slow in processing speed, NumPy’s universal functions use loops optimized at the C language level. Therefore, when handling large amounts of data, they can achieve speeds several times to hundreds of times faster.
List of Major Universal Functions
| Function Name | Description | Substitute Operator |
| np.add(x, y) | Addition | x + y |
| np.subtract(x, y) | Subtraction | x - y |
| np.multiply(x, y) | Multiplication | x * y |
| np.divide(x, y) | Division | x / y |
| np.power(x, y) | Exponentiation | x ** y |
| np.sqrt(x) | Square Root | None |
| np.sin(x), np.cos(x) | Trigonometric Functions | None |
| np.log(x) | Natural Logarithm | None |
| np.abs(x) | Absolute Value | None |
