function TotalNumericalError % My implementation of example 4.5 % Find the first derivative of f(x) at % x = 0.5 using central difference methods x = 0.5; h = 1; n = 10; dftrue = -0.4*x^3-0.45*x^2-x-0.25; df = zeros(n,1); step = zeros(n,1); error = zeros(n,1); % Use second order central difference derivative equation % for repeatedly smaller values of the stepsize h for i = 1:n df(i,1) = (f(x+h)-f(x-h))/(2*h); step(i,1) = h; error(i,1) = abs(dftrue-df(i,1)); h = 0.1*h; end loglog(step,error,'ro-') xlabel('stepsize') ylabel('error') legend('2nd order approx') hold on pause % Now use fourth order central difference derivative equation % for repeatedly smaller values of the stepsize h h = 1; for i = 1:n df(i,1) = (-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h); step(i,1) = h; error(i,1) = abs(dftrue-df(i,1)); h = 0.1*h; end loglog(step,error,'bo-') legend('2nd order approx','4th order approx') function y = f(x) y = -0.1*x^4-0.15*x^3-0.5*x^2-0.25*x+1.2;