% ChebyshevAccuracyDemo.m illustrates the accuracy of periodic spectral differentiation
% for 4 different functions of increasing smoothness
% Based on Trefethen: Spectral Methods in Matlab
% compare with SpectralAccuracyDemo.m

clear all
clc
close all
warning off
scrnsz = get(0, 'Screensize');
figure('Position', [5 10 scrnsz(3)-5 scrnsz(4)-60])

% Compute derivatives for various values of N:
Nmax = 50; E = zeros(3,Nmax);
for N = 1:Nmax;
    [D,t] = cheb(N);
    y = abs(t).^3; yprime = 3*t.*abs(t);     % 3rd deriv in BV
    E(1,N) = norm(D*y-yprime,inf);
    y = exp(-t.^(-2)); yprime = 2.*y./t.^3;  % C-infinity
    E(2,N) = norm(D*y-yprime,inf);
    y = 1./(1+t.^2); yprime = -2*t.*y.^2;    % analytic in [-1,1]
    E(3,N) = norm(D*y-yprime,inf);
    y = t.^10; yprime = 10*t.^9;             % polynomial
    E(4,N) = norm(D*y-yprime,inf);
end

% Plot results:
titles = {'|t^3|','exp(-t^{-2})','1/(1+t^2)','t^{10}'}; clf
for iplot = 1:4
    subplot(2,2,iplot)
    semilogy(1:Nmax,E(iplot,:),'.','markersize',12)
    line(1:Nmax,E(iplot,:))
    axis([0 Nmax 1e-16 1e3]), grid on
    set(gca,'xtick',0:10:Nmax,'ytick',(10).^(-15:5:0))
    xlabel N, ylabel error, title(titles(iplot))
end
