% circle_area.m
%
%  A circle of radius 1 has area pi.
%
%  Suppose we didn't know this.  We could estimate the area of a circle
%  by picking random points in the square of "radius 1", which has area 4.
%
%  The area of the circle would be estimated by
%
%    Circle area = Square area * number of points in circle / number of points.
%
n = input ( '  Enter N, the number of points to use: ' );

inside = 0;

for i = 1 : n
%
%  rand returns a number between 0 and 1.
%  2*rand-1 is a number between -1 and +1.
%
  x = 2 * rand ( ) - 1.0;
  y = 2 * rand ( ) - 1.0;

  if ( x^2 + y^2 <= 1.0 )
    inside = inside + 1;
  end

end

area = 4.0 * inside / n;

fprintf ( '  %d point area estimate is %g, error is %g\n', ...
  n, area, abs ( pi - area ) );
