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

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);
hits = distFromCenter <= R;
nHits = sum(hits); % number of darts in the circle

plot(x(hits), y(hits), 'b.', ...
x(~hits), y(~hits), 'r.', 'MarkerSize', 6)

axis equal 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)