NumPy ufuncs
🔢 NumPy Universal Functions (ufuncs)
Universal functions (ufuncs) in NumPy are vectorized functions that operate element-wise on arrays.
They are highly optimized, fast, and avoid explicit Python loops.
1. Types of ufuncs
Arithmetic ufuncs
Comparison ufuncs
Logical ufuncs
Trigonometric ufuncs
Exponential and logarithmic ufuncs
Statistical ufuncs (like sum, mean, etc.)
2. Arithmetic ufuncs
| Function | Description |
|---|---|
np.add(x, y) | Element-wise addition |
np.subtract(x, y) | Element-wise subtraction |
np.multiply(x, y) | Element-wise multiplication |
np.divide(x, y) | Element-wise division |
np.power(x, y) | Element-wise power |
np.mod(x, y) | Element-wise modulus |
3. Comparison ufuncs
| Function | Description |
|---|---|
np.equal(x, y) | Element-wise equality |
np.not_equal(x, y) | Element-wise inequality |
np.greater(x, y) | Element-wise greater than |
np.less(x, y) | Element-wise less than |
np.greater_equal(x, y) | Element-wise ≥ |
np.less_equal(x, y) | Element-wise ≤ |
4. Logical ufuncs
| Function | Description |
|---|---|
np.logical_and(x, y) | Element-wise AND |
np.logical_or(x, y) | Element-wise OR |
np.logical_not(x) | Element-wise NOT |
np.logical_xor(x, y) | Element-wise XOR |
5. Trigonometric ufuncs
| Function | Description |
|---|---|
np.sin(x) | Sine |
np.cos(x) | Cosine |
np.tan(x) | Tangent |
np.arcsin(x) | Inverse sine |
np.arccos(x) | Inverse cosine |
np.arctan(x) | Inverse tangent |
6. Exponential & Logarithmic ufuncs
| Function | Description |
|---|---|
np.exp(x) | e^x |
np.exp2(x) | 2^x |
np.log(x) | Natural logarithm |
np.log2(x) | Base-2 logarithm |
np.log10(x) | Base-10 logarithm |
np.sqrt(x) | Square root |
np.square(x) | Element-wise square |
7. Statistical ufuncs
| Function | Description |
|---|---|
np.sum(x) | Sum of elements |
np.mean(x) | Mean |
np.std(x) | Standard deviation |
np.var(x) | Variance |
np.min(x) | Minimum |
np.max(x) | Maximum |
8. Using ufunc with Scalars
ufuncs work with arrays or scalars seamlessly
🧠 Summary
ufuncs = element-wise, fast operations
Covers arithmetic, comparison, logical, trigonometric, exponential, statistical functions
Avoids Python loops → vectorized computations
🎯 Practice Exercises
Create an array
[1,2,3,4,5]and compute square, square root, exp, and log using ufuncs.Compare two arrays element-wise for greater, equal, and less.
Use logical ufuncs to find elements >2 AND <5 in an array.
