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


import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as optim
from mpl_toolkits.mplot3d import Axes3D

def f(x):
    return x[0]**2 + x[1]**2 + 1.1*x[0]*x[1] + x[0] - x[1] + 1.1

def grad(x):
    return [2*x[0] + 1.1*x[1] + 1,
            2*x[1] + 1.1*x[0] - 1]

# Получаем точки минимумов
res_nm = optim.minimize(f, x0=[1, 0], method='Nelder-Mead')
res_bfgs = optim.minimize(f, jac=grad, x0=[1, 0], method='BFGS')

# Сетка для графиков
xx = np.linspace(-2.5, 2.5, 50)
X, Y = np.meshgrid(xx, xx)
Z = X**2 + Y**2 + 1.1*X*Y + X - Y + 1.1

# Фигура: 2 строки, 1 колонка
fig = plt.figure(figsize=(8, 10))

# === Верхний график: 3D поверхность ===
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.plot_surface(X, Y, Z, cmap='viridis', alpha=0.8)
ax1.scatter(res_nm.x[0], res_nm.x[1], f(res_nm.x), color='red', s=80, label='Nelder-Mead')
ax1.scatter(res_bfgs.x[0], res_bfgs.x[1], f(res_bfgs.x), color='blue', s=80, marker='^', label='BFGS')
ax1.legend()
ax1.set_title('3D поверхность функции (вариант 16)')
ax1.set_xlabel('x1')
ax1.set_ylabel('x2')
ax1.set_zlabel('f(x1, x2)')

# === Нижний график: линии уровня и градиенты ===
plt.subplot(2, 1, 2)
plt.contour(X, Y, Z, levels=20, cmap='viridis')
py, px = np.gradient(Z)
plt.quiver(X, Y, px, py, alpha=0.6)
plt.plot(res_nm.x[0], res_nm.x[1], 'ro', markersize=8, label='Nelder-Mead')
plt.plot(res_bfgs.x[0], res_bfgs.x[1], 'b^', markersize=8, label='BFGS')
plt.legend()
plt.title('Линии уровня и градиенты')
plt.xlabel('x1')
plt.ylabel('x2')
plt.axis('equal')
plt.grid(alpha=0.3)

plt.tight_layout()
plt.show()