import numpy as np
import matplotlib.pyplot as plt
x0 = 0.25
epsilon = 1e-15
N_max = 10**6
# === ВАША ФУНКЦИЯ ===
def phi(x):
return 4 / (x**2 + 2*x + 6)
def f(x):
return x - phi(x)
def dphi(x):
denom = (x**2 + 2*x + 6)**2
return -4 * (2*x + 2) / denom # φ'(x)
x_check = np.linspace(0, 1, 500)
q = np.max(np.abs(dphi(x_check)))
print(f" Проверка сходимости на [0; 1]: max |φ'(x)| = {q:.4f}")
print(f" Условие |φ'(x)| < 1 {'ВЫПОЛНЕНО' if q < 1 else 'НЕ ВЫПОЛНЕНО'}")
x_history = [x0]
f_history = [f(x0)]
n = 0
while n < N_max:
x_next = phi(x_history[-1])
f_val = f(x_next)
x_history.append(x_next)
f_history.append(f_val)
n += 1
if abs(f_val) < epsilon:
print(f"Критерий останова достигнут на шаге n = {n}")
break
x_star = x_history[-1]
print(f"\nРЕЗУЛЬТАТ: x* = {x_star:.16f}, |f(x*)| = {abs(f_history[-1]):.2e}")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
x_plot = np.linspace(0, 1, 400)
ax1.plot(x_plot, x_plot, 'k--', linewidth=2, label='y = x')
ax1.plot(x_plot, phi(x_plot), 'b-', linewidth=2, label='y = φ(x)')
ax1.plot(x_star, x_star, 'ro', markersize=10, label=f'Корень ≈ {x_star:.5f}')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.legend()
ax1.grid(True, alpha=0.5)
ax1.set_title('1. Графическое отделение корня')
cob_x, cob_y = [], []
steps = min(30, len(x_history) - 1)
for i in range(steps):
cob_x.append(x_history[i])
cob_y.append(x_history[i])
cob_x.append(x_history[i])
cob_y.append(x_history[i+1])
cob_x.append(x_history[i+1])
cob_y.append(x_history[i+1])
ax2.plot(x_plot, x_plot, 'k--', linewidth=1, alpha=0.4, label='y = x')
ax2.plot(x_plot, phi(x_plot), 'b-', linewidth=2, label='y = φ(x)')
ax2.plot(cob_x, cob_y, 'r-', linewidth=1.5, label='Итерации')
ax2.plot(x_history[0], x_history[0], 'go', markersize=8, label=f'Старт: x₀={x0}')
ax2.plot(x_star, x_star, 'mo', markersize=8, label=f'Финиш: x*')
ax2.set_xlim(0.0, 1.0)
ax2.set_ylim(0.0, 1.0)
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.legend(fontsize=9)
ax2.grid(True, alpha=0.5)
ax2.set_title('2. Сходимость к корню')
plt.tight_layout()
plt.savefig('variant22_fixed_point_matplotlib.png', dpi=200, bbox_inches='tight')
plt.show()