% Demo for Derivative Aprroximation. % % f(x) = 4 sqrt(x) - ln(x) at x=4 % f'(4) = 0.75 exact value. format long g h = 10.^(-(1:16)); h = h'; % generate step sizes x = 4+h; % calculate the locations 4+h y = 4*sqrt(x) - log(x); % compute f(4+h); f4 = 8 - log(4); % compute f(4) once and for all df = (y-f4)./h; % compute (f(4+h)-f(4))/h for our selection of h relerr1 = (df-0.75)/0.75; % compute the relative error for each h display('forward differences') [h df relerr1] % display h, the approx derivative and the relative error pause % same procedure, this time step back, i.e. use f(4-h) x = 4-h; % calculate the locations 4+h y = 4*sqrt(x) - log(x); % compute f(4+h); df = -(y-f4)./h; % compute (f(4+h)-f(4))/h for our selection of h relerr2 = (df-0.75)/0.75; % compute the relative error for each h display('backward differences') [h df relerr2] % display h, the approx derivative and the relative error pause % graph the relative errors in a loglog plot loglog(h,abs(relerr1),h,abs(relerr2),'--') pause display(' both error curves have approximately the same shape, optimum near h = 10^(-7)') pause % improved formula x = 4+h; % calculate the locations 4+h y2 = 4*sqrt(x) - log(x); % compute f(4+h); x = 4-h; % calculate the locations 4-h y1 = 4*sqrt(x) - log(x); % compute f(4-h); df = 0.5*(y2-y1)./h; % compute (f(4+h)-f(4-h))/(2h) for our selection of h relerr3 = (df-0.75)/0.75; % compute the relative error for each h display('refined derivative approximations') [h df relerr3] % display h, the approx derivative and the relative error loglog(h,abs(relerr3),h,abs(relerr1),'--'); display('new optimum near h = 10^(-5)') pause