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

  1. Arithmetic ufuncs

  2. Comparison ufuncs

  3. Logical ufuncs

  4. Trigonometric ufuncs

  5. Exponential and logarithmic ufuncs

  6. Statistical ufuncs (like sum, mean, etc.)


 2. Arithmetic ufuncs

FunctionDescription
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

FunctionDescription
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

FunctionDescription
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

FunctionDescription
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

FunctionDescription
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

FunctionDescription
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

  1. Create an array [1,2,3,4,5] and compute square, square root, exp, and log using ufuncs.

  2. Compare two arrays element-wise for greater, equal, and less.

  3. Use logical ufuncs to find elements >2 AND <5 in an array.

You may also like...