% Example taken from Chapter 7 of N. Trefethen's book 
% "Approximation Theory and Approximation Practice" (SIAM, 2013)

clear all, close all

figure(1)
x = chebfun('x'); 
f = abs(x);
%f = chebfun({0.0, @(x) x.^2},[-1 0 1]);
nn = 2*round(2.^(0:.3:7))-1;
ee = 0*nn;
for j = 1:length(nn)
    n = nn(j); fn = chebfun(f,n+1); ee(j) = norm(f-fn,inf);
end
hold off, loglog(nn,0.1./nn.^1,'r'), FS = 'fontsize';
%hold off, loglog(nn,1./nn.^2,'r'), FS = 'fontsize';
text(5,0.07,'n^{-1}',FS,12)
grid on, axis([1 300 1e-5 2])
hold on, loglog(nn,ee,'.')
xlabel('n'), ylabel('||f-p_n||');
title('Linear convergence for a differentiable function',FS,9)


figure(2)
f = abs(sin(5*x)).^3;
for j = 1:length(nn)
    n = nn(j); fn = chebfun(f,n+1); ee(j) = norm(f-fn,inf);
end
hold off, loglog(nn,nn.^-3,'r')
text(4,.0015,'n^{-3}',FS,12)
grid on, axis([1 300 2e-6 10])
hold on, loglog(nn,ee,'.')
xlabel('n'), ylabel('||f-p_n||');
title('Cubic convergence for a 3-times differentiable function',FS,9)
