%% forward difference derivative of sin
f = @sin;
x = linspace(0, 2 * pi, 25);
fprime = fdiff(f, x, 0.001);
expected = cos(x);

figure
plot(x, expected, 'b-', x, fprime, 'ro')
legend('true derivative', 'forward difference derivative', 'Location', 'north')

% error 
error = expected - fprime;
figure
plot(x, error)
ylabel('error (true derivative - forward difference)')
title('error of forward difference');

% error as a function of h
figure
for h = [0.001 0.00075 0.0005 0.00025]
    fprime = fdiff(f, x, h);
    error = expected - fprime;
    plot(x, error)
    hold on
end
ylabel('error (true derivative - forward difference)')
title('error of forward difference as a function of h');

%% backward difference derivative of sin
f = @sin;
x = linspace(0, 2 * pi, 25);
fprime = bdiff(f, x, 0.001);
expected = cos(x);

figure
plot(x, expected, 'b-', x, fprime, 'ro')
legend('true derivative', 'bacward difference derivative', 'Location', 'north')

% error 
error = expected - fprime;
figure
plot(x, error)
ylabel('error (true derivative - backward difference)')
title('error of backward difference');

% error as a function of h
figure
for h = [0.001 0.00075 0.0005 0.00025]
    fprime = bdiff(f, x, h);
    error = expected - fprime;
    plot(x, error)
    hold on
end
ylabel('error (true derivative - backward difference)')
title('error of backward difference as a function of h');


%% central difference derivative of sin
f = @sin;
x = linspace(0, 2 * pi, 25);
fprime = cdiff(f, x, 0.001);
expected = cos(x);

figure
plot(x, expected, 'b-', x, fprime, 'ro')
legend('true derivative', 'central difference derivative', 'Location', 'north')

% error 
error = expected - fprime;
figure
plot(x, error)
ylabel('error (true derivative - central difference)')
title('error of central difference');

% error as a function of h
figure
for h = [0.001 0.00075 0.0005 0.00025]
    fprime = cdiff(f, x, h);
    error = expected - fprime;
    plot(x, error)
    hold on
end
ylabel('error (true derivative - central difference)')
title('error of central difference as a function of h');


%% noisy functions
f = @noisysin;
x = linspace(0, 2 * pi, 25);
fprime = fdiff(f, x, 0.01);
expected = cos(x);

figure
plot(x, expected, 'b-', x, fprime, 'ro')
legend('true derivative', 'forward difference derivative', 'Location', 'north')
