0

我正在尝试使用 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();
    }
}
4

1 回答 1

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}。

于 2016-04-28T01:23:24.643 回答