% throw: Throw multiple darts at a simple target
% Point (px,py) is where the dart lands
%
% Written by Paul Chew for CS100M, Feb 2006

close all                   % Close all previous figure windows

% Create the square (centered at origin; side length = 2)
hold on
axis('equal');              % Make the units the same length on each axis
axis([-1 1 -1 1]);          % Specify min and max values for each axis

count = 2000;
countIn = 0;
for n = 1:count
    % Compute position of "dart"
    px = 2*rand - 1;
    py = 2*rand - 1;
    if (px^2 + py^2 <= 1)   % If within circle...
        plot(px, py, 'og'); % Hit
        countIn = countIn + 1;
    else
        plot(px, py, 'or'); % Miss
    end
end

% Report approximation of pi:
% Count is proportional to square's area (= 4); countIn is proporitional
% to circle's area (= pi).
approxPi = 4*countIn/count;
fprintf('After %d trials, pi is approximately %.2f\n', count, approxPi);
