Last updated
Solving Systems of Linear Equations
A system of linear equations is a set of equations with multiple unknowns that must all be satisfied simultaneously. The most common methods for solving them are substitution, elimination (Gaussian elimination), and matrix methods (Cramer's rule, LU decomposition). For 2×2 and 3×3 systems, these can be done by hand. For larger systems, matrix methods are essential.
Gaussian Elimination
// Solve Ax = b using Gaussian elimination with partial pivoting
function gaussianElimination(A, b) {
const n = A.length;
// Augmented matrix [A|b]
const M = A.map((row, i) => [...row, b[i]]);
for (let col = 0; col < n; col++) {
// Find pivot
let maxRow = col;
for (let row = col+1; row < n; row++)
if (Math.abs(M[row][col]) > Math.abs(M[maxRow][col])) maxRow = row;
[M[col], M[maxRow]] = [M[maxRow], M[col]];
// Eliminate below
for (let row = col+1; row < n; row++) {
const factor = M[row][col] / M[col][col];
for (let j = col; j <= n; j++)
M[row][j] -= factor * M[col][j];
}
}
// Back substitution
const x = new Array(n).fill(0);
for (let i = n-1; i >= 0; i--) {
x[i] = M[i][n];
for (let j = i+1; j < n; j++) x[i] -= M[i][j] * x[j];
x[i] /= M[i][i];
}
return x;
}
// Solve: 2x + y = 5, x - y = 1
const A = [[2, 1], [1, -1]];
const b = [5, 1];
console.log(gaussianElimination(A, b)); // [2, 1]
Cramer's Rule (2×2)
For: ax + by = e
cx + dy = f
det(A) = ad - bc
x = (ed - bf) / det(A)
y = (af - ec) / det(A)
Example: 2x + y = 5, x - y = 1
det = (2)(-1) - (1)(1) = -3
x = (5×-1 - 1×1) / -3 = -6/-3 = 2
y = (2×1 - 5×1) / -3 = -3/-3 = 1