题
我有如下三个方程:
- x + y + z = 100;
- x + y - z = 50;
- x - y - z = 10;
如何使用 Java 找到 x、y 和 z 的值?
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?
}
您有任何可能的解决方案或其他通用框架吗?
解决方案
您可以使用行列式来计算 x y 和 z 的值。逻辑可以在这里找到 http://www.intmath.com/Matrices-determinants/1_Determinants.php
然后你需要使用 3 维数组在 java 中实现它。
其他提示
由于您正在编写 Java,因此您可以使用 美国医学会杂志 包来解决这个问题。我推荐一个好的 LU 分解方法。
这是一个简单的线性代数问题。您应该能够轻松地手动或使用 Excel 之类的工具来解决它。一旦获得,您就可以使用该解决方案来测试您的程序。
当然,不能保证一定有解决方案。如果您的矩阵是奇异矩阵,则意味着 3D 空间中这三条线不存在交集。
你可以使用java矩阵包 美国医学会杂志. 。请参阅下面此示例的完整页面 这里
/*
*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();
}
}
不隶属于 StackOverflow