Solingen

lab2

Mar 6th, 2026
46
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.38 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def parse_input(filename):
  4. """Parse input file with matrices A1, y1, A2, y2"""
  5. systems = []
  6. with open(filename, 'r') as f:
  7. lines = [line.strip() for line in f if line.strip()]
  8.  
  9. i = 0
  10. while i < len(lines):
  11. if lines[i].startswith('A'):
  12. # Read matrix A
  13. A = []
  14. i += 1
  15. while i < len(lines) and not lines[i].startswith('y') and not lines[i].startswith('A'):
  16. row = list(map(float, lines[i].split()))
  17. A.append(row)
  18. i += 1
  19. A = np.array(A)
  20. if i < len(lines) and lines[i].startswith('y'):
  21. # Read vector y
  22. i += 1
  23. y = np.array(list(map(float, lines[i].split())))
  24. i += 1
  25. systems.append((A, y))
  26.  
  27. return systems
  28.  
  29.  
  30. def iterative_solve(A, y, eps=1e-6, max_iter=1000):
  31. """
  32. Solve Ax = y using Jacobi iterative method.
  33. Transform to x = y' - B*x where:
  34. - Divide each equation i by A[i,i]
  35. - B[i,j] = A[i,j]/A[i,i] for i != j, B[i,i] = 0
  36. - y'[i] = y[i]/A[i,i]
  37. """
  38. n = len(y)
  39.  
  40. # Build B and y_tilde: x = y_tilde - B*x
  41. B = np.zeros((n, n))
  42. y_tilde = np.zeros(n)
  43.  
  44. for i in range(n):
  45. if abs(A[i, i]) < 1e-15:
  46. raise ValueError(f"Zero diagonal element at row {i}, cannot apply Jacobi method")
  47. y_tilde[i] = y[i] / A[i, i]
  48. for j in range(n):
  49. if i != j:
  50. B[i, j] = A[i, j] / A[i, i]
  51.  
  52. print("\n--- Матрица B (итерационная матрица) ---")
  53. print(np.array2string(B, precision=6, suppress_small=True))
  54.  
  55. # Operator norm of B (infinity norm = max row sum of abs values)
  56. norm_B_inf = np.max(np.sum(np.abs(B), axis=1))
  57. norm_B_1 = np.max(np.sum(np.abs(B), axis=0))
  58. norm_B_2 = np.linalg.norm(B, 2)
  59.  
  60. print(f"\nКоэффициент сжатия (норма B):")
  61. print(f" ||B||_inf (строчная) = {norm_B_inf:.6f}")
  62. print(f" ||B||_1 (столбцовая) = {norm_B_1:.6f}")
  63. print(f" ||B||_2 (спектральная) = {norm_B_2:.6f}")
  64.  
  65. # Choose the smallest norm for convergence check
  66. norm_B = min(norm_B_inf, norm_B_1, norm_B_2)
  67.  
  68. if norm_B >= 1:
  69. print(f"\n⚠️ Предупреждение: ||B|| = {norm_B:.6f} >= 1, метод может не сходиться!")
  70. else:
  71. print(f"\n✓ Метод сходится, используем ||B|| = {norm_B:.6f} < 1")
  72.  
  73. # Iterative process starting from x0 = 0
  74. x = np.zeros(n)
  75.  
  76. print(f"\n{'Итерация':<10} {'||x_new - x_old||':<22} Значения x")
  77. print("-" * 80)
  78.  
  79. for k in range(max_iter):
  80. # x_new = y_tilde - B * x (Jacobi: use old x for all components)
  81. x_new = y_tilde - B @ x
  82.  
  83. diff = np.linalg.norm(x_new - x, np.inf)
  84.  
  85. x_str = " ".join([f"{v:10.6f}" for v in x_new])
  86. print(f"{k+1:<10} {diff:<22.8e} [{x_str}]")
  87.  
  88. if diff < eps:
  89. print(f"\n✓ Сходимость достигнута за {k+1} итераций (||Δx|| = {diff:.2e} < ε = {eps:.2e})")
  90. return x_new, k+1, norm_B
  91.  
  92. x = x_new
  93.  
  94. print(f"\n⚠️ Достигнуто максимальное число итераций ({max_iter})")
  95. return x, max_iter, norm_B
  96.  
  97.  
  98. def verify_solution(A, y, x):
  99. """Verify solution by computing residual"""
  100. residual = A @ x - y
  101. print(f"\nПроверка (A*x - y): [{', '.join([f'{r:.2e}' for r in residual])}]")
  102. print(f"||A*x - y||_inf = {np.max(np.abs(residual)):.2e}")
  103.  
  104.  
  105. def main():
  106. filename = 'input22.txt'
  107.  
  108. # Ask user for epsilon
  109. try:
  110. eps = float(input("Введите точность ε (например, 1e-6): "))
  111. except ValueError:
  112. eps = 1e-6
  113. print(f"Неверный ввод, используется ε = {eps}")
  114.  
  115. print(f"\nТочность: ε = {eps}\n")
  116.  
  117. systems = parse_input(filename)
  118.  
  119. for idx, (A, y) in enumerate(systems, 1):
  120. print("\n" + "=" * 80)
  121. print(f"СИСТЕМА {idx}: A{idx} * x = y{idx}")
  122. print("=" * 80)
  123.  
  124. n = len(y)
  125. print(f"\nРазмерность системы: {n}x{n}")
  126.  
  127. print("\nМатрица A:")
  128. print(np.array2string(A, precision=4, suppress_small=True))
  129.  
  130. print("\nВектор y:")
  131. print(y)
  132.  
  133. try:
  134. x_sol, iters, norm_B = iterative_solve(A, y, eps=eps)
  135.  
  136. print(f"\n{'='*40}")
  137. print(f"ОТВЕТ (система {idx}):")
  138. for i, xi in enumerate(x_sol):
  139. print(f" x{i+1} = {xi:.8f}")
  140.  
  141. verify_solution(A, y, x_sol)
  142.  
  143. # Cross-check with numpy
  144. x_exact = np.linalg.solve(A, y)
  145. print(f"\nТочное решение (numpy.linalg.solve):")
  146. for i, xi in enumerate(x_exact):
  147. print(f" x{i+1} = {xi:.8f}")
  148.  
  149. print(f"\nПогрешность итерационного решения: {np.max(np.abs(x_sol - x_exact)):.2e}")
  150.  
  151. except ValueError as e:
  152. print(f"\nОшибка: {e}")
  153.  
  154.  
  155. if __name__ == "__main__":
  156. main()
Advertisement
Comments
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment