Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "Р3213/molchanov_413015/lab1/Qt-Math-App"]
path = Р3213/molchanov_413015/lab1/Qt-Math-App
url = https://github.com/fefumo/Qt-Math-App.git
1 change: 1 addition & 0 deletions Р3213/molchanov_413015/lab1/Qt-Math-App
Submodule Qt-Math-App added at 9d3140
Binary file not shown.
32 changes: 32 additions & 0 deletions Р3213/molchanov_413015/lab2/functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import math

def f1(x):
return x**3 - x - 2

def f2(x):
return math.cos(x) - x

def f3(x):
return math.exp(x) - 2

def f4(x):
return x**2 - 2

def f5(x):
return math.sin(x) - 0.5

def get_functions():
return {
"1": ("x^3 - x - 2", f1),
"2": ("cos(x) - x", f2),
"3": ("exp(x) - 2", f3),
"4": ("x^2 - 2", f4),
"5": ("sin(x) - 0.5", f5),
}

def get_function_choice(functions):
print("Доступные функции:")
for key, (desc, _) in functions.items():
print(f"{key}: {desc}")
choice = input("Выберите номер функции: ").strip()
return functions[choice][1]
22 changes: 22 additions & 0 deletions Р3213/molchanov_413015/lab2/input_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
def get_user_input():
source = input("Ввод из файла или с клавиатуры? (file/keyboard): ").strip().lower()
if source == "file":
filename = input("Введите имя файла: ").strip()
with open(filename, encoding="utf-8") as f:
parts = f.read().split()
a, b, eps = map(float, parts[:3])
else:
a = float(input("Введите левую границу интервала a: "))
b = float(input("Введите правую границу интервала b: "))
eps = float(input("Введите точность вычисления eps: "))
return a, b, eps

def get_output_choice():
return input("Вывести результат на экран или в файл? (screen/file): ").strip().lower()

def get_function_choice(functions):
print("Доступные функции:")
for key, (desc, _) in functions.items():
print(f"{key}: {desc}")
choice = input("Выберите номер функции: ").strip()
return functions[choice][1]
1 change: 1 addition & 0 deletions Р3213/molchanov_413015/lab2/inputs.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-2 2 0.01
121 changes: 121 additions & 0 deletions Р3213/molchanov_413015/lab2/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import numpy as np
from functions import get_functions
from input_handler import get_user_input, get_function_choice, get_output_choice
from verification import verify_interval, find_initial_guess
from methods.chord import chord_method
from methods.secant import secant_method
from methods.simple_iteration import simple_iteration_method
from systems.systems import get_systems
from systems.newton_system import newton_system
import matplotlib.pyplot as plt

def plot_scalar_function(func, a, b, root=None):
x_vals = np.linspace(a, b, 400)
y_vals = [func(x) for x in x_vals]

plt.axhline(0, color='gray', linestyle='--')
plt.plot(x_vals, y_vals, label='f(x)')
if root is not None:
plt.scatter(root, func(root), color='red', label='Корень')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('График функции')
plt.legend()
plt.grid(True)
plt.show()

def main():
mode = input("Выберите режим: 'scalar' (одно уравнение) или 'system' (система): ").strip().lower()

if mode == "system":
systems = get_systems()
print("Доступные системы:")
for key, s in systems.items():
print(f"{key}: {s['desc']}")
choice = input("Выберите номер системы: ").strip()
system = systems[choice]
F, J = system["func"], system["jacobian"]
default_guess = system["guess"]

print(f"Рекомендуемое начальное приближение: {default_guess}")
use_default = input("Использовать рекомендованное? (y/n): ").strip().lower()
if use_default == "y":
x0 = default_guess
else:
x0 = list(map(float, input("Введите начальные приближения x1 и x2 через пробел: ").split()))

eps = float(input("Введите точность eps: "))

result = newton_system(F, J, x0, eps)

print(f"Решение: x = {result['x']}")
print(f"Итераций: {result['iterations']}")
print(f"Вектор невязки (норма): {result['residual']:.3e}")

for i, e in enumerate(result['errors']):
print(f"Погрешности на итерации {i+1}: {e}")

# График
x_vals = np.linspace(-3, 3, 400)
y_vals = np.linspace(-3, 3, 400)
X, Y = np.meshgrid(x_vals, y_vals)

