Загрузка данных


import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize_scalar, root_scalar

# Функция для варианта 16
def f(x):
    return x**3 + 0.205*x**2 - 10.880*x - 1.469

# ----- 1. Метод деления пополам для минимума -----
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

a_min, b_min = 1.5, 2.2
x_min_dich = dichotomy_min(f, a_min, b_min)
y_min_dich = f(x_min_dich)
print(f"Метод деления пополам (минимум): x = {x_min_dich:.6f}, f(x) = {y_min_dich:.6f}")

# ----- 2. Метод золотого сечения для максимума -----
def golden_section_max(f, a, b, tol=1e-6):
    gr = (np.sqrt(5) - 1) / 2  # 0.618...
    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

a_max, b_max = -2.2, -1.7
x_max_gold = golden_section_max(f, a_max, b_max)
y_max_gold = f(x_max_gold)
print(f"Метод золотого сечения (максимум): x = {x_max_gold:.6f}, f(x) = {y_max_gold:.6f}")

# ----- 3. Проверка через SciPy -----
# Корни
root1 = root_scalar(f, bracket=[-3.5, -3.2], method='bisect').root
root2 = root_scalar(f, bracket=[-0.2, -0.1], method='bisect').root
root3 = root_scalar(f, bracket=[3.2, 3.3], method='bisect').root
print(f"\nКорни через scipy: x1 = {root1:.6f}, x2 = {root2:.6f}, x3 = {root3:.6f}")

# Экстремумы
res_min = minimize_scalar(f, bounds=[1.5, 2.2], method='bounded')
res_max = minimize_scalar(lambda x: -f(x), bounds=[-2.2, -1.7], method='bounded')
print(f"Минимум (scipy): x = {res_min.x:.6f}, f(x) = {res_min.fun:.6f}")
print(f"Максимум (scipy): x = {res_max.x:.6f}, f(x) = {-res_max.fun:.6f}")

# ----- 4. Построение графика -----
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='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True, linestyle='--', alpha=0.7)

# Отмечаем корни
plt.plot(root1, f(root1), 'ro', markersize=8, label='Корни')
plt.plot(root2, f(root2), 'ro', markersize=8)
plt.plot(root3, f(root3), 'ro', markersize=8)

# Отмечаем экстремумы
plt.plot(res_min.x, res_min.fun, 'g^', markersize=10, label='Минимум')
plt.plot(res_max.x, -res_max.fun, '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', dpi=150)
print("\nГрафик сохранён как 'final_plot.png'")
plt.show(block=True)   # блокирует окно до закрытия