% mcPi
% Monte Carlo approximation of pi with plot.
% Store all dart positions in vectors.

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