import csv
import math
import matplotlib.pyplot as plt
# Variant 22: x = 4 / (x^2 + 2x + 6)
def phi(x):
return 4 / (x*x + 2*x + 6)
x0 = 0.5
eps = 1e-6
max_iter = 100
# Fixed-point iterations
xs = [x0]
for _ in range(max_iter):
xn = phi(xs[-1])
xs.append(xn)
if abs(xs[-1] - xs[-2]) < eps:
break
root = xs[-1]
iterations = len(xs) - 1
print(f"x0 = {x0}")
print(f"iterations = {iterations}")
print(f"root ≈ {root:.10f}")
# Save iteration table
with open('variant22_iterations_matplotlib.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['n', 'x_n', 'abs_dx'])
for n in range(1, len(xs)):
writer.writerow([n, f'{xs[n]:.10f}', f'{abs(xs[n]-xs[n-1]):.10f}'])
plt.style.use('seaborn-v0_8-whitegrid')
# Chart 1: convergence of iterations
fig, ax = plt.subplots(figsize=(8, 5), dpi=200)
ax.plot(range(len(xs)), xs, marker='o', linewidth=2, color='#1f77b4')
ax.set_title('Convergence of iterations for variant 22')
ax.set_xlabel('Iteration n')
ax.set_ylabel('x_n')
ax.annotate(
f'root ≈ {root:.6f}',
xy=(iterations, root),
xytext=(max(0, iterations - 4), root + 0.03),
arrowprops=dict(arrowstyle='->', color='black')
)
fig.tight_layout()
fig.savefig('variant22_convergence_matplotlib.png', bbox_inches='tight')
plt.close(fig)
# Chart 2: function and identity line
xmin, xmax = 0, 1
grid = [xmin + (xmax - xmin) * i / 400 for i in range(401)]
y_phi = [phi(x) for x in grid]
y_id = grid
fig, ax = plt.subplots(figsize=(8, 5), dpi=200)
ax.plot(grid, y_phi, label='phi(x)', linewidth=2, color='#ff7f0e')
ax.plot(grid, y_id, label='y = x', linewidth=2, color='#2ca02c')
ax.scatter([root], [root], color='red', zorder=5)
ax.annotate(
f'{root:.6f}',
xy=(root, root),
xytext=(root + 0.03, root + 0.03),
arrowprops=dict(arrowstyle='->', color='red')
)
ax.set_title('Intersection of phi(x) and y=x for variant 22')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
fig.tight_layout()
fig.savefig('variant22_intersection_matplotlib.png', bbox_inches='tight')
plt.close(fig)