我正在使用 Jama 和 Apache Commons Math 来求解线性代数方程。当矩阵很小(4x4)时,它们都可以正常工作。但当它相对较大(25x25)时则不然。以下是我的实现:
贾马:
public double[][] solve(double[][] startState, double[][] input){
double[][] answer = new double[1][input.length-1];
Matrix A = new Matrix(input);
Matrix B = new Matrix(startState);
Matrix X = A.solve(B);
answer = X.getArray();
return answer;
}
这适用于:
double[][] startState = {{1},{2},{1},{2}};
double[][] input = {{1,1,0,0},{1,1,1,0},{0,1,1,1,},{0,0,1,1}};
double[][] answer = new JamaSolution().solve(startState, input);
但它失败了:
double[][] startState = { {0},{1},{2},{0},{2}, {0},{2},{1},{1},{0}, {0},{2},{1},{2},{2}, {1},{1},{1},{1},{2}, {1},{2},{1},{0},{0} };
double[][] input={
{1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,0,1,1, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,1,0,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,1,0,0,0, 1,1,1,0,0, 0,0,0,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0, 0,0,1,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,1, 0,0,0,1,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,1,1, 0,0,0,0,1} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,1,0,0, 0,1,1,1,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,1,0, 0,0,1,1,0} ,
{0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1, 0,0,0,0,1} ,
};
公共数学:
public void solve(double[] startState, double[][] input){
RealMatrix coefficients = new Array2DRowRealMatrix(input, false);
DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
RealVector constants = new ArrayRealVector(startState, false);
RealVector solution = solver.solve(constants);
}
这适用于:
double[] startState = {1,2,1,2};
double[][] input = {{1,1,0,0},{1,1,1,0},{0,1,1,1,},{0,0,1,1}};
但失败:
double[] startState =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