function estimate = approxPi(nDarts)
% Approximate pi using Monte Carlo simulation.
% nDarts = number of darts thrown in the simulation

% Written by Paul Chew for CS100M, Mar 2006

throws = -1 + 2*rand(nDarts, 2);    % Compute all dart throws
x = throws(:, 1);
y = throws(:, 2);

dist = sqrt(x.^2 + y.^2);           % Compute all distances from center
in = sum(dist <= 1);                % Count number inside circle
estimate = 4 * in/nDarts;           % Estimate pi

% Draw a nice picture of the simulation
theta = 2*pi*(0:.01:1);
xCircle = cos(theta);
yCircle = sin(theta);
plot(x, y, 'o', xCircle, yCircle, '-r');
axis([-1 1 -1 1], 'square');
title(['Pi is approximately ' num2str(estimate)]);