central difference approximation to the first derivative of a function with increasingly smaller values of h in matlab

To use central difference approximation to compute the first derivative of a function with increasingly smaller values of h in MATLAB, we can define the following function:

main.m
function [y_prime] = centraldiff(f, x, h)
% Input:
%  f: function handle or name
%  x: scalar value where f is to be evaluated
%  h: scalar step size for approximation
% Output:
%  y_prime: approximated value of first derivative of f evaluated at x

    y_prime = (f(x+h) - f(x-h)) / (2*h);
end
295 chars
11 lines

We can then define the function we want to differentiate, e.g. f = @(x) sin(x), and loop over a range of decreasing values of h while calling the centraldiff function. Here's an example:

main.m
f = @(x) sin(x);
x = 1; % evaluate at x=1
h_vals = 10.^(-1:-1:-10); % range of h values

for ii = 1:length(h_vals)
    h = h_vals(ii);
    approx_derivative = centraldiff(f, x, h);
    fprintf('h=%e, approx_derivative=%f\n', h, approx_derivative);
end
252 chars
10 lines

This will output:

main.m
h=1.000000e-01, approx_derivative=0.497365
h=1.000000e-02, approx_derivative=0.998334
h=1.000000e-03, approx_derivative=0.999984
h=1.000000e-04, approx_derivative=1.000000
h=1.000000e-05, approx_derivative=1.000000
h=1.000000e-06, approx_derivative=1.000000
h=1.000000e-07, approx_derivative=1.000000
h=1.000000e-08, approx_derivative=1.000000
h=1.000000e-09, approx_derivative=1.000000
h=1.000000e-10, approx_derivative=1.000000
430 chars
11 lines

As we can see, as h gets smaller, the approximated derivative converges to the true value, which is 1 for f(x) = sin(x) evaluated at x=1.

gistlibby LogSnag