前言
本文集合了Gauss消去法, 共轭梯度法, Gmres方法的线性求解器的源码。同时集成了API方便调用,支持读取文本形式的矩阵数据。更进一步集成Matrix Market 的接口, 可以将在 Matrix Market 下载的数据直接读如测试。同时对共轭梯度法和 Gmres 方法都做了预条件矩阵。
部分源码
#ifndef Matrix_H
#define Matrix_H
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <math.h>
using namespace std;
enum SolverType {GAUSS_SOLVER, CG_SOLVER, GMRES_SOLVER, UNKNOWN_METHOD};
static const string SolverTypeName[] = {"GAUSS_SOLVER", "CG_SOLVER", "GMRES_SOLVER", "UNKNOWN_METHOD"};
class Matrix
{
//......
}
//列压缩矩阵
class CSRMatrix : public Matrix
{
//.....
}
//预条件矩阵
class Preconditioner
{
//....
}
class GaussEliminationSolver
{
//.....
}
class ConjugateGradientSolver
{
//....
}
class GMRESSolver
{
//....
}
class LinearSolverAPI
{
public:
/*
.......
*/
public:
void setSolverType(const SolverType& solverType) {_solverType = solverType;}
bool solve();
bool checkSolution();
private:
bool cgSolverApi();
bool gmresSolveApi();
public:
// all function is for test
bool readMatrixFromMatrixMarket(const string& fileName);
bool buildRightVector();
bool readData(const string& fileName, bool isIndexFromZero);
private:
map<unsigned int, map<unsigned int, double> > _A;
vector<double> _x;
vector<double> _b;
double _eps;
double _norm2Error;
SolverType _solverType;
};
源码
完整源码请到我的博客的资源页面下载使用。