Simulating Buffon's needle on Matlab

2.9k Views Asked by At

I am trying to simulate dropping Buffon's needle onto an A4 sheet of paper, but I am not sure how can I construct an A4 size area (21 x 29.7) and define 2 vertically line at 7cm and 14cm in Matlab. I also need to check if the needle(5cm) has crossed a line or crossed the edges of the paper, How can I achieve that ?

1

There are 1 best solutions below

2
On BEST ANSWER
clc,clear

%Note that the condition 'an A4 paper' is in fact not used.

n=1e5;
l=7;
a=5;

s=0;

for i=1:1:n
    x=l+l*rand;         %If we use 'x=3*l*rand', we should study the cases where x=0 and x=3*l.
    %y=29.7*rand;       The value of y is in fact useless.
    theta=pi*rand;
    d1=abs(x-l);
    d2=abs(x-2*l);
    theta1=pi-acos(d1/a);
    theta2=acos(d2/a);
    if theta<theta1 && theta>theta2
        s=s+0;
    else
        s=s+1;
    end
end

p=2*a*n/l/s;
er=abs(p-pi);

fprintf('Pi=%f with n=%.e and er=%.e\n\n',p,n,er);

Just for fun :D