Java逆矩阵计算

Java逆矩阵计算,第1张

Java逆矩阵计算

指数?不,我相信矩阵求逆是O(N ^ 3)。

我建议使用LU分解来求解矩阵方程。使用时无需求解行列式

更好的是,寻找一个可以帮助您的软件包。 JAMA浮现在脑海。

12x12或19x19不是大型矩阵。这是常见的解决与几十或几百问题 十万 的自由度。

这是如何使用JAMA的有效示例。编译和运行时,必须在CLASSPATH中包含JAMA JAR:

package linearalgebra;import Jama.LUDecomposition;import Jama.Matrix;public class JamaDemo{    public static void main(String[] args)    {        double [][] values = {{1, 1, 2}, {2, 4, -3}, {3, 6, -5}};  // each array is a row in the matrix        double [] rhs = { 9, 1, 0 }; // rhs vector        double [] answer = { 1, 2, 3 }; // this is the answer that you should get.        Matrix a = new Matrix(values);        a.print(10, 2);        LUDecomposition luDecomposition = new LUDecomposition(a);        luDecomposition.getL().print(10, 2); // lower matrix        luDecomposition.getU().print(10, 2); // upper matrix        Matrix b = new Matrix(rhs, rhs.length);        Matrix x = luDecomposition.solve(b); // solve Ax = b for the unknown vector x        x.print(10, 2); // print the solution        Matrix residual = a.times(x).minus(b); // calculate the residual error        double rnorm = residual.normInf(); // get the max error (yes, it's very small)        System.out.println("residual: " + rnorm);    }}

这是根据quantum_dev的建议使用Apache Commons Math解决的相同问题:

package linearalgebra;import org.apache.commons.math.linear.Array2DRowRealMatrix;import org.apache.commons.math.linear.ArrayRealVector;import org.apache.commons.math.linear.DecompositionSolver;import org.apache.commons.math.linear.LUDecompositionImpl;import org.apache.commons.math.linear.RealMatrix;import org.apache.commons.math.linear.RealVector;public class LinearAlgebraDemo{    public static void main(String[] args)    {        double [][] values = {{1, 1, 2}, {2, 4, -3}, {3, 6, -5}};        double [] rhs = { 9, 1, 0 };        RealMatrix a = new Array2DRowRealMatrix(values);        System.out.println("a matrix: " + a);        DecompositionSolver solver = new LUDecompositionImpl(a).getSolver();        RealVector b = new ArrayRealVector(rhs);        RealVector x = solver.solve(b);        System.out.println("solution x: " + x);;        RealVector residual = a.operate(x).subtract(b);        double rnorm = residual.getLInfNorm();        System.out.println("residual: " + rnorm);    }}

使这些适应您的情况。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5479150.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存