numerics 0.1.0
Loading...
Searching...
No Matches
jacobi.cpp
Go to the documentation of this file.
2#include <cmath>
3#include <stdexcept>
4
5namespace num {
6
7SolverResult jacobi(const Matrix &A, const Vector &b, Vector &x, real tol,
8 idx max_iter, Backend backend) {
9 constexpr real zero_diag_tol = 1e-15;
10 idx n = b.size();
11 if (A.rows() != n || A.cols() != n || x.size() != n)
12 throw std::invalid_argument("Dimension mismatch in Jacobi solver");
13
14 Vector x_new(n);
15 SolverResult result{0, 0.0, false};
16
17 for (idx iter = 0; iter < max_iter; ++iter) {
18 // Compute all updates from the previous iterate simultaneously
19#ifdef NUMERICS_HAS_OMP
20#pragma omp parallel for schedule(static) if (backend == Backend::omp)
21#endif
22 for (idx i = 0; i < n; ++i) {
23 if (std::abs(A(i, i)) < zero_diag_tol)
24 throw std::runtime_error("Zero diagonal in Jacobi solver at row " +
25 std::to_string(i));
26 real sigma = 0.0;
27 for (idx j = 0; j < n; ++j)
28 if (j != i)
29 sigma += A(i, j) * x[j];
30 x_new[i] = (b[i] - sigma) / A(i, i);
31 }
32
33 for (idx i = 0; i < n; ++i)
34 x[i] = x_new[i];
35
36 // Residual ||b - Ax||
37 real res = 0.0;
38#ifdef NUMERICS_HAS_OMP
39#pragma omp parallel for reduction(+ : res) \
40 schedule(static) if (backend == Backend::omp)
41#endif
42 for (idx i = 0; i < n; ++i) {
43 real ri = b[i];
44 for (idx j = 0; j < n; ++j)
45 ri -= A(i, j) * x[j];
46 res += ri * ri;
47 }
48 result.residual = std::sqrt(res);
49 result.iterations = iter + 1;
50
51 if (result.residual < tol) {
52 result.converged = true;
53 break;
54 }
55 }
56 return result;
57}
58
59} // namespace num
constexpr idx size() const noexcept
Definition vector.hpp:80
Dense row-major matrix with optional GPU storage.
Definition matrix.hpp:12
constexpr idx rows() const noexcept
Definition matrix.hpp:24
constexpr idx cols() const noexcept
Definition matrix.hpp:25
Jacobi iterative solver.
double real
Definition types.hpp:10
Backend
Selects which backend handles a linalg operation.
Definition policy.hpp:19
std::size_t idx
Definition types.hpp:11
constexpr real e
Definition math.hpp:43
SolverResult jacobi(const Matrix &A, const Vector &b, Vector &x, real tol=1e-10, idx max_iter=1000, Backend backend=default_backend)
Jacobi iterative solver for Ax = b.
Definition jacobi.cpp:7