Using NumPy allows you to intuitively write everything from element-wise calculations (like vector addition and subtraction) to dot products and cross products, which are crucial in linear algebra.
Particular caution is required for “multiplication.” You need to be aware that Python’s * operator represents the “Hadamard product (element-wise multiplication)” and not the “dot product.”
Executable Sample Code
Here is an implementation example covering all patterns using vectors $\vec{a} = [1, 2, 3]$ and $\vec{b} = [4, 5, 6]$.
import numpy as np
def vector_operations_demo():
# Definition of vectors
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
scalar = 10
print(f"Vector a: {a}")
print(f"Vector b: {b}")
print("-" * 30)
# 1. Addition (Vector Addition)
# Add elements together: [1+4, 2+5, 3+6]
add = a + b
print(f"1. Addition (a + b): {add}")
# 2. Subtraction (Vector Subtraction)
# Subtract elements: [1-4, 2-5, 3-6]
sub = a - b
print(f"2. Subtraction (a - b): {sub}")
# 3. Scalar Multiplication
# Multiply all elements by a constant: [1*10, 2*10, 3*10]
mul_scalar = a * scalar
print(f"3. Scalar Mult (a * 10): {mul_scalar}")
# 4. Scalar Division
# Divide all elements by a constant
div_scalar = a / scalar
print(f"4. Scalar Div (a / 10): {div_scalar}")
# 5. Hadamard Product (Element-wise Multiplication)
# Multiply elements at the same position: [1*4, 2*5, 3*6]
# * Note: This is NOT matrix multiplication
hadamard_mul = a * b
print(f"5. Hadamard Product (a * b): {hadamard_mul}")
# 6. Element-wise Division
# Divide elements at the same position
hadamard_div = a / b
print(f"6. Element-wise Div (a / b): {hadamard_div}")
# 7. Dot Product
# Sum of the products of corresponding components: 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32
# Use np.dot(a, b) or the @ operator
dot_prod = np.dot(a, b)
dot_prod_op = a @ b
print(f"7. Dot Product (np.dot / @): {dot_prod}")
# 8. Cross Product
# Generate a vector orthogonal to two vectors (mainly used in 3D)
cross_prod = np.cross(a, b)
print(f"8. Cross Product (np.cross): {cross_prod}")
if __name__ == "__main__":
vector_operations_demo()
Summary of Operation Methods
The meanings of operators in Python (NumPy) are as follows:
| Operation Type | Mathematical Meaning | Python Operator / Function |
| Addition | $\vec{a} + \vec{b}$ | a + b |
| Subtraction | $\vec{a} – \vec{b}$ | a - b |
| Scalar Multiplication | $k \vec{a}$ | a * k |
| Hadamard Product | $[a_1 b_1, a_2 b_2, \dots]$ | a * b (Intuitive but be careful) |
| Dot Product | $\vec{a} \cdot \vec{b}$ | np.dot(a, b) or a @ b |
| Cross Product | $\vec{a} \times \vec{b}$ | np.cross(a, b) |
Supplement: About the @ Operator for Dot Products
In Python 3.5 and later, a dedicated operator @ was introduced to represent matrix multiplication and dot products.
Instead of writing np.dot(a, b), you can write a @ b, allowing for expressions closer to mathematical formulas.
