% mcPi
% Monte Carlo approximation of pi with plot.
% Use VECTORIZED arithmetic.

axis equal off
hold on

L= 10; % length of square (diameter of circle)
R= L/2; % half length (radius)

N= 10000; % total number of darts
% Throw darts
x= rand(1,N)*L - R;
y= rand(1,N)*L - R;
distFromCenter= sqrt(x.^2 + y.^2);
nHits= 0; % number of darts in the circle so far
for k= 1:N

if distFromCenter(k) <= R
nHits = nHits + 1;
plot(x(k), y(k), 'b.', 'MarkerSize', 6)
else
plot(x(k), y(k), 'r.', 'MarkerSize', 6)
end
end

hold off

myPi = (nHits/N)*4;
err = abs(myPi - pi);
fprintf('My pi is %.2f (error is %.3f)\n', myPi, err)
fprintf('Based on %d trials\n', N)