我正在尝试使用Jama解决4x4线性方程组(4个变量,4个方程)。我尝试了以下代码,但它不起作用。如果有人可以使用Jama或任何其他方法帮助我,我将不胜感激。
import Jama.Matrix;
public class OvaWork {
public OvaWork()
{
//Creating Arrays Representing Equations
double[][] lhsArray = {{-3, 1, -1}, {5, -2, 1}, {-1, 1, 3}, {2, 5, 7}};
double[] rhsArray = {-4, 6, 0, 8};
//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("w = " + Math.round(ans.get(0, 0)));
System.out.println("x = " + Math.round(ans.get(1, 0)));
System.out.println("y = " + Math.round(ans.get(2, 0)));
System.out.println("z = " + Math.round(ans.get(3, 0)));
}
public static void main(String[] args)
{
OvaWork o = new OvaWork();
}
}
答案 0 :(得分:2)
您必须尝试使用更简单的示例,例如此2x2等式
double[][] lhsArray = {{1,1},{2, 0}};
double[] rhsArray = {10,2};
Matrix lhs = new Matrix(lhsArray);
Matrix rhs = new Matrix(rhsArray, 2);
Matrix ans = lhs.solve(rhs);
它有效,输出是一个矩阵{1,9}
您的代码存在的问题是您的矩阵不是正方形,而是3x4
double[][] lhsArray = {{-3, 1, -1}, {5, -2, 1}, {-1, 1, 3}, {2, 5, 7}};
将矩阵更改为方形矩阵。
测试这个微不足道的等式:
double[][] lhsArray = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
double[] rhsArray = {1, 2, 3, 4};
Matrix lhs = new Matrix(lhsArray);
Matrix rhs = new Matrix(rhsArray, 4);
Matrix ans = lhs.solve(rhs);
如预期的那样,ans是{1,2,3,4}。