Topics in this subject
NumPy 1 min read Updated 4 Aug 2026

8. Mathematical Operations

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

Element-wise arithmetic#

a = np.array([1, 2, 3]); b = np.array([4, 5, 6])
a + b      # [5 7 9]
a * b      # [ 4 10 18]   (element-wise, NOT matrix mult)
a ** 2     # [1 4 9]
b % a      # [0 1 0]

⚠️ Common Mistake: * is element-wise. For matrix multiplication use @ or np.matmul.

Universal functions (ufuncs)#

Function Purpose
np.sqrt, np.exp, np.log, np.log2, np.log10 math transforms
np.power(a, b) element-wise power
np.mod(a, b) modulo
np.abs / np.absolute absolute value
np.round, np.floor, np.ceil, np.trunc rounding
np.clip(a, lo, hi) limit values to a range
np.sign -1, 0, +1
np.sin, np.cos, np.tan trig
x = np.array([-1.7, 0.5, 2.3, 5.9])
np.clip(x, 0, 3)     # [0.  0.5 2.3 3. ]
np.round(x)          # [-2.  0.  2.  6.]
np.floor(x)          # [-2.  0.  2.  5.]
np.ceil(x)           # [-1.  1.  3.  6.]
np.abs(x)            # [1.7 0.5 2.3 5.9]

💡 Tip: ufuncs accept an out= parameter to write results into an existing array — avoids allocating memory in tight loops.

🚀 Best Practice: Prefer np.log1p(x) over np.log(1+x) and np.expm1(x) over np.exp(x)-1 for numerical stability with small x.