66 * @link <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gaussian Elimination Wiki</a>
77 * @see InverseOfMatrix finds the full of inverse of a matrice, but is not required to solve a system.
88 */
9- public class SolveSystem {
9+ public final class SolveSystem {
1010 private SolveSystem () {
1111 }
1212
1313 /**
1414 * Problem: Given a matrix A and vector b, solve the linear system Ax = b for the vector x.\
1515 * <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.
1816 * <b>This OVERWRITES the input matrix to save on memory</b>
1917 *
2018 * @param matrix - a square matrix of doubles
2119 * @param constants - an array of constant
2220 * @return solutions
2321 */
2422 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
2624 for (int k = 0 ; k < matrix .length - 1 ; k ++) {
2725 // find the largest value in column (to avoid zero pivots)
2826 double maxVal = Math .abs (matrix [k ][k ]);
@@ -33,8 +31,10 @@ public static double[] solveSystem(double[][] matrix, double[] constants) {
3331 maxIdx = j ;
3432 }
3533 }
36- if (Math .abs (maxVal ) < TOL ) // hope the matrix works out
34+ if (Math .abs (maxVal ) < tol ){
35+ // hope the matrix works out
3736 continue ;
37+ }
3838 // swap rows
3939 double [] temp = matrix [k ];
4040 matrix [k ] = matrix [maxIdx ];
@@ -56,12 +56,16 @@ public static double[] solveSystem(double[][] matrix, double[] constants) {
5656 System .arraycopy (constants , 0 , x , 0 , constants .length );
5757 for (int i = matrix .length - 1 ; i >= 0 ; i --) {
5858 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+ }
6062 x [i ] = constants [i ] - sum ;
61- if (Math .abs (matrix [i ][i ]) > TOL )
63+ if (Math .abs (matrix [i ][i ]) > tol ){
6264 x [i ] /= matrix [i ][i ];
63- else
65+ }
66+ else {
6467 throw new IllegalArgumentException ("Matrix was found to be singular" );
68+ }
6569 }
6670 return x ;
6771 }
0 commit comments