NumPy provides concise operations for vector and matrix calculations. This section introduces the tools; later chapters develop their mathematical meaning.
import numpy as npElementwise multiplication versus matrix multiplication¶
Consider two matrices with the same shape:
A = np.array([
[1.0, 2.0],
[3.0, 4.0],
])
B = np.array([
[2.0, 0.0],
[1.0, 2.0],
])The * operator multiplies corresponding entries:
A * Barray([[2., 0.],
[3., 8.]])The @ operator performs matrix multiplication:
A @ Barray([[ 4., 4.],
[10., 8.]])These results differ because matrix multiplication forms row-by-column dot products. For to be defined, the number of columns of must equal the number of rows of .
A.shape, B.shape, (A @ B).shape((2, 2), (2, 2), (2, 2))Matrix-vector products¶
A matrix-vector product combines the columns of a matrix using the entries of the vector:
x = np.array([5.0, -1.0])
b = A @ x
barray([ 3., 11.])Check the calculation manually:
Dot products and norms¶
For one-dimensional arrays, @ computes the dot product:
u = np.array([1.0, 2.0, -1.0])
v = np.array([3.0, 0.0, 4.0])
u @ vnp.float64(-1.0)The Euclidean norm measures vector length:
np.linalg.norm(u)np.float64(2.449489742783178)These operations return in the geometry chapter with definitions and applications.
Solving a linear system¶
The system
can be written as . Define the coefficient matrix and right-hand side:
A = np.array([
[2.0, 1.0],
[1.0, -1.0],
])
b = np.array([7.0, 2.0])Use np.linalg.solve(A, b) for a square system with a unique solution:
x = np.linalg.solve(A, b)
xarray([3., 1.])Never stop at the returned array. Check the residual :
residual = A @ x - b
residual, np.linalg.norm(residual)(array([0., 0.]), np.float64(0.0))The residual may contain tiny values such as 1e-16 because computers approximate most real-number arithmetic.
Comparing floating-point results¶
Avoid exact equality for computed floating-point arrays:
0.1 + 0.2 == 0.3FalseUse a tolerance-based comparison:
np.isclose(0.1 + 0.2, 0.3), np.allclose(A @ x, b)(np.True_, True)Inverses¶
For an invertible matrix, NumPy can compute :
A_inverse = np.linalg.inv(A)
A_inversearray([[ 0.33333333, 0.33333333],
[ 0.33333333, -0.66666667]])The product is approximately the identity matrix:
A @ A_inversearray([[1.00000000e+00, 0.00000000e+00],
[5.55111512e-17, 1.00000000e+00]])The formula is mathematically valid:
A_inverse @ barray([3., 1.])However, when the goal is to solve , prefer:
x = np.linalg.solve(A, b)Computing an inverse performs unnecessary work and can introduce more numerical error. Use inv when the inverse itself is the object being studied, not as the default system-solving method.
Singular and nearly singular systems¶
A singular matrix does not have an inverse. solve reports this rather than inventing a unique solution:
singular = np.array([
[1.0, 2.0],
[2.0, 4.0],
])Running np.linalg.solve(singular, np.array([3.0, 6.0])) raises LinAlgError: Singular matrix.
Some invertible matrices are still numerically difficult. The condition number is one warning sign:
np.linalg.cond(A), np.linalg.cond(singular)(np.float64(1.7675918792439989), np.float64(4.804857307547117e+16))We will interpret singularity and conditioning after developing elimination, invertibility, and vector spaces.
A reliable computational workflow¶
When using a linear algebra routine:
state the mathematical problem;
construct arrays with intentional shapes;
inspect
.shape;call the appropriate routine;
verify the result with a residual or mathematical property; and
interpret the result in the problem’s context.
Practice¶
Exercise 1: matrix-vector product¶
Compute for
Predict the output shape before running the calculation.
Solution
M = np.array([
[1.0, -2.0, 0.0],
[3.0, 1.0, 4.0],
])
v = np.array([2.0, -1.0, 3.0])
product = M @ v
product, product.shape(array([ 4., 17.]), (2,))The result is [4., 17.] with shape (2,).
Exercise 2: solve and verify¶
Solve the system
Verify the answer with np.allclose.
Solution
A = np.array([
[3.0, -2.0],
[5.0, 1.0],
])
b = np.array([4.0, 11.0])
x = np.linalg.solve(A, b)
x, np.allclose(A @ x, b)(array([2., 1.]), True)The solution is and .
Exercise 3: diagnose the operation¶
Explain why A * x is not a replacement for A @ x when A is a matrix and x is a vector.
Solution
A * x uses broadcasting to multiply each row’s entries elementwise by x; its result has the same matrix shape as A. A @ x forms one dot product per row and returns a vector. The operations answer different questions.