import numpy as np
import matplotlib.pyplot as plt
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=(15, 10))
axes = axes.flatten()
# 1. Левые прямоугольники
axes[0].plot(x_curve, y_curve, 'r')
for i in range(n):
xi = a + i * h
axes[0].add_patch(plt.Rectangle((xi, 0), h, f(xi), edgecolor='b', alpha=0.3))
axes[0].set_title("ЛПР (Левые)")
# 2. Правые прямоугольники
axes[1].plot(x_curve, y_curve, 'r')
for i in range(n):
xi = a + i * h
axes[1].add_patch(plt.Rectangle((xi, 0), h, f(xi + h), edgecolor='b', alpha=0.3))
axes[1].set_title("ППР (Правые)")
# 3. Средние прямоугольники
axes[2].plot(x_curve, y_curve, 'r')
for i in range(n):
xi = a + i * h
axes[2].add_patch(plt.Rectangle((xi, 0), h, f(xi + h/2), edgecolor='b', alpha=0.3))
axes[2].set_title("СПР (Средние)")
# 4. Трапеции
axes[3].plot(x_curve, y_curve, 'r')
for i in range(n):
xi = a + i * h
axes[3].fill([xi, xi, xi+h, xi+h], [0, f(xi), f(xi+h), 0], 'b', edgecolor='b', alpha=0.3)
axes[3].set_title("ТР (Трапеции)")
# 5. Симпсон (Параболы)
axes[4].plot(x_curve, y_curve, 'r')
for i in range(0, n, 2):
x_p = np.linspace(a + i*h, a + (i+2)*h, 20)
# Построение параболы через 3 точки
x3 = [a+i*h, a+(i+1)*h, a+(i+2)*h]
y3 = [f(x) for x in x3]
poly = np.polyfit(x3, y3, 2)
axes[4].fill_between(x_p, 0, np.polyval(poly, x_p), color='b', alpha=0.3, edgecolor='b')
axes[4].set_title("СИМП (Симпсона)")
# 6. Монте-Карло
axes[5].plot(x_curve, y_curve, 'r')
x_rand = np.random.uniform(a, b, 200)
y_rand = np.random.uniform(0, 1, 200)
under = y_rand < f(x_rand)
axes[5].scatter(x_rand[under], y_rand[under], s=5, c='g')
axes[5].scatter(x_rand[~under], y_rand[~under], s=5, c='gray', alpha=0.5)
axes[5].set_title("ММК (Монте-Карло)")
for ax in axes:
ax.set_xlim(a-0.05, b+0.05)
ax.set_ylim(0, 1.1)
ax.grid(True, alpha=0.2)
plt.tight_layout()
plt.show()