function DifferenceTable(f, fp, x, method)
%DifferenceTable creates a table of numerical derivatives using forward 
% difference.
%
% Syntax:  DifferenceTable(f, fp, x, method)
%
% Inputs:
% f             function handle 
% fp            function handle for derivative of function for error
%               checking
% x             floating point value to compute the numerical derivative
% method        'forward', 'backward', 'centered', or 'richardson'
%
%   ---Optional Arguments---
% field name    'Method'
% field         parameter value , for field name 'Method'. The default method
%               is forward difference.
%
% Outputs:
% approx        the numerical approximation to the derivative of function
%
% Example: 
%   zero = DiffenceTable(@cos, @(x) -sin(x), pi/3)
%   zero = DiffenceTable(@sin, @cos, pi/2, 'richardson')
%   zero = DiffenceTable(@(x) exp(x)-1, @exp, -1)
%
% Other m-files required: none
% Subfunctions: 
% MAT-files required: 
%
% See also: 
%
% Author: Matlab Instructor
% 2022-Apr-04; Last revision: 2022-Apr-04
%
%------------- BEGIN CODE --------------

    if nargin < 4, method = 'forward'; end

    % create table
    fprintf('%s', repmat('=',1,37))
    fprintf('\n\n')
   
    if strcmpi(method, 'richardson')
        fprintf('%s Method = Richardson extrapolation\n%s\n', ...
                repmat(' ',1,12), repmat('-',1,60))
    else
        fprintf('%s Method = %s difference\n%s\n', ...
                repmat(' ',1,12), method, repmat('-',1,60))
    end
   
    fprintf('    h %s (f(x+h)-f(x))/h %s Error\n', ...
            repmat(' ',1,10), repmat(' ',1,7))
    fprintf('%s', repmat('-',1,60))
    fprintf('\n')
    
    N = 16;
    h = 10.^(-(1:N));
    y = derivative(f, x, 'method', method, 'stepsize', h);
    
    for k=1:N
        fprintf('%8.1e    %22.16f     %8.1e\n', h(k), y(k), abs(y(k)-fp(x)))
    end
    
    fprintf('%s', repmat('-',1,60))
    fprintf('\n\n')

    % create plot
    loglog(h,abs(y-fp(x)))
    xlabel('log h')
    ylabel('log absolute error')
    title(['f(x) = ',func2str(f),'(',sprintf('%g',x),')'])
end

%------------- END OF CODE --------------
%Please send suggestions for improvement of the above template header 
%to Denis Gilbert at this email address: gilbertd@dfo-mpo.gc.ca.
%Your contribution towards improving this template will be acknowledged in
%the "Changes" section of the TEMPLATE_HEADER web page on the Matlab
%Central File Exchange
