我正在尝试用Java计算逆矩阵.
我正在遵循伴随方法(首先计算伴随矩阵,然后转置这个矩阵,最后,将它乘以行列式值的倒数).
当矩阵不太大时,它可以工作.我已经检查过,对于尺寸为12×12的矩阵,可以快速得到结果.但是,当矩阵大于12×12时,完成计算所需的时间呈指数增长.
我需要反转的矩阵是19×19,需要花费太多时间.更多时间消耗的方法是用于计算行列式的方法.
我正在使用的代码是:
public static double determinant(double[][] input) {
int rows = nRows(input); //number of rows in the matrix
int columns = nColumns(input); //number of columns in the matrix
double determinant = 0;
if ((rows== 1) && (columns == 1)) return input[0][0];
int sign = 1;
for (int column = 0; column < columns; column++) {
double[][] submatrix = getSubmatrix(input, rows, columns,column);
determinant = determinant + sign*input[0][column]*determinant(submatrix);
sign*=-1;
}
return determinant;
}
有人知道如何更有效地计算大矩阵的行列式吗?如果没有,有没有人知道如何使用其他算法计算大矩阵的逆?
谢谢
解决方法:
成倍?不,我相信矩阵求逆是O(N ^ 3).
我建议使用LU decomposition来求解矩阵方程.使用它时,您无需为行列式求解.
更好的是,查看一个包来帮助你.想到了JAMA.
12×12或19×19不是大型matricies.解决具有数十或数十万*度的问题是很常见的.
这是一个如何使用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);
}
}
根据quant_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);
}
}
根据您的情况调整这些.