MATH 1152: SymPy implementation
While studying MATH 1152 (Linear Algebra I Honors) at Carleton University, I started exploring how Python could help me understand and verify linear algebra concepts.
One useful library is SymPy, a Python library for symbolic mathematics. Unlike NumPy and SciPy, which primarily focus on numerical computation, SymPy can perform exact calculations using fractions and symbolic expressions.
-
Creating a Matrix
1 2 3 4 5 6 7 8 9 10 11 12import sympy as sp A = sp.Matrix([ [1, 2, 3], [2, 4, 6], [1, 1, 1] ]) # The matrix A is: # Matrix([[1, 2, 3], [2, 4, 6], [1, 1, 1]]) print("The matrix A is:") print(A) -
Calculating the Row Echelon Form (REF) and Reduced Row Echelon Form (RREF)
1 2 3 4 5 6 7 8 9 10# The row echelon form of the matrix is: # Matrix([[1, 2, 3], [0, -1, -2], [0, 0, 0]]) ref = A.echelon_form() print("The row echelon form of the matrix is:") print(ref) rref = A.rref() # The reduced row echelon form of the matrix is: # (Matrix([[1, 0, -1],[0, 1, 2],[0, 0, 0]]), (0, 1)) print("The reduced row echelon form of the matrix is:") print(rref) -
Calculating the Rank of a Matrix
1 2 3# The rank of the matrix is: 2 rank = A.rank() print(f"The rank of the matrix is: {rank}") -
Finding the Null Space of a Matrix
1 2 3 4 5 6# The null space of the matrix is: # Matrix([[1], [-2], [1]]) null_space = A.nullspace() print("The null space of the matrix is:") for vector in null_space: print(vector) -
Solving Systems of Linear Equations
1 2 3 4 5 6 7# Solving the system of equations Ax = b b = sp.Matrix([4, 8, 2]) solution = A.solve(b) # The solution to the system of equations Ax = b is: # {(tau0, 2 - 2*tau0, tau0)} print("The solution to the system of equations Ax = b is:") print(solution)The tau0 represents a free variable, like or mentioned in the course.
-
Why SymPy Instead of NumPy and SciPy?
NumPy and SciPy are essential for numerical linear algebra and machine learning. However, SymPy is particularly convenient when studying mathematical definitions and working with exact values.
A note to the author
Feel free to drop me a note.