-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot_finding_comparison.py
More file actions
84 lines (64 loc) · 2.63 KB
/
root_finding_comparison.py
File metadata and controls
84 lines (64 loc) · 2.63 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, QMessageBox
from ui.root_finding_comparison import Ui_RootFindingComparison
class RootFindingComparisonApp(QMainWindow, Ui_RootFindingComparison):
def __init__(self):
super().__init__()
self.setupUi(self)
self.calculate_button.clicked.connect(self.calculate_root)
def calculate_root(self):
try:
expr = self.function_text_edit.toPlainText()
a = float(self.xstart_text_edit.toPlainText())
b = float(self.xend_text_edit.toPlainText())
def f(x):
return eval(expr, {"x": x, "np": np})
root, iterations = None, 0
if self.bisection_radio.isChecked():
root, iterations = self.bisection_method(f, a, b)
elif self.secant_radio.isChecked():
root, iterations = self.secant_method(f, a, b)
if root is not None:
exact_root = np.sqrt(5)
relative_error = abs((root - exact_root) / exact_root) * 100
self.root_value_label.setText(f"{root:.8f}")
self.iterations_label.setText(str(iterations))
self.exact_root_label.setText(f"{exact_root:.8f}")
self.error_label.setText(f"{relative_error:.8f}%")
else:
self.root_value_label.setText("Error")
self.iterations_label.setText("Error")
self.exact_root_label.setText("Error")
self.error_label.setText("Error")
except Exception as e:
self.show_error(f"Unexpected Error: {e}")
def bisection_method(self, f, a, b, tol=1e-6):
if f(a) * f(b) >= 0:
print("Invalid initial values. f(a) and f(b) must be of different signs")
return None, 0
iterations = 0
midpoint = (a + b) / 2
while abs(f(midpoint)) > tol:
iterations += 1
if f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
midpoint = (a + b) / 2
return midpoint, iterations
def secant_method(self, f, a, b, tol=1e-6):
iterations = 0
x0, x1 = a, b
while abs(f(x1)) > tol:
iterations += 1
if f(x1) - f(x0) == 0:
return None, iterations
x_new = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
x0, x1 = x1, x_new
return x1, iterations
def show_error(self, message):
msg = QMessageBox()
msg.setIcon(QMessageBox.Icon.Critical)
msg.setWindowTitle("Error")
msg.setText(message)
msg.exec()