🔢 NumPy
Math Functions
NumPy provides optimized mathematical functions (ufuncs) for trigonometry, logarithms, rounding, and statistics. These operate element-wise on arrays and are orders of magnitude faster than Python loops.
● Intermediate
📖 Based on: numpy-user manual
📋 Table of Contents
1 · Universal Functions
| Category | Functions |
|---|---|
| Trigonometric | np.sin, cos, tan, arcsin, arccos, arctan |
| Exponential | np.exp, exp2, log, log2, log10 |
| Power | np.sqrt, square, power, cbrt |
| Arithmetic | np.add, subtract, multiply, divide, mod |
| Absolute | np.abs, fabs, sign |
Python
import numpy as np x = np.array([0, np.pi/4, np.pi/2, np.pi]) print(np.sin(x)) # [0, 0.707, 1, 0] print(np.exp([0,1,2])) # [1, 2.718, 7.389] print(np.log([1, np.e, np.e**2])) # [0, 1, 2]
▶ Output
[0. 0.707 1. 0.][1. 2.718 7.389]
[0. 1. 2.]
2 · Statistical Functions
Python
data = np.array([14,18,11,13,16,15,12,17]) print(f"Mean: {np.mean(data):.2f}") # 14.50 print(f"Median: {np.median(data):.2f}") # 14.50 print(f"Std: {np.std(data):.2f}") # 2.29 print(f"Var: {np.var(data):.2f}") # 5.25 print(f"25th %: {np.percentile(data, 25)}") # 12.25 print(f"Corr: {np.corrcoef([1,2,3],[2,4,6])}")
▶ Output
Mean: 14.50Median: 14.50
Std: 2.29
Var: 5.25
3 · Rounding & Comparison
Python
x = np.array([1.23, 2.78, 3.45]) print(np.round(x, 1)) # [1.2, 2.8, 3.5] print(np.floor(x)) # [1., 2., 3.] print(np.ceil(x)) # [2., 3., 4.] print(np.clip(x, 2, 3)) # [2., 2.78, 3.] (clamp) # Float comparison (avoid == for floats) a = np.array([0.1+0.2]) print(np.isclose(a, 0.3)) # [True]
▶ Output
[1.2 2.8 3.5] · [1. 2. 3.] · [2. 3. 4.] · [True]