[英]Printing out: no solution, multiple solution with Apache in java
我有這段代碼可以解決 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)
因為上面的矩陣有或多個解,或沒有解
您可以要求行列式https://en.wikipedia.org/wiki/Determinant
“一個線性方程組有一個唯一的非平凡解,當且僅當它的行列式不為零。如果這個行列式為零,那么系統要么沒有非平凡解,要么有無限多個解。”
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)));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.