gpt4 book ai didi

java - Jama 包,4x4 线性方程求解器

转载 作者:行者123 更新时间:2023-12-02 03:40:25 25 4
gpt4 key购买 nike

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

最佳答案

您必须尝试使用​​更简单的示例,例如这个 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}。

关于java - Jama 包,4x4 线性方程求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36898630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com