How to Solve Equations with java?

天涯浪子 提交于 2019-11-26 14:17:17

问题


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?


回答1:


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.




回答2:


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.




回答3:


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();
    }
}




回答4:


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




回答5:


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




回答6:


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

Code example



来源:https://stackoverflow.com/questions/1431885/how-to-solve-equations-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!