% mcPi
% Monte Carlo approximation of pi

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

N= 10000;   % total number of darts
hits= 0;    % number of darts in the circle so far
for k= 1:N
    % Throw kth dart
    x = rand(1)*L-R;
    y = rand(1)*L-R;
    if sqrt(x^2+y^2)<=R
        hits = hits + 1;
    end 
end

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)