
% to calculate the value of pi through monte carlo simulations.
% file : /home/patil/public_html/pi_by_monte.m
% Program by Sanjay A Patil 
% Created on November 30, 2004. 1800 hours central time
% As part of the Particle Filtering Presentation
% being held from November 29, 2004 to December 03, 2004
% The idea of the Presentation is to-get-going 
% The nonlinear Stastistical Modeling of Speech Group.
%
% Monte Carlo Simulations is about picking random numbers to the task and
% then applying rules of probability, to estimate the result.

% Here we have to calculate the value of pi = 3.142 by monte carlo
% simulations
% Here in our idea is to estimate value of pi by using the formula
% pi = 4 times # of times the random number lie within a circle divided by
%      # of times the random number was generated.

% =========================================================================
%                     ( # within a circle)
%    pi =    4 x  ----------------------------
%                   ( # of total iterations)
% =========================================================================

% to clear the workspace of all the variables
%
clear all;
clc;

% primary variable declaration
% idea is to calculate value of pi of different number of iterations
% so as to get an idea as to how the # of iterations can affect the estimate
% But, it is important to remember, larger # of iterations need not gaurantee 
% better estimate (of pi).
% Also one more observation, because we are picking random number, the
% estimate varies drastically.
%
iterate_start = 25; % starting value of the iteration
iterate_end = 1000; 
step = 150; % defines the jump in the value of iterations
index = 1; % to store values of pi for different iterations

for iterate = iterate_start : step : iterate_end
    
    % to random numbers used as cartesian coordinates of a point
    % the function rand generates uniformly distributed random number
    % between (0,1).
    %
    x = rand(1, iterate);
    y = rand(1, iterate);
    
    % value of the pi will be stored here
    %
    counter(index) = 0;
    
    % to pick the each point (x,y) and check whether it lies within a
    % circle
    %
    for i = 1 : 1 : iterate
        % circle condition
        %
        if ( x(i)^2 + y(i)^2 <= 1)
            counter(index) = counter(index) + 1;
        end;
        
    end;
    
    % actual calculations
    % 
    counter(index) = 4 * counter(index) / iterate;
    
    % let us go for one more iterations
    %
    index = index + 1;
    
end;

% display the value of pi for all the iterations
%
disp(' The values of pi as the # of iterations increases : ');
disp([num2str(counter)]);