6
6
* @link <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gaussian Elimination Wiki</a>
7
7
* @see InverseOfMatrix finds the full of inverse of a matrice, but is not required to solve a system.
8
8
*/
9
- public class SolveSystem {
9
+ public final class SolveSystem {
10
10
private SolveSystem () {
11
11
}
12
12
13
13
/**
14
14
* Problem: Given a matrix A and vector b, solve the linear system Ax = b for the vector x.\
15
15
* <p>
16
- * This variation uses @link <a href="https://en.wikipedia.org/wiki/Crout_matrix_decomposition">Crout Reduction</a>
17
- * and partial pivoting to decompose the matrix.
18
16
* <b>This OVERWRITES the input matrix to save on memory</b>
19
17
*
20
18
* @param matrix - a square matrix of doubles
21
19
* @param constants - an array of constant
22
20
* @return solutions
23
21
*/
24
22
public static double [] solveSystem (double [][] matrix , double [] constants ) {
25
- final double TOL = 0.00000001 ; // tolerance for round off
23
+ final double tol = 0.00000001 ; // tolerance for round off
26
24
for (int k = 0 ; k < matrix .length - 1 ; k ++) {
27
25
// find the largest value in column (to avoid zero pivots)
28
26
double maxVal = Math .abs (matrix [k ][k ]);
@@ -33,8 +31,10 @@ public static double[] solveSystem(double[][] matrix, double[] constants) {
33
31
maxIdx = j ;
34
32
}
35
33
}
36
- if (Math .abs (maxVal ) < TOL ) // hope the matrix works out
34
+ if (Math .abs (maxVal ) < tol ){
35
+ // hope the matrix works out
37
36
continue ;
37
+ }
38
38
// swap rows
39
39
double [] temp = matrix [k ];
40
40
matrix [k ] = matrix [maxIdx ];
@@ -56,12 +56,16 @@ public static double[] solveSystem(double[][] matrix, double[] constants) {
56
56
System .arraycopy (constants , 0 , x , 0 , constants .length );
57
57
for (int i = matrix .length - 1 ; i >= 0 ; i --) {
58
58
double sum = 0 ;
59
- for (int j = i + 1 ; j < matrix .length ; j ++) sum += matrix [i ][j ] * x [j ];
59
+ for (int j = i + 1 ; j < matrix .length ; j ++){
60
+ sum += matrix [i ][j ] * x [j ];
61
+ }
60
62
x [i ] = constants [i ] - sum ;
61
- if (Math .abs (matrix [i ][i ]) > TOL )
63
+ if (Math .abs (matrix [i ][i ]) > tol ){
62
64
x [i ] /= matrix [i ][i ];
63
- else
65
+ }
66
+ else {
64
67
throw new IllegalArgumentException ("Matrix was found to be singular" );
68
+ }
65
69
}
66
70
return x ;
67
71
}
0 commit comments