function differenceQuotientErrors
% generate the log-log plot in Figure 11.1, p.76 of my book
% for the function f(x)=sin(x), for which the derivative is f'(x)=cos(x),
% compute the difference quotient (f(x+h) – f(x))/h for various h and
Copyright By PowCoder代写 加微信 powcoder
% compare this with the true derivative. The difference is the error.
% The error is dominated by DISCRETIZATION ERROR when h is large and
% by CANCELLATION ERROR (ROUNDING ERROR) when h is small. Use x = 1.
% define the anonymous function f
f = @(x)sin(x);
fprime = @(x)cos(x);
fx = f(x);
derivx = fprime(x);
% collect all the values of h in a vector h using the .^ operator
h = 10.^(-20:0); % vector with components 10^-20, 10^-19, …, 1, 0
for k=1:length(h)
dif_quo(k) = (f(x+h(k)) – fx)/h(k);
error(k) = abs(derivx – dif_quo(k));
loglog(h,error,’*’)
xlabel(‘h’)
ylabel(‘error’);
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com