%computes numerically the derivative of f at a
%using right differences, central differences and Richardson differences
%notice smaller error for central differences

format long;

f = @(x) sin(x);
f_p = @(x) cos(x);

n = 3;
a = 0.5;
h = 1;

right_diff = zeros(1,n);
central_diff = zeros(1,n);
richardson_diff = zeros(1,n);

for i=1:n
    h = h/10;
    right_diff(i) = [f(a+h)-f(a)]/h;
    central_diff(i) = [f(a+h)-f(a-h)]/(2*h);
    richardson_diff(i) = 4*[f(a+h/2)-f(a-h/2)]/(3*h)-[f(a+h)-f(a-h)]/(6*h);
end

exact = f_p(a)*ones(1,n);

disp('absolute errors for right differences are...')
abs(right_diff-exact)

disp('absolute errors for central differences are...')
abs(central_diff-exact)

disp('absolute errors for Richardson differences are...')
abs(richardson_diff-exact)


