% cs3113f08HW02P03.m
% Monte Carlo simulation to compute the volume of 
% water inside a spherical tank.
% K. Ming Leung, September 21, 2008
% 10 pts total

clear;
nPoints = 10000000; repeat = 5; 
ztop = -0.8;    % height of water measured from origin
XX = 2*rand(repeat,nPoints) - 1;
YY = 2*rand(repeat,nPoints) - 1;
ZZ = 2*rand(repeat,nPoints) - 1;

nInside = sum((XX.^2+YY.^2+ZZ.^2 <= 1) & ZZ <= ztop,2);
Volumes = 8*nInside/nPoints;
h = ztop+1; % height of water measured from the bottom
vexact = pi*h*h*(3-h)/3;
RelativeErrors = Volumes/vexact - 1,
volume = mean(Volumes)
relativeError = volume/vexact - 1





