%==========================================================================
% Code that illustrates the behavior of the approximation error versus the
% discretization parameter h for the 2nd-order centered finite difference
% approximation of the 1st derivative.
% Created:     23.10.2019
% Last change: 23.10.2019
% Author: Marco Sutti.
%==========================================================================
close all; clear; clc;
set( 0, 'defaultAxesTickLabelInterpreter', 'latex' );
set( 0, 'defaultLegendInterpreter',        'latex' );
set( 0, 'defaultTextInterpreter',          'latex' );
set( 0, 'defaultAxesFontSize', 14 );

%--------------------------------------------------------------------------
% Data
%--------------------------------------------------------------------------
% Define the function and its derivative;
f = @(x) sin(x);
df = @(x) cos(x);

% Define the point x0;
x0 = pi/3;

% Evaluate the derivative at x0;
df_x0 = df(x0);

% Create a grid for the interval [10^-16,10^-1];
hs = logspace( -16, -1, 100 );

error = zeros(size(hs));

% Compute the error
for i = 1:length(hs)
    h = hs(i);
    error(i) = abs ( df_x0 - ( f ( x0 + h ) - f ( x0 - h ))/(2*h) );
end

% Plot;
figure;
hold on;
set(gca,'xscale','log');
set(gca,'yscale','log');
% set(gca, 'YTick', [1e-12, 1e-6, 1e0]);
set(gca, 'XTick', [ 1e-20, 1e-15, 1e-10, 1e-5, 1e0 ] );
hs_ref = [ 1e-7, 2e0 ];
h1 = plot( hs_ref, hs_ref.^2, '--', 'LineWidth', 2, 'Color', [.7 .7 .7] );
h2 = plot( hs , error, 'ok', 'MarkerFaceColor', [.49 1 .63] );
grid on;
hL = legend([h2,h1],{'Erreur','$O(h^{2})$'}, 'interpreter','latex', ...
                                             'FontSize', 14, ...
                                             'Location', 'SW' );

saveas( gcf, 'central_diff', 'epsc' )
                                         
