import numpy as np
import matplotlib.pyplot as plt
import math
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
# Аналитический эталон для 20 варианта (для 16 нулей в Δ)
TRUE_VAL = math.pi/12 + math.sqrt(3)/8
# --- 2. Функции методов ---
def get_simpson_res(n_val):
if n_val % 2 != 0: n_val += 1
h_s = (b - a) / n_val
x = np.linspace(a, b, n_val + 1)
y = f(x)
return (h_s/3) * (y[0] + y[-1] + 4*np.sum(y[1:-1:2]) + 2*np.sum(y[2:-2:2]))
# --- 3. Визуализация 6 методов ---
fig, axes = plt.subplots(2, 3, figsize=(16, 11))
axes = axes.flatten()
x_curve = np.linspace(a, b, 200)
for idx, name in enumerate(["ЛПР", "ППР", "СПР", "ТР", "СИМП", "ММК"]):
ax = axes[idx]
ax.plot(x_curve, f(x_curve), color='#0055ff', lw=2.5, zorder=10) # Яркая синяя линия
if name == "ЛПР":
for i in range(n):
ax.add_patch(Rectangle((a+i*h, 0), h, f(a+i*h), facecolor='#add8e6', alpha=0.6, edgecolor='black', lw=0.7))
elif name == "ППР":
for i in range(n):
ax.add_patch(Rectangle((a+i*h, 0), h, f(a+(i+1)*h), facecolor='#add8e6', alpha=0.6, edgecolor='black', lw=0.7))
elif name == "СПР":
for i in range(n):
xm = a + i*h + h/2
ax.add_patch(Rectangle((a+i*h, 0), h, f(xm), facecolor='#add8e6', alpha=0.6, edgecolor='black', lw=0.7))
elif name == "ТР":
for i in range(n):
xi = a + i*h
ax.fill([xi, xi, xi+h, xi+h], [0, f(xi), f(xi+h), 0], color='#add8e6', alpha=0.6, edgecolor='black', lw=0.7)
elif name == "СИМП":
for i in range(0, n, 2):
x_pts = [a+i*h, a+(i+1)*h, a+(i+2)*h]
y_pts = f(np.array(x_pts))
p = np.polyfit(x_pts, y_pts, 2)
x_range = np.linspace(x_pts[0], x_pts[2], 30)
ax.fill_between(x_range, 0, np.polyval(p, x_range), color='#add8e6', alpha=0.6, edgecolor='black', lw=0.7)
ax.vlines(x_pts, 0, y_pts, color='black', lw=0.5, alpha=0.3)
elif name == "ММК":
# Имитация наложенных столбиков как на фото
n_mc = 2000
xr = np.random.uniform(a, b, n_mc)
yr = np.random.uniform(0, 1, n_mc)
inside = xr[yr < f(xr)]
# Рисуем основной слой столбиков
ax.hist(inside, bins=10, range=(a, b), color='red', alpha=0.3, edgecolor='darkred', rwidth=0.85)
# Добавляем "шум" вторым слоем для эффекта наложения
ax.hist(inside, bins=15, range=(a, b), color='red', alpha=0.15, rwidth=0.95)
ax.set_title(f"Метод: {name}")
ax.set_xlim(a-0.02, b+0.02)
ax.set_ylim(0, 1.1)
ax.grid(True, ls=':', alpha=0.6)
plt.tight_layout()
# --- 4. Вывод таблицы в консоль (научный вид) ---
print(f"Аналитическое S = {TRUE_VAL:.18f}")
print("="*95)
n_final = 1000
s_simpson = get_simpson_res(n_final)
delta = abs(TRUE_VAL - s_simpson)
sigma = (delta / TRUE_VAL) * 100
print(f"| n = {n_final:<8} | Ŝ = {s_simpson:.18f} | Δ = {delta:.2e} | δ = {sigma:.16f}% |")
print("="*95)
plt.show()