我有这个代码可以解决4x4线性方程。 当线性方程没有解或者有多个解时,我怎么能打印出来。而不是打印错误?
public class OvaWork
{
void fourthEquationSolver()
{
//Creating Arrays Representing Equations
double[][] lhsArray = {{8,1,10,1}, {2,1,5,4}, {1,5,3,2}, {9,8,4,6}};
double[] rhsArray = {14,22,38,44};
//Creating Matrix Objects with arrays
Matrix lhs = new Matrix(lhsArray);
Matrix rhs = new Matrix(rhsArray, 4);
//Calculate Solved Matrix
Matrix ans = lhs.solve(rhs);
//Printing Answers
System.out.println("x1 = " + (ans.get(0, 0)));
System.out.println("x2 = " + (ans.get(1, 0)));
System.out.println("X3 = " + (ans.get(2, 0)));
System.out.println("X4 = " + (ans.get(3, 0)));
}
public static void main(String[] args)
{
OvaWork equation = new OvaWork();
}
}
当我在这段代码中写下这样的矩阵:
1,1,1,1=14
2,2,2,2=22
3,3,3,3=38
4,4,4,4=44
此代码打印:
Exception in thread "main" java.lang.RuntimeException: Matrix is singular.
at Jama.LUDecomposition.solve(LUDecomposition.java:282)
at Jama.Matrix.solve(Matrix.java:815)
at OvaWork.fourthEquationSolver(OvaWork.java:20)
at OvaWork.main(OvaWork.java:106)
因为上面的矩阵有多个解决方案,或者没有解决方案
答案 0 :(得分:0)
您可以要求决定因素https://en.wikipedia.org/wiki/Determinant
“当且仅当其行列式为非零时,线性方程组才有一个独特的非平凡解。如果该行列式为零,那么系统要么没有非平凡解,要么无数个解。” / p>
if (lhs.det() == 0) {
System.out.println("No solution or infinite number of solutions");
} else {
Matrix ans = lhs.solve(rhs);
//Printing Answers
System.out.println("x1 = " + (ans.get(0, 0)));
System.out.println("x2 = " + (ans.get(1, 0)));
System.out.println("X3 = " + (ans.get(2, 0)));
System.out.println("X4 = " + (ans.get(3, 0)));
}