01_linear_systems.cpp¶
Solve a system of linear equations Ax = b by LU, Cholesky, QR and tridiagonal factorization.
Every factorization is a value, and the same free function solves with all of them. lu(A) pivots, while lu(A, no_pivot) skips the pivot search for matrices whose structure keeps the pivots nonzero. cholesky requires a matrix that carries the SPD law. qr solves least-squares problems with more rows than columns, and thomas solves a tridiagonal system in O(n).
#include <io/json.hpp>
#include <numerics.hpp>
#include <string_view>
using namespace num;
int main(int argc, char **argv) {
const bool plot = argc > 1 && std::string_view(argv[1]) == "--plot";
mat<real> A(3, 3, 0.0);
A(0, 0) = 4.0; A(0, 1) = 1.0;
A(1, 0) = 1.0; A(1, 1) = 4.0; A(1, 2) = 1.0;
A(2, 1) = 1.0; A(2, 2) = 4.0;
const vec<real> b{5.0, 6.0, 5.0};
const auto F = lu(A);
vec<real> x;
solve(F, b, x);
io::json results = {{"lu", {{"x", {x[0], x[1], x[2]}},
{"determinant", det(F)}, {"rcond", rcond(F, A)}}}};
const mat<real> I = inverse(F);
results["inverse_00"] = I(0, 0);
solve(lu(A, no_pivot), b, x);
results["no_pivot_lu"] = {x[0], x[1], x[2]};
solve(cholesky(assume_spd(A)), b, x);
results["cholesky"] = {x[0], x[1], x[2]};
vec<real> lower{1.0, 1.0}, diag{4.0, 4.0, 4.0}, upper{1.0, 1.0};
thomas(lower, diag, upper, b, x);
results["thomas"] = {x[0], x[1], x[2]};
// Least squares: the line c0 + c1 t through five noisy points.
const real t[5] = {0.0, 1.0, 2.0, 3.0, 4.0};
const vec<real> data{1.1, 2.9, 5.2, 7.1, 8.8};
mat<real> V(5, 2, 0.0);
for (idx i = 0; i < 5; ++i) {
V(i, 0) = 1.0;
V(i, 1) = t[i];
}
vec<real> c;
solve(qr(V), data, c);
results["least_squares_coefficients"] = {c[0], c[1]};
io::write_json(results, "result.json");
if (plot) {
std::vector<double> ts(t, t + 5), ys(data.data(), data.data() + 5), fit;
for (double ti : ts) {
fit.push_back(c[0] + (c[1] * ti));
}
plt::plot(ts, ys, "data", "points");
plt::plot(ts, fit, "least-squares line", "lines");
plt::title("01 QR least squares");
plt::savefig("plot.png");
}
}
Saved result:
{
"cholesky": [
1.0,
0.9999999999999999,
1.0
],
"inverse_00": 0.26785714285714285,
"least_squares_coefficients": [
1.1000000000000016,
1.9599999999999995
],
"lu": {
"determinant": 56.0,
"rcond": 0.38888888888888895,
"x": [
1.0,
1.0,
1.0
]
},
"no_pivot_lu": [
1.0,
1.0,
1.0
],
"thomas": [
1.0,
1.0,
1.0
]
}
