import csv, math
import matplotlib.pyplot as plt
def f(x):
return math.asin(x) / math.sqrt(1 - x*x) - 0.5
def chord_method(x0, x1, eps=1e-6, max_iter=100):
xs = [x0, x1]
fs = [f(x0), f(x1)]
for _ in range(max_iter):
if fs[-1] == fs[-2]:
break
x2 = xs[-1] - fs[-1] * (xs[-1] - xs[-2]) / (fs[-1] - fs[-2])
xs.append(x2)
fs.append(f(x2))
if abs(xs[-1] - xs[-2]) < eps:
break
return xs, fs
x_left, x_right = -0.5, 0.8
x0, x1 = x_left, x_right
xs, fs = chord_method(x0, x1)
root = xs[-1]
with open('variant22_chord_iterations.csv', 'w', newline='', encoding='utf-8') as fcsv:
writer = csv.writer(fcsv)
writer.writerow(['n', 'x_n', 'f(x_n)', 'abs_dx'])
for n in range(len(xs)):
abs_dx = '' if n == 0 else f'{abs(xs[n]-xs[n-1]):.10f}'
writer.writerow([n, f'{xs[n]:.10f}', f'{fs[n]:.10f}', abs_dx])
plt.style.use('seaborn-v0_8-whitegrid')
grid = [x_left + (x_right - x_left) * i / 800 for i in range(801)]
y = [f(x) for x in grid]
fig, ax = plt.subplots(figsize=(8, 5), dpi=200)
ax.plot(grid, y, label='f(x)', linewidth=2, color='#1f77b4')
ax.axhline(0, color='black', linewidth=1)
ax.scatter([root], [f(root)], color='red', zorder=5)
ax.annotate(
f'x* ≈ {root:.6f}',
xy=(root, 0),
xytext=(root + 0.05, 0.15),
arrowprops=dict(arrowstyle='->', color='red')
)
ax.set_title('Variant 22: function graph for chord method')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()
fig.tight_layout()
fig.savefig('variant22_chord_function.png', bbox_inches='tight')
plt.close(fig)
fig, ax = plt.subplots(figsize=(8, 5), dpi=200)
ax.plot(range(len(xs)), xs, marker='o', linewidth=2, color='#ff7f0e')
ax.set_title('Variant 22: chord method convergence')
ax.set_xlabel('Iteration n')
ax.set_ylabel('x_n')
ax.annotate(
f'root ≈ {root:.6f}',
xy=(len(xs)-1, root),
xytext=(max(0, len(xs)-5), root+0.04),
arrowprops=dict(arrowstyle='->', color='black')
)
fig.tight_layout()
fig.savefig('variant22_chord_convergence.png', bbox_inches='tight')
plt.close(fig)