26
26
* // ]
27
27
*/
28
28
29
+ const tolerance = 0.000001
30
+
29
31
const isMatrixValid = ( matrix ) => {
30
32
let numRows = matrix . length
31
33
let numCols = matrix [ 0 ] . length
@@ -47,7 +49,7 @@ const isMatrixValid = (matrix) => {
47
49
const checkNonZero = ( currentRow , currentCol , matrix ) => {
48
50
let numRows = matrix . length
49
51
for ( let i = currentRow ; i < numRows ; i ++ ) {
50
- if ( matrix [ i ] [ currentCol ] !== 0 ) {
52
+ if ( ! isTolerant ( 0 , matrix [ i ] [ currentCol ] , tolerance ) ) {
51
53
return true
52
54
}
53
55
}
@@ -88,28 +90,22 @@ const subtractRow = (currentRow, fromRow, matrix) => {
88
90
}
89
91
}
90
92
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 ) ;
100
96
}
101
97
102
98
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.' )
105
101
}
106
102
107
103
let numRows = matrix . length
108
104
let numCols = matrix [ 0 ] . length
109
105
let result = matrix
110
106
111
107
for ( let i = 0 , j = 0 ; i < numRows && j < numCols ; ) {
112
- if ( checkNonZero ( i , j , result ) === false ) {
108
+ if ( ! checkNonZero ( i , j , result ) ) {
113
109
j ++
114
110
continue
115
111
}
@@ -121,15 +117,14 @@ const rowEchelon = (matrix) => {
121
117
//..............make bottom elements zero...............
122
118
for ( let x = i + 1 ; x < numRows ; x ++ ) {
123
119
factor = result [ x ] [ j ]
124
- if ( factor === 0 ) {
120
+ if ( isTolerant ( 0 , factor , tolerance ) ) {
125
121
continue
126
122
}
127
123
scalarMultiplication ( i , factor , result )
128
124
subtractRow ( i , x , result )
129
125
factor = 1 / factor
130
126
scalarMultiplication ( i , factor , result )
131
127
}
132
- formatResult ( result )
133
128
i ++
134
129
}
135
130
return result
0 commit comments