How to Solve Equations with java?

前端 未结 8 715
花落未央
花落未央 2020-12-03 05:45

I have three equations like the following ones:

  • x + y + z = 100;
  • x + y - z = 50;
  • x - y - z = 10;

How can I find the values of

8条回答
  •  醉梦人生
    2020-12-03 06:08

    try this, please:

    import org.apache.commons.math3.linear.*;
    import org.junit.Assert;
    import org.junit.Test;
    
    /**
     * Author: Andrea Ciccotta
     */
    public class LinearSystemTest extends Assert {
    
        /**
         * Ax = B
         * 2x + 3y - 2z = 1
         * -x + 7y + 6x = -2
         * 4x - 3y - 5z = 1
         * 

    * it will use the LUDecomposition: * LU decomposition: * 1. find A = LU where LUx = B * 2. solve Ly = B * 4. solve Ux = y */ @Test public void linearSystem3x3Test() { final RealMatrix coefficients = new Array2DRowRealMatrix(new double[][]{{2, 3, -2}, {-1, 7, 6}, {4, -3, -5}}); final DecompositionSolver solver = new LUDecomposition(coefficients).getSolver(); final RealVector constants = new ArrayRealVector(new double[]{1, -2, 1}, false); final RealVector solution = solver.solve(constants); final double[] arraySolution = solution.toArray(); assertEquals(arraySolution[0], -0.36986301369863006, 0); assertEquals(arraySolution[1], 0.1780821917808219, 0); assertEquals(arraySolution[2], -0.6027397260273972, 0); } }

提交回复
热议问题