Last active
May 22, 2020 15:39
-
-
Save danielherrerohernando/f4849de8cdda426d2d85ba423c783cda to your computer and use it in GitHub Desktop.
Gauss-Jordan method implementation for solving systems of equations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const buildAugmentedMatrix = (leftMatrix, rightMatrix) => leftMatrix.map((row,i)=>row.concat(rightMatrix[i])); | |
const triangularize = (augmentedMatrix) => { | |
const n = augmentedMatrix.length; | |
for (let i=0; i<n-1; i++) { | |
for (let j=i+1; j<n; j++) { | |
const c = augmentedMatrix[j][i]/augmentedMatrix[i][i]; | |
for (let k=i+1; k<n+1; k++) { | |
augmentedMatrix[j][k] = augmentedMatrix[j][k] - c*augmentedMatrix[i][k]; | |
} | |
} | |
} | |
return augmentedMatrix; | |
}; | |
const backSubstitute = (augmentedMatrix) => { | |
const x = []; | |
const n = augmentedMatrix.length; | |
for (let i=n-1; i>=0; i--) { | |
const alreadySolvedTerms = x.reduce((acc,val,idx) => acc + val*augmentedMatrix[i][n-1-idx], 0); | |
x.push((augmentedMatrix[i][n] - alreadySolvedTerms) / augmentedMatrix[i][i]); | |
} | |
return x.reverse(); | |
}; | |
const solve = (leftMatrix, rightMatrix) => backSubstitute(triangularize(buildAugmentedMatrix(leftMatrix, rightMatrix))); | |
module.exports = { | |
solve | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment