% Gauss Quadrature for Example 11.8
clearvars
clc

f = @(x) cos(x);

Iexact = integral(f,-1,1);
I1 = gauss_quad(f,1);
I2 = gauss_quad(f,2);
I3 = gauss_quad(f,3);
I4 = gauss_quad(f,4);

Er1 = (Iexact - I1)/Iexact;
Er2 = (Iexact - I2)/Iexact;
Er3 = (Iexact - I3)/Iexact;
Er4 = (Iexact - I4)/Iexact;

disp('GAUSS QUADRATURE')
disp('------------------------------------------------------------')
disp(['With 1 integration point,  I1 = ',num2str(I1),' and Er1 = ',num2str(Er1)])
disp(['With 2 integration points, I2 = ',num2str(I2),' and Er2 = ',num2str(Er2)])
disp(['With 3 integration points, I3 = ',num2str(I3),' and Er3 = ',num2str(Er3)])
disp(['With 4 integration points, I4 = ',num2str(I4),' and Er4 = ',num2str(Er4)])

xplot = linspace(-1,1);
yplot = f(xplot);

figure
hold on
fplot(f,[-1,1],'LineWidth',2)
area(xplot,yplot,'EdgeColor',[0.8500, 0.3250, 0.0980],'FaceAlpha',0.2)
xlim([-1,1])
ylim([-1,1])
plot([0,0],ylim,'-k')
plot(xlim,[0,0],'-k')
xlabel('x')
ylabel('f(x)')
title('f(x) = cos(x)')