% 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
x= rand(1,N)*L-R;
y= rand(1,N)*L-R;
dista= sqrt(x.^2 + y.^2);
hits= 0;    % number of darts in the circle so far
for k= 1:N
    % Throw kth dart
    if dista(k)<=R
        hits = hits + 1;
        plot(x(k),y(k),'m*')
    else
        plot(x(k),y(k),'kx')
    end 
end

hold off

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