-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjacobi_method.py
More file actions
84 lines (64 loc) · 2.69 KB
/
jacobi_method.py
File metadata and controls
84 lines (64 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import numpy as np
from PyQt6.QtWidgets import QMainWindow, QTableWidgetItem, QMessageBox
from ui.jacobi_method import Ui_JacobiMethod
class JacobiMethodApp(QMainWindow, Ui_JacobiMethod):
def __init__(self):
super().__init__()
self.setupUi(self)
self.size_spinbox.setValue(3)
self.iterations_spinbox.setValue(1000)
self.size_spinbox.valueChanged.connect(self.update_table_size)
self.solve_button.clicked.connect(self.solve_system)
self.update_table_size()
def update_table_size(self):
n = self.size_spinbox.value()
self.coeff_table.setRowCount(n)
self.coeff_table.setColumnCount(n + 1)
self.initial_guess_table.setRowCount(1)
self.initial_guess_table.setColumnCount(n)
for i in range(n):
for j in range(n + 1):
self.coeff_table.setItem(i, j, QTableWidgetItem(str(0)))
self.initial_guess_table.setItem(0, i, QTableWidgetItem("0"))
def solve_system(self):
try:
n = self.size_spinbox.value()
a = np.zeros((n, n))
b = np.zeros(n)
for i in range(n):
for j in range(n):
a[i, j] = float(self.coeff_table.item(i, j).text())
b[i] = float(self.coeff_table.item(i, n).text())
x0 = np.zeros(n)
for j in range(n):
x0[j] = float(self.initial_guess_table.item(0, j).text())
max_iter = self.iterations_spinbox.value()
solution = self.jacobi_method(a, b, x0, 1e-6, max_iter)
self.solution_table.setRowCount(1)
self.solution_table.setColumnCount(n)
if solution != "no conv":
for j in range(n):
self.solution_table.setItem(0, j, QTableWidgetItem(f"{solution[j]:.6f}"))
else:
for j in range(n):
self.solution_table.setItem(0, j, QTableWidgetItem("No conv"))
except Exception as e:
self.show_error(f"Unexpected Error: {e}")
def jacobi_method(self, a, b, x0, tol=1e-6, max_iter=1000):
n = len(b)
x = x0
for _ in range(max_iter):
x_new = np.zeros_like(x)
for i in range(n):
summation = sum(a[i][j] * x[j] for j in range(n) if j != i)
x_new[i] = (b[i] - summation) / a[i][i]
if np.linalg.norm(x_new - x, ord=np.inf) < tol:
return x_new
x = x_new
return "no conv"
def show_error(self, message):
msg = QMessageBox()
msg.setIcon(QMessageBox.Icon.Critical)
msg.setWindowTitle("Error")
msg.setText(message)
msg.exec()