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


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec


def f(x):
    """Исходная функция: f(x) = arcsin(x)/sqrt(1-x^2) - 1/2"""
    return np.arcsin(x) / np.sqrt(1 - x**2) - 0.5


def chord_method(a, b, eps=1e-6, max_iter=100):
    """
    Метод хорд (метод ложного положения)
    """
    if f(a) * f(b) >= 0:
        print(f"ВНИМАНИЕ: f(a)*f(b) = {f(a) * f(b)}")
        print("Функция может не иметь корней на этом интервале")

    iterations = []
    x_prev = a
    fa = f(a)

    for i in range(max_iter):
        fb = f(b)

        # Формула метода хорд
        x = a - fa * (b - a) / (fb - fa)
        fx = f(x)

        # Сохраняем данные для визуализации
        iterations.append({
            'iter': i + 1,
            'a': a,
            'b': b,
            'x': x,
            'f(x)': fx,
            'error': abs(x - x_prev) if i > 0 else abs(b - a)
        })

        # Проверка на сходимость
        if abs(fx) < eps or abs(x - x_prev) < eps:
            break

        # Выбор нового интервала
        if fa * fx < 0:
            b = x
        else:
            a = x
            fa = fx

        x_prev = x

    return x, iterations


# ==================== ПАРАМЕТРЫ ====================
a, b = -0.5, 0.8
eps = 1e-14

print("=" * 80)
print("РЕШЕНИЕ УРАВНЕНИЯ МЕТОДОМ ХОРД - ВАРИАНТ 22")
print("=" * 80)
print(f"Уравнение: f(x) = arcsin(x)/sqrt(1-x^2) - 1/2 = 0")
print(f"Интервал: [{a}, {b}]")
print(f"Точность: {eps}")
print("=" * 80)

# ==================== РЕШЕНИЕ ====================
try:
    root, iterations = chord_method(a, b, eps)

    print("\nИТЕРАЦИИ:")
    print("-" * 80)
    print(f"{'№':<4} {'a':<12} {'b':<12} {'x':<12} {'f(x)':<15} {'|Δx|':<12}")
    print("-" * 80)

    for it in iterations:
        print(f"{it['iter']:<4} {it['a']:<12.6f} {it['b']:<12.6f} "
              f"{it['x']:<12.6f} {it['f(x)']:<15.6e} {it['error']:<12.6e}")

    print("-" * 80)
    print(f"\n✓ КОРЕНЬ УРАВНЕНИЯ: x = {root:.10f}")
    print(f"✓ f(x) = {f(root):.2e}")
    print(f"✓ Число итераций: {len(iterations)}")

except Exception as e:
    print(f"✗ Ошибка: {e}")
    exit(1)

# ==================== ВИЗУАЛИЗАЦИЯ ====================
plt.style.use('seaborn-v0_8-whitegrid')
fig = plt.figure(figsize=(16, 12))
gs = GridSpec(3, 2, figure=fig, hspace=0.3, wspace=0.3)

