function myPi = piApproxSub(nDarts, L)
% Monte Carlo approximation of pi
% Throws nDarts darts at an LxL board.

    r= L/4;     % Inner radius of annular target
    hits= 0;    % number of darts in the circle so far
    for k = 1:nDarts
        [x, y]= throwDart(L);

        %if isInAnnulus(x, y, L/2, r)
        if isInCircle(x, y, L/2)
            hits= hits + 1;
        end
    end

    %myPi = piFromAnnulus(hits/nDarts, r/(L/2));
    myPi = piFromCircle(hits/nDarts);
end

function [x, y] = throwDart(L)
% Generate a uniformly random point in an LxL square
% Square is centered at the origin.
    x = rand()*L - L/2;
    y = rand()*L - L/2;
end

function b = isInCircle(x, y, r)
% Is point (x, y) within a circle of radius r?
    b = x^2 + y^2 < r^2;
end

function p = piFromCircle(prob)
% Approximate pi if prob is probability of hitting a circle
% inscribed in a square.
    p = 4*prob;
end

function b = isInAnnulus(x, y, r, a)
% Is point (x, y) with in an annulus of outer radius r and
% inner radius a?
    b = (x^2 + y^2 < r^2) && (x^2 + y^2 > a^2);
end

function p = piFromAnnulus(prob, rRatio)
% Approximate pi if prob is probability of hitting an annulus
% inscribed in a square whose ratio of inner to outer radius
% is rRatio.
    p = 4*prob/(1 - rRatio^2);
end
