Lesson 10 of 18
Solving Ax = b
Solving a Linear System
A system of linear equations like:
can be written in matrix form as :
A = [[2, 1],
[1, 1]]
b = [5, 3]
Gaussian Elimination
We solve this by row reduction — transforming into upper triangular form, then back-substituting:
def solve(A, b):
n = len(b)
# Augment [A|b]
M = [A[i][:] + [b[i]] for i in range(n)]
# Forward elimination
for col in range(n):
for row in range(col+1, n):
factor = M[row][col] / M[col][col]
M[row] = [M[row][k] - factor*M[col][k] for k in range(n+1)]
# Back substitution
x = [0.0] * n
for i in range(n-1, -1, -1):
x[i] = (M[i][n] - sum(M[i][j]*x[j] for j in range(i+1, n))) / M[i][i]
return [round(xi, 1) for xi in x]
x = solve([[2,1],[1,1]], [5,3])
print(x) # [2.0, 1.0] → x=2, y=1
Why Gaussian Elimination?
- More numerically stable than computing the inverse
- Works directly on the augmented matrix
- Basis for LU decomposition
Verifying the Solution
Check: should equal :
Ax = [sum(A[i][j]*x[j] for j in range(len(x))) for i in range(len(A))]
print(all(abs(Ax[i] - b[i]) < 1e-9 for i in range(len(b)))) # True
Your Task
Implement solve(A, b) that returns the solution vector to , rounded to 1 decimal place.
Pyodide loading...
Loading...
Click "Run" to execute your code.