gauss seidel for loop in javascript

Here is a sample code to solve a system of equations using Gauss-Seidel method using for loop in JavaScript:

index.tsx
function gaussSeidel(A, x, b, tolerance) {
  const n = A.length;
  let iter = 0;
  let norm = 2 * tolerance;
  while (norm > tolerance && iter < 1000) {
    norm = 0;
    for (let i = 0; i < n; i++) {
      let sigma = 0;
      for (let j = 0; j < n; j++) {
        if (i !== j) {
          sigma += A[i][j] * x[j];
        }
      }
      const temp = (b[i] - sigma) / A[i][i];
      norm += Math.abs(x[i] - temp);
      x[i] = temp;
    }
    iter++;
  }
  return x;
}

// Sample usage
const A = [[4, -1, 0], [1, 3, -1], [1, 0, 2]];
const b = [3, 2, 1];
const x = [0, 0, 0];
const tolerance = 0.0001;
const solution = gaussSeidel(A, x, b, tolerance);
console.log(solution); // [ 0.5000359209910011, 0.9999876328403659, 0.49997207984563924 ]
743 chars
30 lines

In this code, A represents the coefficient matrix of the system, x represents the initial guess for the solution, and b represents the constant vector on the right-hand side of the equations. tolerance is the maximum tolerance allowed for the difference between the newly computed solution and the previous solution. The method returns the solution array after sufficient iteration.

related categories

gistlibby LogSnag