60 lines
1.4 KiB
C++
60 lines
1.4 KiB
C++
#include "krylov/types/common.hpp"
|
|
#include <cassert>
|
|
#include <cmath>
|
|
|
|
static bool approx(double a, double b, double eps = 1e-10) {
|
|
return std::abs(a - b) < eps;
|
|
}
|
|
|
|
int main() {
|
|
using krylov::Matrix;
|
|
using krylov::Vector;
|
|
using MatrixXd = Matrix;
|
|
using VectorXd = Vector;
|
|
|
|
// 1) 基本矩阵 / 向量运算
|
|
MatrixXd A(2, 2);
|
|
A << 4, 1,
|
|
2, 3;
|
|
VectorXd b(2);
|
|
b << 1, 2;
|
|
|
|
VectorXd Ab = A * b;
|
|
assert(approx(Ab(0), 4 * 1 + 1 * 2));
|
|
assert(approx(Ab(1), 2 * 1 + 3 * 2));
|
|
|
|
// 2) 行列式 / 逆
|
|
assert(approx(A.determinant(), 4 * 3 - 1 * 2));
|
|
MatrixXd I = A * A.inverse();
|
|
assert(approx(I(0, 0), 1.0));
|
|
assert(approx(I(1, 1), 1.0));
|
|
assert(approx(I(0, 1), 0.0));
|
|
assert(approx(I(1, 0), 0.0));
|
|
|
|
// 3) 线性方程求解 A x = b
|
|
VectorXd x = A.colPivHouseholderQr().solve(b);
|
|
VectorXd r = A * x - b;
|
|
assert(r.norm() < 1e-10);
|
|
|
|
// 4) 范数
|
|
VectorXd v(3);
|
|
v << 3, 0, 4;
|
|
assert(approx(v.norm(), 5.0));
|
|
assert(approx(v.squaredNorm(), 25.0));
|
|
|
|
// 5) 稀疏矩阵基础
|
|
krylov::SparseMatrix S(3, 3);
|
|
S.insert(0, 0) = 1.0;
|
|
S.insert(1, 1) = 2.0;
|
|
S.insert(2, 2) = 3.0;
|
|
S.makeCompressed();
|
|
VectorXd y(3);
|
|
y << 1, 1, 1;
|
|
VectorXd Sy = S * y;
|
|
assert(approx(Sy(0), 1.0));
|
|
assert(approx(Sy(1), 2.0));
|
|
assert(approx(Sy(2), 3.0));
|
|
|
|
return 0;
|
|
}
|