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


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

# 1. Функция варианта 20
def f(x):
    return np.sqrt(1 - x**2)

a, b = 0, 0.5
n = 10
h = (b - a) / n
x_curve = np.linspace(a, b, 200)
y_curve = f(x_curve)

fig, axes = plt.subplots(2, 3, figsize=(16, 10))
axes = axes.flatten()

# Настройки стиля
line_style = {'color': 'red', 'lw': 2, 'label': 'f(x)'}
fill_style = {'facecolor': 'blue', 'alpha': 0.15, 'edgecolor': 'darkblue', 'lw': 0.5}

# --- 1. ЛПР (Левые прямоугольники) ---
ax = axes[0]
ax.plot(x_curve, y_curve, **line_style)
for i in range(n):
    xi = a + i * h
    ax.add_patch(Rectangle((xi, 0), h, f(xi), **fill_style))
ax.set_title(f"ЛПР (Левые), n={n}\nВысота по левому краю")

# --- 2. ППР (Правые прямоугольники) ---
ax = axes[1]
ax.plot(x_curve, y_curve, **line_style)
for i in range(n):
    xi = a + i * h
    ax.add_patch(Rectangle((xi, 0), h, f(xi + h), **fill_style))
ax.set_title(f"ППР (Правые), n={n}\nВысота по правому краю")

# --- 3. СПР (Средние прямоугольники) ---
ax = axes[2]
ax.plot(x_curve, y_curve, **line_style)
for i in range(n):
    xi = a + i * h
    xm = xi + h/2
    ax.add_patch(Rectangle((xi, 0), h, f(xm), **fill_style))
    ax.scatter(xm, f(xm), color='black', s=5, zorder=3) # Точка замера
ax.set_title(f"СПР (Средние), n={n}\nЗамер в центре интервала")

# --- 4. ТР (Трапеции) ---
ax = axes[3]
ax.plot(x_curve, y_curve, **line_style)
for i in range(n):
    xi = a + i * h
    ax.fill([xi, xi, xi+h, xi+h], [0, f(xi), f(xi+h), 0], **fill_style)
ax.set_title(f"ТР (Трапеции), n={n}\nЛинейная аппроксимация")

# --- 5. СИМП (Симпсон) ---
ax = axes[4]
ax.plot(x_curve, y_curve, **line_style)
for i in range(0, n, 2):
    x_nodes = [a+i*h, a+(i+1)*h, a+(i+2)*h]
    y_nodes = [f(x) for x in x_nodes]
    p = np.polyfit(x_nodes, y_nodes, 2)
    x_p = np.linspace(x_nodes[0], x_nodes[2], 20)
    ax.fill_between(x_p, 0, np.polyval(p, x_p), **fill_style)
    ax.scatter(x_nodes, y_nodes, color='black', s=5, zorder=3)
ax.set_title(f"СИМП (Симпсон), n={n}\nПараболическая аппроксимация")

# --- 6. ММК (Монте-Карло) ---
ax = axes[5]
ax.plot(x_curve, y_curve, **line_style)
n_mc = 400 # Умеренное кол-во точек для n=10 эквивалента
x_rand = np.random.uniform(a, b, n_mc)
y_rand = np.random.uniform(0, 1, n_mc)
under = y_rand < f(x_rand)
ax.scatter(x_rand[under], y_rand[under], s=2, c='green', alpha=0.5)
ax.scatter(x_rand[~under], y_rand[~under], s=2, c='red', alpha=0.2)
ax.set_title(f"ММК, n={n_mc}\nСлучайные испытания")

# Общая доводка
for ax in axes:
    ax.set_xlim(a-0.02, b+0.02)
    ax.set_ylim(0, 1.05)
    ax.grid(True, alpha=0.1)

plt.tight_layout()
plt.show()