# График 1: функция и корень
ax1 = fig.add_subplot(gs[0, :])
x_full = np.linspace(a, b, 1000)
y_full = f(x_full)
ax1.plot(x_full, y_full, 'b-', linewidth=2, alpha=0.8, label='f(x)')
ax1.axhline(y=0, color='k', linestyle='-', linewidth=1)
ax1.scatter([root], [f(root)], color='red', zorder=5, label=f'root ≈ {root:.6f}')
ax1.annotate(
    f'x* = {root:.6f}',
    xy=(root, f(root)),
    xytext=(root + 0.05, f(root) + 0.5),
    arrowprops=dict(arrowstyle='->', color='red'),
    fontsize=10,
    bbox=dict(boxstyle='round,pad=0.3', fc='white', ec='red', alpha=0.8)
)
ax1.set_xlabel('x', fontsize=11, fontweight='bold')
ax1.set_ylabel('f(x)', fontsize=11, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# График 2: первые итерации
ax2 = fig.add_subplot(gs[1, 0])
colors = plt.cm.Set1(np.linspace(0, 1, min(4, len(iterations))))
for i, it in enumerate(iterations[:4]):
    a_i, b_i = it['a'], it['b']
    x_i = it['x']
    ax2.plot([a_i, b_i], [f(a_i), f(b_i)], '--', color=colors[i],
             linewidth=2, alpha=0.8, label=f'Итерация {i + 1}')
    ax2.plot(x_i, f(x_i), 'o', color=colors[i], markersize=8,
             markerfacecolor='white', markeredgewidth=2)
    ax2.annotate(f'x{i + 1}', (x_i, f(x_i)), xytext=(5, 5),
                 textcoords='offset points', fontsize=9)

ax2.plot(x_full, y_full, 'b-', linewidth=1.5, alpha=0.5)
ax2.axhline(y=0, color='k', linestyle='-', linewidth=0.8, alpha=0.5)
ax2.set_xlim(a, b)
ax2.set_xlabel('x', fontsize=11, fontweight='bold')
ax2.set_ylabel('f(x)', fontsize=11, fontweight='bold')
ax2.set_title('Метод хорд: первые итерации', fontsize=13, fontweight='bold')
ax2.legend(fontsize=9)
ax2.grid(True, alpha=0.3)

# График 3: сходимость x_n
ax3 = fig.add_subplot(gs[1, 1])
xs = [it['x'] for it in iterations]
ax3.plot(range(1, len(xs) + 1), xs, marker='o', linewidth=2, color='orange')
ax3.set_xlabel('n', fontsize=11, fontweight='bold')
ax3.set_ylabel('x_n', fontsize=11, fontweight='bold')
ax3.set_title('Сходимость приближений', fontsize=13, fontweight='bold')
ax3.annotate(
    f'root ≈ {root:.6f}',
    xy=(len(xs), root),
    xytext=(max(1, len(xs) - 4), root + 0.05),
    arrowprops=dict(arrowstyle='->', color='black'),
    bbox=dict(boxstyle='round,pad=0.25', fc='white', ec='gray', alpha=0.8)
)
ax3.grid(True, alpha=0.3)

# График 4: погрешность
ax4 = fig.add_subplot(gs[2, :])
errors = [it['error'] for it in iterations]
ax4.plot(range(1, len(errors) + 1), errors, marker='o', linewidth=2, color='green')
ax4.set_xlabel('n', fontsize=11, fontweight='bold')
ax4.set_ylabel('|Δx|', fontsize=11, fontweight='bold')
ax4.set_title('Погрешность итераций', fontsize=13, fontweight='bold')
ax4.set_yscale('log')
ax4.grid(True, alpha=0.3, which='both')

plt.suptitle(

    'f(x) = arcsin(x)/sqrt(1-x^2) - 1/2',
    fontsize=16, fontweight='bold', y=0.995
)

plt.tight_layout(rect=[0, 0, 1, 0.98])
plt.savefig('variant22_chord_full.png', dpi=200, bbox_inches='tight')
plt.show()

# ==================== ИТОГОВАЯ ТАБЛИЦА ====================
print("\n" + "=" * 80)
print("СВОДНАЯ ТАБЛИЦА РЕЗУЛЬТАТОВ")
print("=" * 80)
print(f"{'Параметр':<40} {'Значение':<25}")
print("-" * 80)
print(f"{'Начальный интервал [a, b]':<40} [{a}, {b}]")
print(f"{'Требуемая точность ε':<40} {eps:.0e}")
print(f"{'Найденный корень x*':<40} {root:.10f}")
print(f"{'Значение f(x*)':<40} {f(root):.2e}")
print(f"{'Число итераций':<40} {len(iterations)}")
print(f"{'Последняя погрешность |Δx|':<40} {iterations[-1]['error']:.2e}")
print(f"{'Последнее |f(x)|':<40} {abs(iterations[-1]['f(x)']):.2e}")
print("=" * 80)
print("\n✓ Решение найдено успешно!")