I thought this one we did was particularly cute, since it involves using random numbers (which is why I thought I'd share it ).
(Incidentally, one does not need MATLAB to run this program, GNU Octave is an open source matrix lab for Linux, BSD, and Cygwin).
So the idea here is if you have a unit square centered at the origin, with a circle of r=1/2 inscribed within. If you were to take N number of darts and throw them at the circle/square, as N increases, the ratio #hits in circle/#hits in the square is approximately equal to the ratio Area of Circle/Area of Square. With an area of the circle pi/4 units^2 and the area of the square 1 unit^2, the ratio Area of Circle/Area of Square = pi/4. Solving for pi, we get pi=4*Area of Circle/Area of Square=4*#hits in circle/#hits in the square
Code: Select all
% Defining how many hits within the unit square total
N=1000;
% Defining x and y coordinates of the hits within the unit square
xr=rand(1,N)-0.5;
yr=rand(1,N)-0.5;
% Distance of each hit from the origin
dfo=((xr).^2+(yr).^2).^0.5;
% Determining the hit totals
hin=sum(dfo<0.5); % hits within the circle
hout=sum(dfo>0.5); % hits outside the circle - for fun
% Approximating Pi
pi_apprx=4*hin/N;
% Percent Error calculation
Err=100.*(abs(pi-pi_apprx)./pi);
A=[xr;yr;dfo]
pi_apprx
Err