% mcPi
% Monte Carlo approximation of pi

close all % close all figure windows
figure % new figure window
axis equal off % all axes: same scale, no display
hold on % hold all calls to plot on current axes

L= 10; % length of square (diameter of circle)
R= L/2; % half length (radius)
axis([-R R -R R]) % axis limits

N= 10000; % total number of darts
hits= 0; % number of darts in the circle so far
for k = 1:N
% Throw kth dart
x= rand()*L - R;
y= rand()*L - R;
if sqrt(x^2 + y^2) <= R
plot(x,y,'.r')
hits= hits + 1;
else
plot(x,y,'.b')
end
end

myPi= 4*hits/N;
err= abs(myPi-pi);
title(sprintf('Pi Estimate = %6.3f Error = %6.2e', myPi, err),...
'Fontsize',14)

hold off % next call to plot will be on new axes
shg % Show Handle Graphics (bring figure window to the front)