Skip to content

Commit 5a7fb87

Browse files
committed
fix: replace rounding with float tolerance
1 parent d9e7ffa commit 5a7fb87

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

Maths/RowEchelon.js

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
* // ]
2727
*/
2828

29+
const tolerance = 0.000001
30+
2931
const isMatrixValid = (matrix) => {
3032
let numRows = matrix.length
3133
let numCols = matrix[0].length
@@ -47,7 +49,7 @@ const isMatrixValid = (matrix) => {
4749
const checkNonZero = (currentRow, currentCol, matrix) => {
4850
let numRows = matrix.length
4951
for (let i = currentRow; i < numRows; i++) {
50-
if (matrix[i][currentCol] !== 0) {
52+
if (!isTolerant(0,matrix[i][currentCol], tolerance)) {
5153
return true
5254
}
5355
}
@@ -88,28 +90,22 @@ const subtractRow = (currentRow, fromRow, matrix) => {
8890
}
8991
}
9092

91-
const formatResult = (matrix) => {
92-
let precision = 5
93-
let numRows = matrix.length
94-
let numCols = matrix[0].length
95-
for (let i = 0; i < numRows; i++) {
96-
for (let j = 0; j < numCols; j++) {
97-
matrix[i][j] = parseFloat(matrix[i][j].toFixed(precision))
98-
}
99-
}
93+
const isTolerant = (a, b, tolerance) => {
94+
const absoluteDifference = Math.abs(a - b);
95+
return (absoluteDifference <= tolerance);
10096
}
10197

10298
const rowEchelon = (matrix) => {
103-
if (isMatrixValid(matrix) === false) {
104-
return 'Input is not a valid 2D matrix.'
99+
if (!isMatrixValid(matrix)) {
100+
throw new Error('Input is not a valid 2D matrix.')
105101
}
106102

107103
let numRows = matrix.length
108104
let numCols = matrix[0].length
109105
let result = matrix
110106

111107
for (let i = 0, j = 0; i < numRows && j < numCols; ) {
112-
if (checkNonZero(i, j, result) === false) {
108+
if (!checkNonZero(i, j, result)) {
113109
j++
114110
continue
115111
}
@@ -121,15 +117,14 @@ const rowEchelon = (matrix) => {
121117
//..............make bottom elements zero...............
122118
for (let x = i + 1; x < numRows; x++) {
123119
factor = result[x][j]
124-
if (factor === 0) {
120+
if (isTolerant(0,factor,tolerance)) {
125121
continue
126122
}
127123
scalarMultiplication(i, factor, result)
128124
subtractRow(i, x, result)
129125
factor = 1 / factor
130126
scalarMultiplication(i, factor, result)
131127
}
132-
formatResult(result)
133128
i++
134129
}
135130
return result

0 commit comments

Comments
 (0)