numerics
Loading...
Searching...
No Matches
gauss_seidel.cpp
Go to the documentation of this file.
1
#include "
linalg/solvers/gauss_seidel.hpp
"
2
#include <cmath>
3
#include <stdexcept>
4
5
namespace
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.
13
SolverResult
gauss_seidel
(
const
Matrix
&
A
,
const
Vector
&
b
,
Vector
& x,
14
real
tol
,
idx
max_iter
,
Backend
backend) {
15
constexpr
real
zero_diag_tol
= 1
e
-15;
16
idx
n =
b
.size();
17
if
(
A
.rows() != n ||
A
.cols() != n || x.
size
() != n)
18
throw
std::invalid_argument(
"Dimension mismatch in Gauss-Seidel solver"
);
19
20
SolverResult
result
{0, 0.0,
false
};
21
22
for
(
idx
iter
= 0;
iter
<
max_iter
; ++
iter
) {
23
// Sequential update -- maintain GS convergence properties
24
for
(
idx
i
= 0;
i
< n; ++
i
) {
25
if
(std::abs(
A
(
i
,
i
)) <
zero_diag_tol
)
26
throw
std::runtime_error(
"Zero diagonal in Gauss-Seidel at row "
+
27
std::to_string(
i
));
28
real
sigma
= 0.0;
29
for
(
idx
j
= 0;
j
< n; ++
j
)
30
if
(
j
!=
i
)
sigma
+=
A
(
i
,
j
) * x[
j
];
31
x[
i
] = (
b
[
i
] -
sigma
) /
A
(
i
,
i
);
32
}
33
34
// Residual ||b - Ax||
35
real
res
= 0.0;
36
#ifdef NUMERICS_HAS_OMP
37
#pragma omp parallel for reduction(+:res) schedule(static) if(backend == Backend::omp)
38
#endif
39
for
(
idx
i
= 0;
i
< n; ++
i
) {
40
real
ri
=
b
[
i
];
41
for
(
idx
j
= 0;
j
< n; ++
j
)
ri
-=
A
(
i
,
j
) * x[
j
];
42
res
+=
ri
*
ri
;
43
}
44
result
.residual = std::sqrt(
res
);
45
result
.iterations =
iter
+ 1;
46
47
if
(
result
.residual <
tol
) {
48
result
.converged =
true
;
49
break
;
50
}
51
}
52
return
result
;
53
}
54
55
}
// namespace num
num::BasicVector< real >
num::BasicVector::size
constexpr idx size() const noexcept
Definition
vector.hpp:77
num::Matrix
Dense row-major matrix with optional GPU storage.
Definition
matrix.hpp:12
gauss_seidel.hpp
Gauss-Seidel iterative solver.
num
Definition
quadrature.hpp:8
num::real
double real
Definition
types.hpp:10
num::Backend
Backend
Selects which backend handles a linalg operation.
Definition
policy.hpp:19
num::ipow
constexpr T ipow(T x) noexcept
Compute x^N at compile time via repeated squaring.
Definition
integer_pow.hpp:34
num::idx
std::size_t idx
Definition
types.hpp:11
num::e
constexpr real e
Definition
math.hpp:41
num::gauss_seidel
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.
Definition
gauss_seidel.cpp:13
num::SolverResult
Definition
solver_result.hpp:8
src
linalg
solvers
gauss_seidel.cpp
Generated by
1.9.8