% mcPi
% Monte Carlo approximation of pi with plot.

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

nHits= 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
nHits = nHits + 1;
plot(x, y, 'b.', 'MarkerSize', 6)
else
plot(x, y, 'r.', 'MarkerSize', 6)
end
end

hold off

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