function [] = probset01_schemeorder(i, x0)
% PROBSET01_SCHEMEORDER  Verify order of convergence of finite difference schemes.
%   PROBSET01_SCHEMEORDER(i, x0) displays order-of-convergence plots
%   for the finite difference formulas applied to test example no. i at
%   point x0.

% Step sizes.
h = .1 * 2.^-(0:10);

% Test functions and exact derivatives.
f  = {@(x) 1 ./ x, ...
      @(x) sin(x) - cos(x), ...
      @(x) (x.^2 - 2*x) .* (x > 1) + (-x.^2 + 2*x - 2) .* (x <= 1), ...
      };
df = {@(x) -1 ./ (x.^2), ...
      @(x) cos(x) + sin(x), ...
      @(x) (2*x - 2   ) .* (x > 1) + (-2*x + 2       ) .* (x <= 1), ...
      };

% Extract MATLABs colors.
Colors = get(groot,'DefaultAxesColorOrder');

% Order of convergence-plots for the finite difference formulas.
hold off
loglog(h, abs(forward( f{i}, x0, h) - df{i}(x0)), 'Color', Colors(1, :))
hold on
loglog(h, abs(backward(f{i}, x0, h) - df{i}(x0)), 'Color', Colors(2, :))
loglog(h, abs(central( f{i}, x0, h) - df{i}(x0)), 'Color', Colors(5, :))

% Reference lines.
loglog(h, .5 * h,    '--', 'Color', Colors(1, :))
loglog(h, .5 * h.^2, '--', 'Color', Colors(5, :))

% Plot settings.
xlabel('$h$',      'Interpreter', 'LaTeX', 'Fontsize', 12);
ylabel('$|e(h)|$', 'Interpreter', 'LaTeX', 'Fontsize', 12);
set(gca, 'Color', 'none');
end

%% Finite difference formulas.
function dfx = forward(f, x, h)
dfx = (f(x + h) - f(x)) ./ h;
end

function dfx = backward(f, x, h)
dfx = (f(x) - f(x - h)) ./ h;
end

function dfx = central(f, x, h)
dfx = (f(x + h) - f(x - h)) ./ (2 * h);
end