← back

Solve Linear Equations using Jacobi Method

#11 · Linear Algebra · Medium

⊣ Solve on deep-ml.com

Problem

Solve a system of linear equations Ax = b using the Jacobi iterative method. Given matrix A, vector b, and an initial guess, iterate until convergence or a maximum number of iterations.

Solution

1
2
3
4
5
6
7
8
9
10
def solve_jacobi(A: list[list[float]], b: list[float], n: int) -> list[float]:
    size = len(b)
    x = [0.0] * size
    for _ in range(n):
        x_new = [0.0] * size
        for i in range(size):
            sigma = sum(A[i][j] * x[j] for j in range(size) if j != i)
            x_new[i] = (b[i] - sigma) / A[i][i]
        x = x_new
    return [round(v, 4) for v in x]

Explanation

  1. Start with an initial guess x = [0, 0, ..., 0].
  2. For each iteration, compute each new x_i using the formula: x_i = (b_i - sum(A_ij * x_j for j != i)) / A_ii.
  3. The key property of Jacobi is that all updates use values from the previous iteration (unlike Gauss-Seidel which uses the latest values).
  4. Repeat for n iterations and return the rounded result.

Complexity

  • Time: O(n * m^2) where n is the number of iterations and m is the system size
  • Space: O(m) for the solution vector