% Monte-Carlo simulation - area of a circle

N=100;   % Number of random points in each trial

% --- Generate points to draw a circle (in red) ---
fi=0:0.01:2*pi; % angular coordinate
cX=1+1*cos(fi);
cY=1+1*sin(fi);
% -------------------

% Generate a set of N random (x,y) pairs between 0 and 2 
X=unifrnd(0,2,N,1);
Y=unifrnd(0,2,N,1);

plot(X,Y,'.',cX,cY,'r')
%%
% Repeat many times
N=100;
ntrials=1000;   % <-- total number of Monte-Carlo experiments

for j=1:ntrials
X=unifrnd(0,2,100,1);
Y=unifrnd(0,2,100,1);

IN=0;
OUT=0;
for i=1:N
    if sqrt((X(i)-1)^2+(Y(i)-1)^2)<1    % if inside -> increase IN
        IN=IN+1;
    else
        OUT=OUT+1;              % if outside -> increase OUT
    end
end
INTOT(j)=IN; 
OUTTOT(j)=OUT;
end
%%
hist(INTOT)         % plot the number of points 'inside' in a histogram
mean(INTOT)
%%
% Calculate the area of the circle
Asquare=2*2;
Area=Asquare*mean(INTOT)/N
