numerics 0.1.0
Loading...
Searching...
No Matches
gauss_seidel.cpp
Go to the documentation of this file.
2#include <cmath>
3#include <stdexcept>
4
5namespace num {
6
7// Gauss-Seidel -- sequential update order, parallel residual when omp backend.
8//
9// Note: standard Gauss-Seidel has sequential data dependencies (x[i] depends
10// on x[0..i-1] updated in the same sweep). We keep the sequential update
11// order here and parallelise only the residual computation. For a truly
12// parallel relaxation scheme, use the Jacobi solver with Backend::omp.
14 const Vector& b,
15 Vector& x,
16 real tol,
17 idx max_iter,
18 Backend backend) {
19 constexpr real zero_diag_tol = 1e-15;
20 idx n = b.size();
21 if (A.rows() != n || A.cols() != n || x.size() != n) {
22 throw std::invalid_argument("Dimension mismatch in Gauss-Seidel solver");
23 }
24
25 SolverResult result{0, 0.0, false};
26
27 for (idx iter = 0; iter < max_iter; ++iter) {
28 // Sequential update -- maintain GS convergence properties
29 for (idx i = 0; i < n; ++i) {
30 if (std::abs(A(i, i)) < zero_diag_tol) {
31 throw std::runtime_error("Zero diagonal in Gauss-Seidel at row "
32 + std::to_string(i));
33 }
34 real sigma = 0.0;
35 for (idx j = 0; j < n; ++j) {
36 if (j != i) {
37 sigma += A(i, j) * x[j];
38 }
39 }
40 x[i] = (b[i] - sigma) / A(i, i);
41 }
42
43 // Residual ||b - Ax||
44 real res = 0.0;
45#ifdef NUMERICS_HAS_OMP
46 #pragma omp parallel for reduction(+ : res) \
47 schedule(static) if (backend == Backend::omp)
48#endif
49 for (idx i = 0; i < n; ++i) {
50 real ri = b[i];
51 for (idx j = 0; j < n; ++j) {
52 ri -= A(i, j) * x[j];
53 }
54 res += ri * ri;
55 }
56 result.residual = std::sqrt(res);
57 result.iterations = iter + 1;
58
59 if (result.residual < tol) {
60 result.converged = true;
61 break;
62 }
63 }
64 return result;
65}
66
67} // namespace num
constexpr idx rows() const noexcept
Definition matrix.hpp:87
constexpr idx cols() const noexcept
Definition matrix.hpp:88
constexpr idx size() const noexcept
Definition vector.hpp:83
Gauss-Seidel iterative solver.
double real
Definition types.hpp:10
Backend
Definition policy.hpp:7
std::size_t idx
Definition types.hpp:11
constexpr real e
Definition math.hpp:44
SolverResult gauss_seidel(const Matrix &A, const Vector &b, Vector &x, real tol=1e-10, idx max_iter=1000, Backend backend=default_backend)
Gauss-Seidel iterative solver for Ax = b.