NULAPACK
NUmerical Linear Algebra PACKage
Loading...
Searching...
No Matches
jacobi.py
Go to the documentation of this file.
1# ====================================================================
2# N U L A P A C K
3# U U L A P A C K
4# L L L A P A C K
5# A A A A P A C K
6# P P P P P A C K
7# A A A A A A C K
8# C C C C C C C K
9# K K K K K K K K
10#
11# This file is part of NULAPACK - NUmerical Linear Algebra PACKage
12#
13# Copyright (C) 2025 Saud Zahir
14#
15# NULAPACK is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# NULAPACK is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with NULAPACK. If not, see <https://www.gnu.org/licenses/>.
27# ====================================================================
28
29import _nulapack
30import numpy as np
31
32
33def jacobi(a, b, max_iter=1000, tol=1e-8, omega=1.0):
34 """
35 Solve the linear system ax = b using the Jacobi method.
36
37 Parameters
38 ----------
39 a : ndarray
40 Coefficient matrix (n x n)
41 b : ndarray
42 Right-hand side vector (n,)
43 max_iter : int, optional
44 Maximum number of iterations
45 tol : float, optional
46 Convergence tolerance
47 omega : float, optional
48 Relaxation factor
49
50 Returns
51 -------
52 x : ndarray
53 Solution vector
54 status : int
55 0 if converged, non-zero otherwise
56 """
57 a = np.ascontiguousarray(a)
58 b = np.asfortranarray(b)
59 n = a.shape[0]
60
61 x = np.zeros_like(b)
62
63 a_flat = a.ravel()
64
65 if np.issubdtype(a.dtype, np.floating):
66 if a.dtype == np.float32:
67 status = _nulapack.sgejsv(a_flat, b, x, max_iter, tol, omega, 0, n)
68 else: # float64
69 status = _nulapack.dgejsv(a_flat, b, x, max_iter, tol, omega, 0, n)
70 elif np.issubdtype(a.dtype, np.complexfloating):
71 if a.dtype == np.complex64:
72 status = _nulapack.cgejsv(a_flat, b, x, max_iter, tol, omega, 0, n)
73 else: # complex128
74 status = _nulapack.zgejsv(a_flat, b, x, max_iter, tol, omega, 0, n)
75 else:
76 raise TypeError(f"Unsupported array dtype: {a.dtype}")
77
78 return x, int(status) if status is not None else 0