582 words
3 minutes
NumPy Math Operations

III. NumPy Math Operations (数学运算)
NumPy math functions are element-wise (逐元素) — they operate on each element independently and return a new array of the same shape. They are implemented in C, making them far faster than Python loops.
1. Basic Arithmetic (四则运算)
Core idea: Operator symbols (+, -, *, /) and their functional equivalents work element-by-element.
import numpy as np
a = np.array([10, 20, 30])b = np.array([1, 2, 3])
np.add(a, b) # [11 22 33] → same as a + bnp.subtract(a, b) # [ 9 18 27] → same as a - bnp.multiply(a, b) # [10 40 90] → same as a * bnp.divide(a, b) # [10. 10. 10.] → same as a / bNote: Broadcasting (广播机制) allows operations between arrays of different shapes. E.g.,
a + 5 adds 5 to every element.2. power() — Exponentiation (幂运算)
Core idea: Raise each element to a given power.
a = np.array([2, 3, 4])
np.power(a, 3) # [ 8 27 64] → a³a ** 2 # [ 4 9 16] → shorthand
np.sqrt(a) # [1.41 1.73 2.0] → square root (平方根)3. exp() / log() — Exponential & Logarithm (指数与对数)
Core idea: Apply the natural exponential or logarithm element-wise.
a = np.array([0, 1, 2])
np.exp(a) # [1. 2.718 7.389] → e^xnp.log(a + 1) # [0. 0.693 1.099] → ln(x)np.log2(np.array([1, 2, 8])) # [0. 1. 3.]np.log10(np.array([1, 10, 100])) # [0. 1. 2.]Note: log(0) returns -inf and raises a warning — always check for zero values before applying log.
4. sin() / cos() / tan() — Trigonometry (三角函数)
Core idea: Input angles must be in radians (弧度), not degrees.
angles = np.array([0, np.pi/6, np.pi/4, np.pi/2])
np.sin(angles) # [0. 0.5 0.707 1. ]np.cos(angles) # [1. 0.866 0.707 0. ]np.tan(angles) # [0. 0.577 1. inf ]
# Convert degrees to radians (角度转弧度)deg = np.array([0, 30, 45, 90])np.sin(np.deg2rad(deg)) # same result5. Rounding Functions (取整函数)
Core idea: Control how floating-point values are rounded.
a = np.array([1.4, 1.5, 2.6, -1.7])
np.round(a) # [ 1. 2. 3. -2.] → nearest evennp.floor(a) # [ 1. 1. 2. -2.] → round down (向下取整)np.ceil(a) # [ 2. 2. 3. -1.] → round up (向上取整)np.trunc(a) # [ 1. 1. 2. -1.] → truncate toward zero (截断)6. Absolute Value & Sign (绝对值与符号)
a = np.array([-3, -1, 0, 2, 5])
np.abs(a) # [3 1 0 2 5]np.sign(a) # [-1 -1 0 1 1]7. Quick Comparison Table
| Function (函数) | Operation | Example Input → Output |
|---|---|---|
add / subtract | ± element-wise | [1,2] + [3,4] → [4,6] |
multiply / divide | ×÷ element-wise | [2,4] * [3,2] → [6,8] |
power(a, n) | [2,3]^2 → [4,9] | |
sqrt(a) | [4,9] → [2,3] | |
exp(a) | [0,1] → [1, 2.718] | |
log(a) | [1, e] → [0, 1] | |
sin / cos / tan | Trig (radians) | [0, π/2] → [0, 1] |
💡 One-line Takeaway
All NumPy math functions are element-wise and support broadcasting — they are always faster than Python loops; just watch out for
All NumPy math functions are element-wise and support broadcasting — they are always faster than Python loops; just watch out for
log(0) and tan(π/2) edge cases. NumPy Math Operations
https://lxy-alexander.github.io/blog/posts/numpy/api/03numpy-math-operations/