1"""Практическая работа 9: методы Якоби и Зейделя."""23import numpy as np456A = np.array(7 [8 [4, -1, 1],9 [1, 5, 1],10 [9, 32, 84],11 ],12 dtype=float,13)14B = np.array([-21, -12, -1859], dtype=float)151617def jacobi(18 matrix: np.ndarray,19 vector: np.ndarray,20 tolerance: float = 1e-10,21 max_iterations: int = 10_000,22) -> tuple[np.ndarray, list[np.ndarray]]:23 diagonal = np.diag(matrix)24 remainder = matrix - np.diagflat(diagonal)25 current = np.zeros_like(vector)26 history = [current.copy()]2728 for _ in range(max_iterations):29 updated = (vector - remainder @ current) / diagonal30 history.append(updated.copy())31 if np.linalg.norm(updated - current, ord=np.inf) < tolerance:32 return updated, history33 current = updated3435 raise RuntimeError("Метод Якоби не сошёлся за заданное число итераций")363738def gauss_seidel(39 matrix: np.ndarray,40 vector: np.ndarray,41 tolerance: float = 1e-10,42 max_iterations: int = 10_000,43) -> tuple[np.ndarray, list[np.ndarray]]:44 current = np.zeros_like(vector)45 history = [current.copy()]4647 for _ in range(max_iterations):48 previous = current.copy()49 for row in range(len(vector)):50 before = matrix[row, :row] @ current[:row]51 after = matrix[row, row + 1 :] @ previous[row + 1 :]52 current[row] = (vector[row] - before - after) / matrix[row, row]53 history.append(current.copy())54 if np.linalg.norm(current - previous, ord=np.inf) < tolerance:55 return current, history5657 raise RuntimeError("Метод Зейделя не сошёлся за заданное число итераций")585960def print_result(name: str, solution: np.ndarray, history: list[np.ndarray]) -> None:61 print(f"\n{name}")62 for number, values in enumerate(history[1:4], start=1):63 print(f"Итерация {number}: {values}")64 print(f"Сошёлся за {len(history) - 1} итераций: {solution}")65 print(f"Невязка ||Ax-b||∞ = {np.linalg.norm(A @ solution - B, ord=np.inf):.3e}")666768def main() -> None:69 exact = np.linalg.solve(A, B)70 jacobi_solution, jacobi_history = jacobi(A, B)71 seidel_solution, seidel_history = gauss_seidel(A, B)7273 print(f"Точное решение NumPy: {exact}")74 print_result("Метод Якоби", jacobi_solution, jacobi_history)75 print_result("Метод Зейделя", seidel_solution, seidel_history)767778if __name__ == "__main__":79 main()