%script to do monte carlo integration. Integrate sin(x) from 0 to 2 pi
%by Nasser Abbasi. For math 502 CSUF probability and statistics 10/18/07

%example output:
%
%number of simulations=400000
%Estimated integral sin(x) from a..b = 1.999907
%Exact value=2.000000


%----- configuration section ----------%
TRUE  = 1; 
FALSE = 0;

number_of_simulations     = 600000;
current_simulation_number = 0;
current_sum = 0;

a = .3;         %left end of integration interval
b = 1.3*pi;     %right end of integration interval
domain_length = (b-a);

function_to_integrate = @cos;
randn('state',010101);

%------ algorithm start --------------------%

x = a + (b-a).*rand(number_of_simulations,1);
current_sum = sum(feval(function_to_integrate,x));

fprintf('number of simulations=%d\nEstimated integral sin(x) from a..b = %f\nExact value=%f\n',...
    number_of_simulations,...
    current_sum*domain_length/number_of_simulations,...
    quad(function_to_integrate,a,b));

