Linear Algebra with SymPy and NumPy
Two Python libraries do all the computing in this course: SymPy for exact answers with fractions and symbols, and NumPy for fast floating-point arrays. This lesson shows how to build vectors and matrices in each, how shapes work, and how to solve a system and row-reduce a matrix.
Two kinds of arithmetic
SymPy Matrix |
NumPy ndarray |
|
|---|---|---|
| Numbers | exact integers, fractions (Rational), symbols, |
floating point (float64) or fixed-size integers |
1/3 is stored as |
1/3 |
0.3333333333333333 |
| Speed | slow, fine for small matrices | very fast, millions of entries |
| Typical use | learning, proofs, row reduction, exact eigenvalues | graphics, ML, data, simulation |
| Matrix product | A * B or A @ B |
A @ B (A * B is element-wise!) |
Here is the same matrix in both worlds:
from sympy import Matrix, Rational
import numpy as np
S = Matrix([[1, 2], [3, 4]])
N = np.array([[1, 2], [3, 4]])
print("SymPy inverse:", S.inv())
print("NumPy inverse:")
print(np.linalg.inv(N))
print("exact 1/3 + 1/6 =", Rational(1, 3) + Rational(1, 6))
print("float 1/3 + 1/6 =", 1/3 + 1/6)SymPy inverse: Matrix([[-2, 1], [3/2, -1/2]])
NumPy inverse:
[[-2. 1. ]
[ 1.5 -0.5]]
exact 1/3 + 1/6 = 1/2
float 1/3 + 1/6 = 0.5
SymPy prints a matrix as Matrix([[row 1], [row 2]]): a list of rows. NumPy prints a grid. Here the float result happens to round to exactly 0.5; with other numbers it does not (try 0.1 + 0.2).
Note: In the browser, Python runs in Pyodide, where NumPy's default integer type is 32-bit (
int32). Use floats ordtype=np.int64if your integers could get large.
Shapes: rows × columns
A matrix with rows and columns has shape . A vector is usually written as a column (). NumPy also has plain 1-D arrays of shape (n,), which act as row or column depending on where you put them.
from sympy import Matrix
import numpy as np
A = Matrix([[1, 0, 2], [0, 3, 1]]) # 2 x 3
v = Matrix([1, 1, 1]) # a column vector, 3 x 1
print("A.shape =", A.shape, " v.shape =", v.shape)
print("A*v =", list(A * v))
An = np.array([[1, 0, 2], [0, 3, 1]])
vn = np.array([1, 1, 1])
print("numpy shapes:", An.shape, vn.shape, "->", (An @ vn).shape)
print("A @ v =", An @ vn)
print("element-wise A * A:")
print(An * An)A.shape = (2, 3) v.shape = (3, 1)
A*v = [3, 4]
numpy shapes: (2, 3) (3,) -> (2,)
A @ v = [3 4]
element-wise A * A:
[[1 0 4]
[0 9 1]]
The product of a matrix with a 3-vector is a 2-vector: the inner sizes (3 and 3) must match, and the outer sizes give the result's shape. You will see why in Matrix Multiplication.
Solving
A system of linear equations is written compactly as . Both libraries can solve a square system with a unique solution:
from sympy import Matrix
import numpy as np
# 2x + y - z = -3
# x - 2y + 3z = 14
# 3x + y + 2z = 7
A = [[2, 1, -1], [1, -2, 3], [3, 1, 2]]
b = [-3, 14, 7]
print("SymPy:", list(Matrix(A).solve(Matrix(b))))
x = np.linalg.solve(np.array(A, dtype=float), np.array(b, dtype=float))
print("NumPy:", x)
print("NumPy, all digits:", x.tolist())
print("close to exact?", np.allclose(x, [1, -2, 3]))SymPy: [1, -2, 3]
NumPy: [ 1. -2. 3.]
NumPy, all digits: [0.9999999999999996, -1.9999999999999996, 3.0000000000000004]
close to exact? True
SymPy returns exactly . NumPy prints the same numbers, but the full digits show tiny errors in the 16th decimal place: floating-point rounding during elimination. Never test NumPy results with ==; use np.allclose (or np.round).
Row reduction with rref()
The central algorithm of the first chapter is row reduction to the reduced row echelon form. SymPy's rref() returns the reduced matrix and the indices of the pivot columns:
from sympy import Matrix
aug = Matrix([[1, 2, -1, 4],
[2, 4, 1, 5],
[1, 2, 2, 1]]) # augmented matrix [A | b]
R, pivots = aug.rref()
for row in R.tolist():
print(row)
print("pivot columns:", pivots)[1, 2, 0, 3]
[0, 0, 1, -1]
[0, 0, 0, 0]
pivot columns: (0, 2)
Read it back as equations: and , with free. So the system has infinitely many solutions. The lessons on Gaussian elimination and Gauss-Jordan elimination show how this works by hand. NumPy has no rref, because row reduction with floats is numerically fragile; numeric code uses factorizations (LU, QR) instead.
Tip: Printing
R.tolist()row by row is easier to read thanprint(R)for anything bigger than .
Exercises
Exercise 1: Shapes
What is the shape of the product of a matrix and a matrix? Can you multiply a matrix by a matrix (in that order)?
Answer
. No: times is undefined.
Solution
Exercise 2: Exact versus float
Compute the inverse of by hand (use ) and check it in SymPy.
Answer
.
Solution
from sympy import Matrix
print(Matrix([[3, 1], [5, 2]]).inv())Matrix([[2, -1], [-5, 3]])
Exercise 3: The * trap (code)
For in NumPy, compute A * A and A @ A. Which one is the matrix product?
Answer
A * A = (element-wise); A @ A = is the matrix product.
Solution
Entry of the matrix product is .
import numpy as np
A = np.array([[1, 2], [3, 4]])
print(A * A)
print(A @ A)[[ 1 4]
[ 9 16]]
[[ 7 10]
[15 22]]
Exercise 4: Read an rref
rref() of an augmented matrix returns rows , . What is the solution?
Answer
, .
Solution
The last column is the right-hand side. Row 1 says and row 2 says .
Test yourself
In NumPy, what does A * B compute for two arrays?
- The matrix product
- The element-wise product
- The dot product of the first rows
- An error
What does SymPy's rref() return?
- Only the determinant
- The reduced row echelon form and the tuple of pivot column indices
- A float approximation of the solution
- The inverse matrix
np.linalg.solve returns 1.4e-16 where SymPy returns 0. What is the best interpretation?
- NumPy found a different solution
- The system has no solution
- It is rounding noise; the value is 0 up to floating-point error
- SymPy is wrong