Skip to content

Commit

Permalink
gauss_jordan_elimination can swap rows
Browse files Browse the repository at this point in the history
fixes #1125
  • Loading branch information
christianp committed Oct 17, 2024
1 parent 4a6464a commit 0ffaa76
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 6 deletions.
18 changes: 16 additions & 2 deletions runtime/scripts/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -3396,9 +3396,23 @@ var matrixmath = Numbas.matrixmath = {
m = m.map(row => row.slice());
for(let i=0; i<rows; i++) {
// divide row i by m[i][i]
const f = m[i][i];
let f = m[i][i];
if(f==0) {
throw(new Numbas.Error("matrixmath.not invertible"));
let j = i+1;
for(;j<rows;j++) {
if(m[j][i] != 0) {
// swap rows j and i
let ri = m[i];
let rj = m[j];
m[i] = rj;
m[j] = ri;
f = m[i][i];
break;
}
}
if(j >= rows) {
throw(new Numbas.Error("matrixmath.not invertible"));
}
}
for(let x=0; x<columns; x++) {
m[i][x] /= f;
Expand Down
18 changes: 16 additions & 2 deletions tests/jme-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -5633,9 +5633,23 @@ var matrixmath = Numbas.matrixmath = {
m = m.map(row => row.slice());
for(let i=0; i<rows; i++) {
// divide row i by m[i][i]
const f = m[i][i];
let f = m[i][i];
if(f==0) {
throw(new Numbas.Error("matrixmath.not invertible"));
let j = i+1;
for(;j<rows;j++) {
if(m[j][i] != 0) {
// swap rows j and i
let ri = m[i];
let rj = m[j];
m[i] = rj;
m[j] = ri;
f = m[i][i];
break;
}
}
if(j >= rows) {
throw(new Numbas.Error("matrixmath.not invertible"));
}
}
for(let x=0; x<columns; x++) {
m[i][x] /= f;
Expand Down
4 changes: 4 additions & 0 deletions tests/jme/doc-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2549,6 +2549,10 @@ export default
{
"in": "gauss_jordan_elimination(matrix([1,2,3,5],[5,6,9,11],[6,9,12,15]))",
"out": "matrix([1,0,0,-2],[0,1,0,-1],[0,0,1,3])"
},
{
"in": "gauss_jordan_elimination(matrix([0,1],[1,0]))",
"out": "matrix([1,0],[0,1])"
}
]
},
Expand Down
18 changes: 16 additions & 2 deletions tests/numbas-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -5634,9 +5634,23 @@ var matrixmath = Numbas.matrixmath = {
m = m.map(row => row.slice());
for(let i=0; i<rows; i++) {
// divide row i by m[i][i]
const f = m[i][i];
let f = m[i][i];
if(f==0) {
throw(new Numbas.Error("matrixmath.not invertible"));
let j = i+1;
for(;j<rows;j++) {
if(m[j][i] != 0) {
// swap rows j and i
let ri = m[i];
let rj = m[j];
m[i] = rj;
m[j] = ri;
f = m[i][i];
break;
}
}
if(j >= rows) {
throw(new Numbas.Error("matrixmath.not invertible"));
}
}
for(let x=0; x<columns; x++) {
m[i][x] /= f;
Expand Down

0 comments on commit 0ffaa76

Please sign in to comment.