% Use Monte Carlo method to compute probability of Buffon's needle N = input('Enter number of sample points: '); volumeofBox=pi/2; % the box is [0, pi]*[0,0.5]; vol =0; mass = 0; for i =1:N, % loop over all sample points theta=0.0+pi*rand; % Gererate a point in the sourrounding box y = 0.0 + 0.5*rand; if y<= 0.5*sin(theta), vol = vol+1; end; end; volumeofobj = (vol/N)* volumeofBox % fraction of pts inside times vol of box p = volumeofobj/volumeofBox