%% fig_newton_damping_comparison.m
% Compare Newton (alpha=1) and damped Newton (alpha=0.5)

f  = @(x) x.^3 - 5*x + 1;
fp = @(x) 3*x.^2 - 5;

% Helper that stores the path of x_t
function xs = newton_path(x0, alpha, f, fp, maxit, tolF)
    xs = x0;
    for it = 1:maxit
        fx  = f(x0);  fpx = fp(x0);
        if abs(fpx) < 1e-12, break; end
        x0 = x0 - alpha * fx / fpx;
        xs(end+1) = x0; %#ok<AGROW>
        if abs(f(x0)) < tolF, break; end
    end
end

% Parameters
x0 = 1.5;  maxit = 50;  tolF = 1e-8;
xs_full = newton_path(x0, 1.0, f, fp, maxit, tolF);
xs_damp = newton_path(x0, 0.5, f, fp, maxit, tolF);

% Plot function and paths
x = linspace(0, 5, 400);  y = f(x);
figure('Color','w');
plot(x, y, 'b', 'LineWidth', 1.5,'DisplayName','f(x)'); hold on; grid on; box on;
yline(0, 'k', 'LineWidth', 1, 'HandleVisibility', 'off');

plot(xs_full, f(xs_full), 'o-', 'LineWidth', 1.2, 'DisplayName','Undamped (\alpha=1.0)');
plot(xs_damp, f(xs_damp), 's--', 'LineWidth', 1.2, 'DisplayName','Damped (\alpha=0.5)');

% Optional: vertical line at the converged root (from undamped)
xstar = xs_full(end);
xline(xstar, ':r', 'DisplayName','Approx. root');

xlabel('x'); ylabel('f(x)');
ylim([-25 25]);
title('Newton–Raphson: Damped vs. Undamped Trajectories');
legend('Location','northwest');

exportgraphics(gcf, 'fig_newton_damping_comparison.png', 'Resolution', 300);