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?
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.
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.
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();
}
}
Create a parser using ANTLR. Then evaluate the AST using Gaussian elimination.
You can also use Commons Math. They have a section of this in their userguide (see 3.4)
Use Gaussian_elimination it's incredibly easy, but there are some values you may have hard life calculating.
Code example