LUDecomposition implements AutoCloseable { public Vector solve(Vector b) { final int m = pivot.size(); if (b.size() != m) throw new CardinalityException(b.size(), m); if (singular) throw new SingularMatrixException(); final double[] bp = new double[m]; for (int row = 0; row < m; row++) bp[row] = b.get((int)pivot.get(row)); for (int col = 0; col < m; col++) { final double bpCol = bp[col]; for (int i = col + 1; i < m; i++) bp[i] -= bpCol * lu.get(i, col); } for (int col = m - 1; col >= 0; col--) { bp[col] /= lu.get(col, col); final double bpCol = bp[col]; for (int i = 0; i < col; i++) bp[i] -= bpCol * lu.get(i, col); } return b.like(m).assign(bp); } LUDecomposition(Matrix matrix);  LUDecomposition(Matrix matrix, double singularityThreshold); @Override void close(); Matrix getL(); Matrix getU(); Matrix getP(); Vector getPivot(); double determinant(); Vector solve(Vector b); Matrix solve(Matrix b);  }
@Test(expected = CardinalityException.class) public void solveVecWrongSize() throws Exception { new LUDecomposition(testMatrix).solve(new DenseVector(testMatrix.rowSize() + 1)); }
@Test(expected = SingularMatrixException.class) public void solveVecSingularMatrix() throws Exception { new LUDecomposition(new DenseMatrix(testMatrix.rowSize(), testMatrix.rowSize())) .solve(new DenseVector(testMatrix.rowSize())); }
@Test public void solveVec() throws Exception { Vector sol = new LUDecomposition(testMatrix) .solve(new DenseVector(testMatrix.rowSize())); assertEquals("Wrong solution vector size.", testMatrix.rowSize(), sol.size()); for (int i = 0; i < sol.size(); i++) assertEquals("Unexpected value at index " + i, 0d, sol.getX(i), 0.0000001d); }
@Test(expected = CardinalityException.class) public void solveMtxWrongSize() throws Exception { new LUDecomposition(testMatrix).solve( new DenseMatrix(testMatrix.rowSize() + 1, testMatrix.rowSize())); }
@Test(expected = SingularMatrixException.class) public void solveMtxSingularMatrix() throws Exception { new LUDecomposition(new DenseMatrix(testMatrix.rowSize(), testMatrix.rowSize())) .solve(new DenseMatrix(testMatrix.rowSize(), testMatrix.rowSize())); }
@Test public void solveMtx() throws Exception { Matrix sol = new LUDecomposition(testMatrix) .solve(new DenseMatrix(testMatrix.rowSize(), testMatrix.rowSize())); assertEquals("Wrong solution matrix row size.", testMatrix.rowSize(), sol.rowSize()); assertEquals("Wrong solution matrix column size.", testMatrix.rowSize(), sol.columnSize()); for (int row = 0; row < sol.rowSize(); row++) for (int col = 0; col < sol.columnSize(); col++) assertEquals("Unexpected P value at (" + row + "," + col + ").", 0d, sol.getX(row, col), 0.0000001d); }