import numpy as np
import matplotlib.pyplot as plt
# Функция для варианта 16
def f(x):
return x**3 + 0.205*x**2 - 10.880*x - 1.469
# ---------- 1. Метод деления пополам для минимума (как в программе 2) ----------
def dichotomy_min(f, a, b, tol=1e-6, delta=1e-5):
while (b - a) > tol:
mid = (a + b) / 2
x1 = mid - delta
x2 = mid + delta
if f(x1) < f(x2):
b = x2
else:
a = x1
return (a + b) / 2
# ---------- 2. Метод золотого сечения для максимума ----------
def golden_section_max(f, a, b, tol=1e-6):
gr = (np.sqrt(5) - 1) / 2
x1 = b - gr * (b - a)
x2 = a + gr * (b - a)
f1 = f(x1)
f2 = f(x2)
while (b - a) > tol:
if f1 > f2:
b = x2
x2 = x1
f2 = f1
x1 = b - gr * (b - a)
f1 = f(x1)
else:
a = x1
x1 = x2
f1 = f2
x2 = a + gr * (b - a)
f2 = f(x2)
return (a + b) / 2
# ---------- 3. Поиск корней методом половинного деления (как в программе 2) ----------
def bisection_root(f, a, b, tol=1e-6):
if f(a) * f(b) >= 0:
raise ValueError("На отрезке нет корня или чётное количество корней")
while (b - a) / 2 > tol:
c = (a + b) / 2
if f(c) == 0:
return c
if f(a) * f(c) < 0:
b = c
else:
a = c
return (a + b) / 2
# ---------- Вычисляем всё ----------
print("Поиск минимума методом деления пополам...")
x_min = dichotomy_min(f, 1.5, 2.2)
y_min = f(x_min)
print(f"Минимум: x = {x_min:.6f}, f(x) = {y_min:.6f}")
print("Поиск максимума методом золотого сечения...")
x_max = golden_section_max(f, -2.2, -1.7)
y_max = f(x_max)
print(f"Максимум: x = {x_max:.6f}, f(x) = {y_max:.6f}")
print("Поиск корней методом половинного деления...")
root1 = bisection_root(f, -3.5, -3.2)
root2 = bisection_root(f, -0.2, -0.1)
root3 = bisection_root(f, 3.2, 3.3)
print(f"Корни: x1 = {root1:.6f}, x2 = {root2:.6f}, x3 = {root3:.6f}")
# ---------- Построение графика ----------
x_plot = np.linspace(-5, 5, 500)
y_plot = f(x_plot)
plt.figure(figsize=(10, 6))
plt.plot(x_plot, y_plot, 'b-', linewidth=1.5, label='f(x)')
plt.axhline(0, color='k', linewidth=0.5)
plt.axvline(0, color='k', linewidth=0.5)
plt.grid(True, linestyle='--', alpha=0.7)
# Отмечаем корни
plt.plot(root1, f(root1), 'ro', markersize=8)
plt.plot(root2, f(root2), 'ro', markersize=8)
plt.plot(root3, f(root3), 'ro', markersize=8)
# Отмечаем экстремумы
plt.plot(x_min, y_min, 'g^', markersize=10, label='Минимум')
plt.plot(x_max, y_max, 'mv', markersize=10, label='Максимум')
plt.title('Функция f(x) = x³ + 0.205x² - 10.880x - 1.469')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.tight_layout()
# Сохраняем и показываем
plt.savefig('final_plot.png')
print("\nГрафик сохранён как 'final_plot.png'")
plt.show()