% area_under_curve_random.m
%
%  Estimate the area between the x axis and the curve y=x^2 for 0<=x<=1.
%
%  Strategy: use random sampling.  The minimum value of y is 0, and the
%  maximum is 1.  Therefore, the area we are interested in is a subset
%  of the unit square: 0 <= x <= 1, 0 <= y <= 1.
%
%  The unit square has area 1.
%
%  If we pick points (x,y) at random in this square, only some lie below
%  the curve.  The number of points that lie below the curve, M, divided
%  by the total number of points we investigated, N, gives us an estimate
%  of the relative size of the area we are interested in.
%
n = input ( '  Enter number of sample points: ' );
m = 0;
area_square = 1.0;

for i = 1 : n
  x = rand ( );
  y = rand ( );
  if ( y <= x^2 )
    m = m + 1;
  end
end

area_curve = ( m / n ) * area_square;

fprintf ( '  Estimate area under y=x^2 is %g\n', area_curve );
fprintf ( '  Exact area is %g\n', 1 / 3 );

