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


import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad



def f(x):
    return np.sqrt(1 - x ** 2)


a, b = 0, 0.5
n_values = [10, 100, 1000]


true_val, _ = quad(f, a, b)



def left_rect(f, a, b, n):
    h = (b - a) / n
    return h * sum(f(a + i * h) for i in range(n))


def right_rect(f, a, b, n):
    h = (b - a) / n
    return h * sum(f(a + (i + 1) * h) for i in range(n))


def mid_rect(f, a, b, n):
    h = (b - a) / n
    return h * sum(f(a + h / 2 + i * h) for i in range(n))


def trapezoid(f, a, b, n):
    h = (b - a) / n
    return h * (0.5 * (f(a) + f(b)) + sum(f(a + i * h) for i in range(1, n)))


def simpson(f, a, b, n):
    if n % 2 != 0: n += 1
    h = (b - a) / n
    x = np.linspace(a, b, n + 1)
    y = f(x)
    return h / 3 * (y[0] + y[-1] + 4 * np.sum(y[1:-1:2]) + 2 * np.sum(y[2:-2:2]))


def monte_carlo(f, a, b, n):
    x_rand = np.random.uniform(a, b, n)
    return (b - a) * np.mean(f(x_rand))


methods = {
    "ЛПР": left_rect,
    "ППР": right_rect,
    "СПР": mid_rect,
    "ТР": trapezoid,
    "СИМП": simpson,
    "ММК": monte_carlo
}


print(f"Истинная площадь (scipy.quad): {true_val:.10f}\n")
print(f"{'n':<7} | {'Метод':<7} | {'Результат':<12} | {'Абс. погр.':<11} | {'Относ. %'}")
print("-" * 72)

for n in n_values:
    for name, func in methods.items():
        res = func(f, a, b, n)
        abs_err = abs(true_val - res)
        rel_err_pct = (abs_err / true_val) * 100


        print(f"{n:<7} | {name:<7} | {res:.8f} | {abs_err:.2e} | {rel_err_pct:.4f}")
    print("-" * 72)


x_plot = np.linspace(a - 0.1, b + 0.1, 400)
plt.figure(figsize=(10, 5))
plt.plot(x_plot, f(x_plot), 'r', lw=2, label='f(x) = $\sqrt{1-x^2}$')
plt.fill_between(np.linspace(a, b, 100), f(np.linspace(a, b, 100)), color='blue', alpha=0.2, label='Истинная площадь')
plt.title('График функции (Вариант 20)')
plt.axhline(0, color='black', lw=1)
plt.axvline(0, color='black', lw=1)
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()