我正在尝试使用 C++ 中的 Eigen 库求解稀疏线性系统 Ax=B,但是以下简单示例似乎给出了错误的解决方案:
#include <Eigen/SparseCholesky>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <iostream>
#include <vector>
using namespace std;
using namespace Eigen;
int main(){
SimplicialLDLT<SparseMatrix<double>> solver;
SparseMatrix<double> A(9,9);
typedef Triplet<double> T;
vector<T> triplet;
VectorXd B(9);
for(int i=0; i<4; i++){
triplet.push_back(T(i,i,1));
triplet.push_back(T(i+5,i+5,1));
}
triplet.push_back(T(4,1,-1));
triplet.push_back(T(4,3,-1));
triplet.push_back(T(4,5,-1));
triplet.push_back(T(4,7,-1));
triplet.push_back(T(4,4,4));
A.setFromTriplets(triplet.begin(),triplet.end());
B << 0,0,0,0,0.387049,0,0,0,0;
solver.compute(A);
VectorXd x = solver.solve(B);
cout << "A\n" << A << "\n";
cout << "B\n" << B << "\n";
cout << "x\n" << x << "\n";
return 0;
}
我没有看到任何错误,算法返回“0”意味着“成功”,但是我得到的解决方案是
x = 0 0.193524 0 0.193524 0.193524 0 0 0 0
这显然不是该系统的解决方案,正确的解决方案是
x = 0 0 0 0 0.0967621 0 0 0 0
最佳答案
Here's documentation对于 SimplicialLDLT
求解器:
This class provides a LDL^T Cholesky factorizations without square root of sparse matrices that are selfadjoint and positive definite.
当矩阵的元素存储实数时,自伴==对称。你的矩阵显然不对称。此外,并非每个对称矩阵都是正定的,see examples .
简而言之,您选择的求解器仅适用于非常狭窄的矩阵类别。正如您已经发现的,SparseLU
求解器适用于您的输入数据。
ConjugateGradient
求解器也不起作用,它不需要矩阵是正定的,但 it does要求它是自伴的。
关于c++ - 特征稀疏求解器结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63583888/