clear all
close all
clc

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% exercise 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
y  = @(x)(sqrt(-4.*(x.^4-x.^2)));

N  = 1000;
x  = linspace(-1,1,N);
y1 = +y(x);
y2 = -y(x);

figure(1), hold on
plot(x,y1,'b')
plot(x,y2,'b')
xlabel('x')
ylabel('y')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% exercise 2
% numerical integration of analytical function...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Area = 2*sum( ((y1(1:N-1)+y1(2:N))./2) .* diff(x) );
fprintf(1,'area = %f\n', Area)


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% exercise 3
% Monte Carlo integration of analytical function...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N = 10000;
A = 0;
for i=1:N
    xr = rand(1)*2-1;
    yr = rand(1)*2-1;
    
    if(yr < y(xr) & yr > -y(xr))
        plot(xr, yr, 'x')
        A = A + 1;
    end
end

Asquare = (max(y1)-min(y2))*(max(x)-min(x));
fprintf(1,'area = %f\n', A/N * Asquare)


