[Math] Writing a MATLAB .m File to Generate a Plot of Absolute Error as a Function of h (step-size)

MATLABnumerical methods

This is the question I am to solve:

Given the function $f(x)=\ln(3x+1)$, compute approximations to $f'(0)$ using the centered 3-point formula:

$f'(x_0)\approx\frac{f(x_0+h)-f(x_0-h)}{2h}$.

Use Matlab to generate a plot of the absolute error as a function of the step-size h
for the centered 3-point formula approximation to f′(0). At what values of h is the error
minimized, that is, what step-sizes yield the maximum accuracy for this problem? (The magnitude of this number will be quite small.)

I have written the following MATLAB .m script file to generate the matrix of values $x, f(x), f'(x),$ and $\approx f'(x)$. However, I cannot figure out how to evaluate the error at more than one value for $h$ at a time, if there is a way.

h = 0.1;

x = -0.3:h:0.3;

f = @(x)(log(3.*x+1));

fp = @(x)((3)./(3.*x+1));

N = length(x);

A = zeros(N,4);

for i=1:N

for j = 1:3

   A(i,1) = x(i);

   A(i,2) = f(A(i,1));

   A(i,3) = fp(A(i,1));

end%j

end%i

for i=2:N-1

for j = 4

   A(i,j) = (A(i+1,j-2)-A(i-1,j-2))./(2.*h);

end%j

end%i

mdpt = ceil(N/2);

pt = A(mdpt,4);

err = abs(pt-fp(0));

scatter(h,err)

Best Answer

There are probably a few ways to answer this question. Perhaps you could generate the approximations of $f'(0)$ using the following code:

x0 = 0;

n = 1000;

h = logspace(-16, -1, n); % Generates n numbers logarithmically spaced between 10^(-16) and 10^(-1)

fp_approx = (f(x0 + h) - f(x0 - h)) ./ (2*h); % The approximations of f'(x_0)

Then compute the error as

fp_exact = fp(x0)*ones(size(fp_approx));

err = abs(fp_approx - fp_exact);

You could take $n$ much larger (say, $n = 10^6$), then find the minimum $h$ using min:

[min_err, idx] = min(err);

h(idx)

Related Question