In: Advanced Math
%%Matlab code for Monte Carlo simulation for finding area of
circle
clear all
close all
%Radius of the circle
r=1;
% number of points generated
N = 10;
a = -r;
b = r;
x = a + (b-a).*rand(N,1);
y = a + (b-a).*rand(N,1);
radii = sqrt(x.^2+y.^2);
hits = sum(radii<=1);
th=linspace(0,2*pi);
x_r=cos(th);
y_r=sin(th);
figure(1)
plot(x_r,y_r,'Linewidth',2)
%Plotting data
k=0;
hold on
for i=1:N
radd=sqrt((x(i)).^2+(y(i)).^2);
if radd<=1
k=k+1;
xx(k)=x(i);
yy(k)=y(i);
plot(x(i),y(i),'r*')
else
plot(x(i),y(i),'b*')
end
end
xlim([-1 1])
ylim([-1 1])
title(sprintf('Monte Carlo plot for N=%d',N))
xlabel('x')
ylabel('y')
ar=4*hits/N;
fprintf('\n\tFor N=%d area of Circle using Monte Carlo method is
%f.\n',N,ar)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
%Radius of the circle
r=1;
% number of points generated
N = 100;
a = -r;
b = r;
x = a + (b-a).*rand(N,1);
y = a + (b-a).*rand(N,1);
radii = sqrt(x.^2+y.^2);
hits = sum(radii<=1);
th=linspace(0,2*pi);
x_r=cos(th);
y_r=sin(th);
figure(2)
plot(x_r,y_r,'Linewidth',2)
%Plotting data
k=0;
hold on
for i=1:N
radd=sqrt((x(i)).^2+(y(i)).^2);
if radd<=1
k=k+1;
xx(k)=x(i);
yy(k)=y(i);
plot(x(i),y(i),'r*')
else
plot(x(i),y(i),'b*')
end
end
xlim([-1 1])
ylim([-1 1])
title(sprintf('Monte Carlo plot for N=%d',N))
xlabel('x')
ylabel('y')
ar=4*hits/N;
fprintf('\n\tFor N=%d area of Circle using Monte Carlo method is
%f.\n',N,ar)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
%Radius of the circle
r=1;
% number of points generated
N = 1000;
a = -r;
b = r;
x = a + (b-a).*rand(N,1);
y = a + (b-a).*rand(N,1);
radii = sqrt(x.^2+y.^2);
hits = sum(radii<=1);
th=linspace(0,2*pi);
x_r=cos(th);
y_r=sin(th);
figure(3)
plot(x_r,y_r,'Linewidth',2)
%Plotting data
k=0;
hold on
for i=1:N
radd=sqrt((x(i)).^2+(y(i)).^2);
if radd<=1
k=k+1;
xx(k)=x(i);
yy(k)=y(i);
plot(x(i),y(i),'r*')
else
plot(x(i),y(i),'b*')
end
end
xlim([-1 1])
ylim([-1 1])
title(sprintf('Monte Carlo plot for N=%d',N))
xlabel('x')
ylabel('y')
ar=4*hits/N;
fprintf('\n\tFor N=%d area of Circle using Monte Carlo method is
%f.\n',N,ar)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%