# central difference approximation write a script which for a vector of increasingly smaller values of h computes approximations of f ′ (2) in matlab

To compute the central difference approximation for a function f, we use the following formula:

$f'(x)&space;\approx&space;\frac{f(x+h)-f(x-h)}{2h}$

We can write a script in MATLAB to calculate the central difference approximation for a vector of increasingly smaller values of h as follows:

main.m% Function to approximate the derivative of f using the central difference formula
function df = central_diff(f, x, h)
df = (f(x+h) - f(x-h)) / (2*h);
end

% Define the function f
f = @(x) x.^2 + sin(x);

% Define the point at which to compute the derivative
x0 = 2;

% Define vector of h values
h_vec = logspace(-1, -16, 16);

% Compute approximations of f'(2) for each value of h in h_vec
df_vec = zeros(1, length(h_vec));
for i = 1:length(h_vec)
df_vec(i) = central_diff(f, x0, h_vec(i));
end

% Plot the error vs. h
figure();
loglog(h_vec, abs(df_vec - (2*cos(2) + 4)), '-o');
xlabel('h');
ylabel('Error');
title('Central Difference Approximation Error');
668 chars27 lines

In this script, we define the function central_diff to calculate the central difference approximation using the formula given above. We then define the function f that we want to approximate the derivative of, as well as the point at which we want to compute the derivative x0.

We define the vector h_vec containing the values of h that we want to use for the approximation, and initialize a vector df_vec to store the results. We use a for loop to compute the approximation of f'(2) for each value of h, and store the results in df_vec.

Finally, we plot the error in the approximation vs. h using a logarithmic scale for both axes. We use the fact that f'(2) = 2*cos(2) + 4 to compute the exact value of the derivative at x0, and plot the absolute value of the error. We can see from the plot that the error decreases as h gets smaller, as expected.

### related categories

gistlibby LogSnag