% Example 11.6
% Romberg's Method
clearvars
clc

f = @(x) exp(x);
a = 0;
b = 2;
n1 = 1;

% For this example, the stopping criteria is the absolute error, so we need
% the exact integral
Iexact = integral(f,a,b);

% Initialize values
es = 0.00042;
maxit = 100;

count = 0;
er = 1;

IR = zeros(1);
k = 1;

while (abs(er)>es && count<maxit)
    count = count + 1;
    for i = 1:count
        IR(i,1) = trap_func(f,a,b,2^(i-1)*n1);
    end
    if(count>1)
        for k = 2:count
            for j = 1:count-k+1
                IR(j,k) = (4^(k-1)*IR(j+1,k-1) - IR(j,k-1))/(4^(k-1)-1);
            end
        end
    end
    er = Iexact - IR(1,k);
    
    disp(['Romberg Table for iteration ',num2str(count)])
    disp(IR)    
end

Ifinal = IR(1,k);

disp(['The estimate of the integral is ',num2str(Ifinal),' after ',num2str(count),' iterations'])