% Topic: Using the Monte Carlo method for finding probabilites 
% Case study: 2-D case (Circle inside a square. Probability that randomly(uniformly) choosen point lays inside the circle)
% And also an interesting method for finding the value of "pi"!
% If you have any question, send an email to: asahebpa@uwaterloo.ca
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all
clc
clear all

number = 100000; % Number of points
Radius = 1;
Area_of_Circle = pi*Radius^2;
Area_of_Square = (2*Radius)^2;
xpoint = 2*Radius*rand(1, number) - Radius; % X coordinate values for points
ypoint = 2*Radius*rand(1, number) - Radius; % Y coordinate values for points
check = zeros(1, number);

for i = 1:number % Loop on all points
   if (xpoint(i)^2 + ypoint(i)^2) < Radius^2 % Checking location of each point (Inside circle or not)
     
      check(i) = 1; % The point is inside circle
     
   end 
end


Probablitiy_beinginside_MonteCarlo = sum(check) / number % For being more accurate, increase "number"
Probablitiy_beinginside_Analytical = Area_of_Circle / Area_of_Square 
Pi_approximation = 4 * Probablitiy_beinginside_MonteCarlo;

hold all

plot(xpoint(find(check==1)), ypoint(find(check==1)), '*')
plot(xpoint(find(check~=1)), ypoint(find(check~=1)), 'o')
str = title('Probability for a point to being inside a circle = $\frac{Number of bluepoints}{Number of bluepoints + Number of redpoints}$');
set(str, 'Interpreter','latex')