TExcelTAD
Home › Linear Algebra & Matrix Theory › Linear Algebra with SymPy and NumPy

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, 2\sqrt{2} 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:

python · try it yourself
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 or dtype=np.int64 if your integers could get large.

Shapes: rows × columns

A matrix with mm rows and nn columns has shape m×nm \times n. A vector is usually written as a column (n×1n \times 1). NumPy also has plain 1-D arrays of shape (n,), which act as row or column depending on where you put them.

python · try it yourself
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 2×32 \times 3 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 Ax=bA\mathbf{x} = \mathbf{b}

A system of linear equations is written compactly as Ax=bA\mathbf{x} = \mathbf{b}. Both libraries can solve a square system with a unique solution:

python · try it yourself
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 (1,−2,3)(1, -2, 3). 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:

python · try it yourself
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: x1+2x2=3x_1 + 2x_2 = 3 and x3=−1x_3 = -1, with x2x_2 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 than print(R) for anything bigger than 2×22 \times 2.

Exercises

Exercise 1: Shapes

What is the shape of the product of a 4×24 \times 2 matrix and a 2×52 \times 5 matrix? Can you multiply a 2×52 \times 5 matrix by a 4×24 \times 2 matrix (in that order)?

Answer

4×54 \times 5. No: 2×52 \times 5 times 4×24 \times 2 is undefined.

Solution
(4×2)(2×5): inner sizes 2=2✓, result 4×5(2×5)(4×2): inner sizes 5≠4  ×, undefined\begin{aligned} &(4 \times 2)(2 \times 5)\text{: inner sizes } 2 = 2 \checkmark, \text{ result } 4 \times 5 \\ &(2 \times 5)(4 \times 2)\text{: inner sizes } 5 \ne 4 \;\boldsymbol{\times}, \text{ undefined} \end{aligned}

Exercise 2: Exact versus float

Compute the inverse of [3152]\begin{bmatrix} 3 & 1 \\ 5 & 2 \end{bmatrix} by hand (use inverse of [abcd]=1ad−bc⋅[d−b−ca]\text{inverse of } \begin{bmatrix} a & b \\ c & d \end{bmatrix} = \frac{1}{ad - bc} \cdot \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}) and check it in SymPy.

Answer

[2−1−53]\begin{bmatrix} 2 & -1 \\ -5 & 3 \end{bmatrix}.

Solution
ad−bc=3⋅2−1⋅5=1inverse=11⋅[2−1−53]\begin{aligned} ad - bc &= 3 \cdot 2 - 1 \cdot 5 = 1 \\ \text{inverse} &= \frac{1}{1} \cdot \begin{bmatrix} 2 & -1 \\ -5 & 3 \end{bmatrix} \end{aligned}
python · try it yourself
from sympy import Matrix
print(Matrix([[3, 1], [5, 2]]).inv())
Matrix([[2, -1], [-5, 3]])

Exercise 3: The * trap (code)

For A=[1234]A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} in NumPy, compute A * A and A @ A. Which one is the matrix product?

Answer

A * A = [14916]\begin{bmatrix} 1 & 4 \\ 9 & 16 \end{bmatrix} (element-wise); A @ A = [7101522]\begin{bmatrix} 7 & 10 \\ 15 & 22 \end{bmatrix} is the matrix product.

Solution

Entry (1,1)(1,1) of the matrix product is row 1⋅column 1=1⋅1+2⋅3=7\text{row } 1 \cdot \text{column } 1 = 1 \cdot 1 + 2 \cdot 3 = 7.

python · try it yourself
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 [A∣b][A \mid \mathbf{b}] returns rows [1,0,5][1, 0, 5], [0,1,−2][0, 1, -2]. What is the solution?

Answer

x1=5x_1 = 5, x2=−2x_2 = -2.

Solution

The last column is the right-hand side. Row 1 says 1⋅x1+0⋅x2=51 \cdot x_1 + 0 \cdot x_2 = 5 and row 2 says x2=−2x_2 = -2.

Test yourself

In NumPy, what does A * B compute for two 3×33 \times 3 arrays?

  1. The matrix product
  2. The element-wise product
  3. The dot product of the first rows
  4. An error

What does SymPy's rref() return?

  1. Only the determinant
  2. The reduced row echelon form and the tuple of pivot column indices
  3. A float approximation of the solution
  4. The inverse matrix

np.linalg.solve returns 1.4e-16 where SymPy returns 0. What is the best interpretation?

  1. NumPy found a different solution
  2. The system has no solution
  3. It is rounding noise; the value is 0 up to floating-point error
  4. SymPy is wrong