In: Advanced Math
Write a code to approximate the derivative of a function f(x) using forward finite difference quotient f( x + h ) - f( x ) f'(x) ≈ ------------------- (for small h). h For the function f(x) = sin(x), at x=1 , compute the FD quotients for h = 1/2k, k=5,...,N, with N=30 and compare with the exact derivative cos(x). Output k , h , error. Where SHOULD the error tend as h → 0 ? 1. Look at the numbers. Does the error behave as expected ? Output to a file "out" (or to arrays in matlab), and plot it [ gnuplot> plot "out" u 2:3 with lines ] Which direction is the curve traversed, left to right or right to left ? Look at the numbers. h is decreasing exponentially, so the points pile up on the vertical axis. The plot is poorely scaled. To see what's happening, use logarithmic scale, i.e. output k , log(h) , log(error) and replot. 2. What is the minimum error ? at what k ? Why does the error get worse for smaller h ? 3. Repeat, using centered finite differences [copy your code to a another file and modify it] f( x + h ) - f( x - h ) f'(x) ≈ ----------------------- (for small h). 2 h 4. Which formula performs better ? in what sense ?
Central difference is better
than forward difference because it achieves faster convergence.
%%Matlab code for forward and central differential
clear all
close all
%function for which derivative have to find
f=@(x) sin(x);
%exact derivative
g=@(x) cos(x);
%loop for derivative
cnt=0; x0=1;
for k=5:30
cnt=cnt+1;
h(cnt)=1/(2^k);
kk(cnt)=k;
%forward derivative
val1(cnt)=(f(x0+h(cnt))-f(x0))/h(cnt);
err1(cnt)=abs(g(x0)-val1(cnt));
%central derivative
val2(cnt)=(f(x0+h(cnt))-f(x0-h(cnt)))/(2*h(cnt));
err2(cnt)=abs(g(x0)-val2(cnt));
end
mm1=find(err1==min(err1));
fprintf('For forward differential minimum error occured at h=%e and
k=%d\n',h(mm1(1)),kk(mm1(1)))
mm2=find(err2==min(err2));
fprintf('For central differential minimum error occured at h=%e and
k=%d\n',h(mm2(1)),kk(mm2(1)))
figure(1)
plot(kk,err1)
hold on
plot(kk,err2)
xlabel('k')
ylabel('error')
title('k vs. error plot')
legend('Forward difference','Central difference')
figure(2)
plot(kk,log(err1))
hold on
plot(kk,log(err2))
xlabel('k')
ylabel('log(error)')
title('k vs. log(error) plot')
legend('Forward difference','Central difference')
fprintf('Central difference is better than forward difference\n')
%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%%%%