15

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 x, y, and z with Java?

String equation1="x+y+z=100;";
String equation2="x+y-z=50;";
String equation3="x-y-z=10;";

int[] SolveEquations(equation1,equation2,equation3) {
   // to do
   // how to do?    
} 

Do you have any possible solutions or other common frameworks?

sth
  • 222,467
  • 53
  • 283
  • 367
Cong De Peng
  • 321
  • 1
  • 4
  • 11
  • 17
    I wish people would stop assuming homework. It's one thing if someone posts something right out of a textbook problem like "Write a nonrecursive algorithm to achieve O(log n) sorting for an array." – Jason S Sep 18 '09 at 15:01
  • Another source, with sample code in various languages is [given here](http://www.cs.umbc.edu/~squire/cs455_l3.html) – DaveJohnston Sep 16 '09 at 09:34

8 Answers8

12

You can use determinant to calculate values of x y and z. Logic can be found out here http://www.intmath.com/Matrices-determinants/1_Determinants.php

And then you need to implement it in java using 3 dimensional arrays.

Xinus
  • 29,617
  • 32
  • 119
  • 165
  • 2
    This is the mathematically valid, but not very good in terms of efficiency. see Transcript - Lecture 20 from video lectures of Professor Gilbert Strang teaching 18.06 "If you had to -- and Matlab would never, never do it. I mean, it would use elimination." http://ocw.mit.edu/OcwWeb/Mathematics/18-06Spring-2005/VideoLectures/detail/lecture20.htm – Liran Orevi Sep 16 '09 at 09:51
  • 6
    Computing a determinant is (I think) O(n!). Gaussian elimination is O(n^2). – erikkallen Sep 17 '09 at 09:48
  • 3
    NO NO NO ***NEVER*** use determinants. What the previous two commenters said. – Jason S Sep 18 '09 at 15:01
12

Since you're writing Java, you can use the JAMA package to solve this. I'd recommend a good LU decomposition method.

It's a simple linear algebra problem. You should be able to solve it by hand or using something like Excel pretty easily. Once you have that you can use the solution to test your program.

There's no guarantee, of course, that there is a solution. If your matrix is singular, that means there is no intersection of those three lines in 3D space.

Jayan
  • 18,003
  • 15
  • 89
  • 143
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • What's the reason to prefer LU decomposition? – Liran Orevi Sep 16 '09 at 10:55
  • 1
    "LU decomposition is computationally efficient only when we have to solve a matrix equation multiple times for different b; it is faster in this case to do an LU decomposition of the matrix A once and then solve the triangular matrices for the different b, than to use Gaussian elimination each time." - common for finite element analysis with multiple load vectors. You're correct - it might not matter in this case. – duffymo Sep 16 '09 at 21:37
10

you can use the java matrix package JAMA. See the full page of this example below here

/*
 *Solving three variable linear equation system
 * 3x + 2y -  z =  1 ---> Eqn(1)
 * 2x - 2y + 4z = -2 ---> Eqn(2)
 * -x + y/2-  z =  0 ---> Eqn(3)
 */
import Jama.Matrix;
import java.lang.Math.*;
public class Main {
    public Main() {
        //Creating  Arrays Representing Equations
        double[][] lhsArray = {{3, 2, -1}, {2, -2, 4}, {-1, 0.5, -1}};
        double[] rhsArray = {1, -2, 0};
        //Creating Matrix Objects with arrays
        Matrix lhs = new Matrix(lhsArray);
        Matrix rhs = new Matrix(rhsArray, 3);
        //Calculate Solved Matrix
        Matrix ans = lhs.solve(rhs);
        //Printing Answers
        System.out.println("x = " + Math.round(ans.get(0, 0)));
        System.out.println("y = " + Math.round(ans.get(1, 0)));
        System.out.println("z = " + Math.round(ans.get(2, 0)));
    }

    public static void main(String[] args) {
        new Main();
    }
}

sandi vorace
  • 101
  • 1
  • 5
5

You can also use Commons Math. They have a section of this in their userguide (see 3.4)

Valentin Rocher
  • 11,667
  • 45
  • 59
4

Create a parser using ANTLR. Then evaluate the AST using Gaussian elimination.

erikkallen
  • 33,800
  • 13
  • 85
  • 120
2

Use Gaussian_elimination it's incredibly easy, but there are some values you may have hard life calculating.

Code example

Liran Orevi
  • 4,755
  • 7
  • 47
  • 64
2

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
     * <p>
     * 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);
    }

}
Andrea Ciccotta
  • 598
  • 6
  • 16
1

There are many ways to solve linear system equations. There is a simplest way to perform this. In the example the java code solve for two variables USING Matrix method but you can modify to perform 3 variables calculations.

import java.util.Scanner; //OBJETO SCANNER

public class SYS2 {

    public static void main (String args[]) {

        //VARIABLE DECLARATION SPACE
        int i=0,j = 0;
        float x,y;
         Scanner S = new Scanner (System.in);

         int EC3[][]= new int [2][3]; //ARRAY TO STORE EQUATION 2X3

         float DET1=0;
        float DET2 =0;


        float DETA=0;
         float DETB=0;

        //END VARIABLE DECLARATIONS
       System.out.println("Enter Equation System : ");

for (i=0; i< 2; i++) {
                for (j=0; j< 3; j++) 
                        EC3[i][j] = S.nextInt();
                }    

                System.out.println("SISTEMA DE ECUACION LINEAL: "); //THIS SENTENCE ONLY PRINT THE CATCHED VALUES OF EQUATION

                for (i=0; i< 2; i++) {
                        for (j=0; j< 3; j++) 

                              System.out.print(EC3[i][j] + "  ");

                            System.out.println();


                }    




           //    System.out.print("Determinante A de la Matriz: ");

             //    System.out.print((EC3[0][2] * EC3[1][1]) - (EC3[0][1]*EC3[1][2]) );

                for (i=0;i<2;i++) {
                        for (j=0; j<2;j++)
                                DET1=  ((EC3[0][2] * EC3[1][1]) -( EC3[0][1]*EC3[1][2]));
                }

                           //    System.out.print(DET1 );
                            //       System.out.println();

                                 for (i=0;i<2;i++) {
                                        for (j=0; j<2;j++)
                                         DET2=  ((EC3[0][0] * EC3[1][1]) - (EC3[0][1]*EC3[1][0]));
                }

                               // System.out.print("Determinante B de la Matriz: ");
                               //  System.out.println(DET2 ); 

    x = (DET1 / DET2);

    System.out.println();
    System.out.println("X = " + x);
    System.out.print("=======================");
    //FIN PARA VALOR DE X



    //COMIENZO DE VALOR DE Y

  //  System.out.print("Determinante A de la Matriz Y: ");

                                    for (i=0;i<2;i++) {
                                            for (j=0; j<2;j++)
                                         DETA=  EC3[0][0] * EC3[1][2] - EC3[0][2]*EC3[1][0];


                                        //    System.out.print(DETA );
                                          //  System.out.println();
                }


                                     for (i=0;i<2;i++) {
                                            for (j=0; j<2;j++)
                                         DETB=  EC3[0][0] * EC3[1][1] - EC3[0][1]*EC3[1][0];

                }

                                   // System.out.print("Determinante B de la Matriz Y: ");
                                   //  System.out.println(DETB );                  
                                    y = DETA / DETB;

                                    System.out.print("=======================");
                                    System.out.println();

                                    System.out.println("Y = " + y);
                                    System.out.print("=======================");
    }
}