【问题标题】:How to solve linear system of equations using colt library in java如何在java中使用colt库求解线性方程组
【发布时间】:2013-10-14 10:09:45
【问题描述】:

我想使用 Colt 库求解线性方程 ma​​trix*X=D。 我试过了:

DoubleMatrix2D matrix;
matrix = new DenseDoubleMatrix2D(4,4);
for (int row = 0; row < 4; row++) {
    for (int column = 0; column < 4; column++) {
        // We set and get a cell value:             
        matrix.set(row,column,row+column);          
    }
}
DoubleMatrix2D D;
D = new DenseDoubleMatrix2D(4,1);
D.set(0,0, 1.0);
D.set(1,0, -1.0);
D.set(2,0, 91.0);
D.set(3,0, -5.0);
DoubleMatrix2D X;
X = solve(matrix,D);

但我得到一个错误
“方法solve(DoubleMatrix2D,DoubleMatrix2D)对于Test类型未定义”, 其中 Test 是类的名称。

我做错了什么? 有什么想法吗?...

【问题讨论】:

  • 能否请您添加您如何声明solve 方法?
  • solve 方法是 Colt 库中的一个方法,它不是我的。我只是想知道如何在我的程序中使用它...
  • 你在课堂上导入 Colt 库了吗?
  • 是的,我输入了:import cern.colt.matrix.*; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; 不是吗?...

标签: java matrix system linear-algebra colt


【解决方案1】:

您收到此错误的原因是因为方法solve() 是非静态的,无法从main() 访问。

这应该可以解决您的问题:

Algebra algebra = new Algebra();
DoubleMatrix2D X = algebra.solve(matrix, D);

【讨论】:

  • 很好,但是当我运行它时,我得到了错误:Exception in thread "main" java.lang.IllegalArgumentException:Matrix is singular.at cern.colt.matrix.linalg.LUDecompositionQuick.solve(Unknown Source)at cern.colt.matrix.linalg.LUDecomposition.solve(Unknown Source)at cern.colt.matrix.linalg.Algebra.solve(Unknown Source)at test.Test.main(Test.java:89)
【解决方案2】:

您也可以为此使用la4j(Java 的线性代数):

  • 对于确定的系统m == n,实际上是您的情况:

    // The coefficient matrix 'a'
    Matrix a = new Basic2DMatrix(new double[][] {
      { 1.0, 2.0, 3.0 },
      { 4.0, 5.0, 6.0 },
      { 7.0, 8.0. 9.0 }
    });
    
    // A right hand side vector, which is simple dense vector
    Vector b = new BasicVector(new double[] { 1.0, 2.0, 3.0 });
    
    // We will use standard Forward-Back Substitution method,
    // which is based on LU decomposition and can be used with square systems
    LinearSystemSolver solver = 
       a.withSolver(LinearAlgebra.FORWARD_BACK_SUBSTITUTION);
    
    Vector x = solver.solve(b, LinearAlgebra.DENSE_FACTORY);
    
  • 对于超定系统m &gt; n,可以使用LinearAlgebra.LEAST_SQUARES求解器。

所有示例均来自官方网站:http://la4j.org

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多