clear %% % First consider the integral % % \int_{-1}^1 \frac{1}{1+4x^2} \, dx = \arctan(2). % f = @(x) 1./(1 + 4*x.^2); exact = atan(2); %% % We compare the two spectral integration methods for a range of n values. n = (8:4:96)'; errCC = 0*n; errGL = 0*n; for k = 1:length(n) errCC(k) = exact - ccint(f,n(k)); errGL(k) = exact - glint(f,n(k)); end figure(1) semilogy( n, abs(errCC), '.-') hold on semilogy( n, abs(errGL), '.-') axis tight xlabel('number of nodes') ylabel('error') title('Spectral integration of f(x) = 1/(1 + 4x^2)') legend('CC','GL') grid on %% % (The missing dots are where the error is exactly zero.) Gauss--Legendre % does converge faster here, but at something less than twice the rate. Now % we try a more sharply peaked integrand: % % \int_{-1}^1 \frac{1}{1+16x^2} \, dx = \frac{1}{2}\arctan(4). % f = @(x) 1./(1 + 16*x.^2); exact = atan(4)/2; %% n = (8:4:96)'; errCC = 0*n; errGL = 0*n; for k = 1:length(n) errCC(k) = exact - ccint(f,n(k)); errGL(k) = exact - glint(f,n(k)); end figure(2) semilogy( n, abs(errCC), '.-') hold on semilogy( n, abs(errGL), '.-') axis tight xlabel('number of nodes') ylabel('error') title('Spectral integration of f(x) = 1/(1 + 16x^2)') legend('CC','GL') grid on %% % The two are very close until about n=40, when the Clenshaw--Curtis % method slows down.