MATH 1152: SymPy implementation

Updated 2 min read

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.

  1. Creating a Matrix

    python
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    import 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)
  2. Calculating the Row Echelon Form (REF) and Reduced Row Echelon Form (RREF)

    python
     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)
  3. Calculating the Rank of a Matrix

    python
    1
    2
    3
    
    # The rank of the matrix is: 2
    rank = A.rank()
    print(f"The rank of the matrix is: {rank}")
  4. Finding the Null Space of a Matrix

    python
    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)
  5. Solving Systems of Linear Equations

    python
    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 ss or tt mentioned in the course.

  6. 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.

Write a letter

To Ziang Cui

About “MATH 1152: SymPy implementation”

Markdown & LaTeX supported: **bold**, $x^2$, $$…$$. Sent as source text.

0 / 3000

Your letter is private. Your words and any contact details you include will be sent to the author through the email service.