You are on page 1of 2

Slide 3

tic
N=1000;
% Number of points
x=rand(N,1)*2-1;
% uniform random values for x-coordinates
y=rand(N,1)*2-1;
% uniform random values for y-coordinates
insideCircle=x.^2+y.^2.<1;
% array for all points 1 if point inside, 0 if not
pointsInCircle=nnz(insideCircle);
% number of points in circle
pi_sim=4*pointsInCircle/N;
%calculated value for pi
toc
plot(x,y,'MarkerSize',10,'Marker','.','LineStyle','none'); % plot random points
hold 'on'
% prepare to add the plot of the circle
axis equal
% adjust x to y ratio, so circle is round
phi=0:361;
% angles of the circle points
xc=cos(phi.*pi/180);
% x-coordinates of the circle
yc=sin(phi.*pi/180);
% y-coordinates of the circle
plot(xc,yc,'LineWidth',2,'Color',[1 0 0])
% plot circle
set(gca,'FontSize',14);
toc

Slide 4
N=1000;
x=zeros(N,1);
y=zeros(N,1);
pointsInCircle=0;
for i=1:N
%Throw the die for a single point
Single_x=rand()*2-1;
Single_y=rand()*2-1;
% Is this point inside the circle ?
if Single_x^2+Single_y^2<1
pointsInCircle=pointsInCircle+1;
end
% add single point to array of all points
x(i)=Single_x;
y(i)=Single_y;
end
pi_sim=4*pointsInCircle/N;
% calculate pi
% plot points
plot(x,y,'MarkerSize',1,'Marker','.','LineStyle','none');
hold 'on'
axis equal
xk=zeros(361,1);
yk=zeros(361,1);
for phi=1:361
xk(phi)=cos(phi*pi/180);
yk(phi)=sin(phi*pi/180);
end
plot(xk,yk,'LineWidth',2,'Color',[1 0 0])
set(gca,'FontSize',14);

Slide 10
N=10000000;
% Number of families
sex1=randi(2,N,1);
% sex of child 1
sex2=randi(2,N,1);
% sex od child 2
day1=randi(7,N,1);
% Weekday of birthday of child 1
day2=randi(7,N,1);
% Weekday of birthday of child 2
oneTuesdayBoy=sex1==1 & day1==2 | sex2==1 & day2==2;
TwoBoys=sex1==1 & sex2==1;
oneTuesdayBoyAndTwoBoys=oneTuesdayBoy & TwoBoys;
p=nnz(oneTuesdayBoyAndTwoBoys)/nnz(oneTuesdayBoy)

You might also like