%rum_midpoint method
%this scripts runs implementations of the midpoint method:
%1. A version that uses loops 2. A version the uses a vectorized code
%MA 302
%PC

clc
clear

f=@(x)exp(x.^2);

true_int_val =  integral(f,0,1);
approx_int_vals = zeros(1,10);
error_vals = zeros(1,10);

tic

n=10;
for i=1:10
 approx_int = mid_point_method(f,0,1,n);
 error_v = abs(approx_int-true_int_val);
 approx_int_vals(i) = approx_int;
 error_vals(i) = error_v;
 n=2*n;
end
format long e

disp('Error values - Loop code');
disp(error_vals');

ratios= error_vals(1:9)./error_vals(2:10);
disp('Ratio of Errors - Loop code');
disp(ratios');

disp('Loop Version:');
elapsed_time_l =toc;
fprintf('Loop Version elapsed time = %f \n',elapsed_time_l);
fprintf('----------------------------------\n');

%start timing the vectorized version
tic
n=10;
for i=1:10
 approx_int = opt_mid_point_method(f,0,1,n);
 error_v = abs(approx_int-true_int_val);
 approx_int_vals(i) = approx_int;
 error_vals(i) = error_v;
 n=2*n;
end
format long e

disp('Error values - Optimized Version');
disp(error_vals');

ratios= error_vals(1:9)./error_vals(2:10);
disp('Ratio of errors - Optimized Version');
disp(ratios')

elapsed_time_o = toc;
fprintf('Optimized version elapsed time = %f\n',elapsed_time_o);
