Monday, July 22, 2024

Python linear algebra

Every algebra 1 student should learn about solving a system of 2 equations and 2 unknowns. Then they will learn about 3 by 3... then gosh n by n. There is gotta be easier way to do this than combining equations, well yes there is, enter linear algebra. But solving a linear system of equation is still hard to do by hand, painful to punch it on your calculator too. Enter computer programming! Python can effortless do this with the Numpy library. Programming this from scratch is not a very pleasant programming task.
import numpy as np
 
"""
Simple little 2x2 system example:
 x + 2y = 1
 3x + 5y = 2
 
 This can be written as matrix form [A][x] = [B]:
 
 [1 2][x] =  [1]
 [3 5][y]    [2]
 
 
 So the solution is inv(A)B
 
 Inverse matrix is painful to do by hand, but numpy can do it easy,
 It even has a solve method
 """
 
A = np.array([[1, 2], 
              [3, 5]])
B = np.array([1, 2])

Ainv = np.linalg.inv(A)
solution = np.matmul(Ainv,B)
print("Solution by multiply inverse: ")
print(solution)

solution2 = np.linalg.solve(A, B)
print("Solution by linalg solve: ")
print(solution2)

Output:
Solution by multiply inverse matrix and right hand side: 
[-1.  1.]
or by linalg solve: 
[-1.  1.]
That means x=-1, y =1.

No comments: