guass seidel with for loop given with tolerance=0 01 in javascript

Gauss-Seidel is an iterative method of solving a system of linear equations. Here's how to implement it with a for loop and a given tolerance of 0.01 in JavaScript:

index.tsx
function gaussSeidel(A, b) {
  const n = A.length;
  const x = new Array(n).fill(0);

  let iterations = 0;
  let error = Infinity;

  while (error > 0.01) {
    for (let i = 0; i < n; i++) {
      let sigma = 0;

      for (let j = 0; j < n; j++) {
        if (j !== i) {
          sigma += A[i][j] * x[j];
        }
      }

      const prev = x[i];
      x[i] = (b[i] - sigma) / A[i][i];
      error = Math.abs(x[i] - prev);
    }

    iterations++;
  }

  return { x, iterations };
}
488 chars
28 lines

This function takes in two arguments, A and b, which represents the system of linear equations in matrix form:

index.tsx
Ax = b
7 chars
2 lines

where A is a square matrix of coefficients, x is a column vector of unknowns, and b is a column vector of constants.

The function first initializes x to be an array of zeros, and then enters a loop that iteratively updates x until the error falls below the given tolerance of 0.01.

For each iteration, the function loops through each row of A, and for each element a[i][j], it checks if j != i. If it does, it adds a[i][j] * x[j] to sigma. It uses the sigma value to compute x[i] for that iteration, and updates the error accordingly.

The function continues iterating until the error falls below the tolerance, and returns the final x value and the number of iterations taken.

Note: The convergence of Gauss-Seidel can be sensitive to the order in which the equations are solved. This implementation solves the equations in the order they appear in the matrix, but there are other strategies that may converge faster.

gistlibby LogSnag