if choice == "1":
Z1 = X**2 + Y**2 - 4
Z2 = X - Y
elif choice == "2":
Z1 = X**2 - Y - 1
Z2 = X + Y**2 - 3
elif choice == "3":
Z1 = X**2 + Y**2 - 1
Z2 = X**3 - Y + 0.5
else:
Z1 = Z2 = None

if Z1 is not None and Z2 is not None:
plt.contour(X, Y, Z1, [0], colors='blue')
plt.contour(X, Y, Z2, [0], colors='red')
plt.scatter(*result['x'], color='green')
plt.title("Графики системы и найденный корень")
plt.xlabel("x1")
plt.ylabel("x2")
plt.grid(True)
plt.axis('equal')
plt.show()

else:
functions = get_functions()
func = get_function_choice(functions)
method = input("Выберите метод (chord/secant/iteration): ").strip().lower()
a, b, eps = get_user_input()

if not verify_interval(func, a, b):
print("На заданном интервале нет корней или их несколько.")
return

x0 = find_initial_guess(func, a, b)

if method == "chord":
result = chord_method(func, a, b, eps)
elif method == "secant":
result = secant_method(func, a, b, eps)
elif method == "iteration":
result = simple_iteration_method(func, a, b, eps)
else:
print("Неизвестный метод.")
return

output_choice = get_output_choice()
if output_choice == "screen":
print("Результат:")
print(result)
else:
with open("result.txt", "w", encoding="utf-8") as f:
f.write(str(result))
print("Результат записан в result.txt")

# Показываем график после вывода
plot_scalar_function(func, a, b, root=result['root'])

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions Р3213/molchanov_413015/lab2/result.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{'method': 'Метод хорд', 'a': 1.5213797068045676, 'b': 2.0, 'epsilon': 0.01, 'root': 1.5213797068045676, 'f(root)': 0.0, 'iterations': 10000}
Binary file not shown.
Binary file not shown.
38 changes: 38 additions & 0 deletions Р3213/molchanov_413015/lab2/systems/newton_system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import numpy as np

def newton_system(F, J, x0, eps=1e-6, max_iter=100):
x = np.array(x0, dtype=float)
iter_count = 0
errors = []

while iter_count < max_iter:
Fx = np.array(F(x))
Jx = np.array(J(x))

norm_F = np.linalg.norm(Fx)
if norm_F < eps:
break

try:
dx = np.linalg.solve(Jx, -Fx)
except np.linalg.LinAlgError:
print("Якобиан необратим.")
break

x_new = x + dx
error = np.linalg.norm(dx)
errors.append(error)

if error < eps:
x = x_new
break

x = x_new
iter_count += 1

return {
"x": x.tolist(),
"iterations": iter_count,
"errors": errors,
"residual": np.linalg.norm(F(x))
}
63 changes: 63 additions & 0 deletions Р3213/molchanov_413015/lab2/systems/systems.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
def system1(x):
x1, x2 = x
return [
x1**2 + x2**2 - 4,
x1 - x2
]

def jacobian1(x):
x1, x2 = x
return [
[2 * x1, 2 * x2],
[1, -1]
]

def system2(x):
x1, x2 = x
return [
x1**2 - x2 - 1,
x1 + x2**2 - 3
]

def jacobian2(x):
x1, x2 = x
return [
[2 * x1, -1],
[1, 2 * x2]
]

def system3(x):
x1, x2 = x
return [
x1**2 + x2**2 - 1,
x1**3 - x2 + 0.5
]

def jacobian3(x):
x1, x2 = x
return [
[2 * x1, 2 * x2],
[3 * x1**2, -1]
]

def get_systems():
return {
"1": {
"desc": "x^2 + y^2 = 4; x = y",
"func": system1,
"jacobian": jacobian1,
"guess": [1.0, 1.0]
},
"2": {
"desc": "x^2 - y = 1; x + y^2 = 3",
"func": system2,
"jacobian": jacobian2,
"guess": [1.0, 1.0]
},
"3": {
"desc": "x^2 + y^2 = 1; x^3 - y = -0.5",
"func": system3,
"jacobian": jacobian3,
"guess": [0.5, 0.5]
}
}
8 changes: 8 additions & 0 deletions Р3213/molchanov_413015/lab2/verification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def verify_interval(func, a, b):
try:
return func(a) * func(b) < 0
except:
return False

def find_initial_guess(func, a, b):
return a if abs(func(a)) < abs(func(b)) else b
Binary file not shown.
Loading