Subject to the constraint . The NonNegativeLeastSquares class is used to compute a solution, which is compared to the exact solution of {1, -4, 7}.
import com.imsl.math.*; public class NonNegativeLeastSquaresEx1 { public static void main(String args[]) throws Exception { double a[][] = { { 1, -3, 2}, {-3, 10, -5}, { 2, -5, 6} }; double b[] = {27, -78, 64}; NonNegativeLeastSquares nnls = new NonNegativeLeastSquares(a, b); nnls.solve(); double[] x = nnls.getSolution(); new PrintMatrix("Solution").print(x); // compare solution with exact answer double[][] compare = new double[2][]; compare[0] = Matrix.multiply(a, x); compare[1] = Matrix.multiply(a, new double[] {1, -4, 7}); PrintMatrixFormat pmf = new PrintMatrixFormat(); pmf.setColumnLabels(new String[] {"x >= 0", "exact"}); PrintMatrix pm = new PrintMatrix("Comparison of 'b'"); pm.print(pmf, Matrix.transpose(compare)); } }
Solution 0 0 18.449 1 0 2 4.507 Comparison of 'b' x >= 0 exact 0 27.464 27 1 -77.884 -78 2 63.942 64Link to Java source.