Pi (not the raspberry, but our irrational friend)
Posted: Wed Sep 12, 2012 4:51 am
This is particularly off topic, but anyway, I'm taking a computer science course as a co-requisite for the ordinary differential equations class that I'm also taking, and we had to write a couple of programs for MATLAB that approximated our irrational friend, pi (also known as the ratio Circumference/Diameter ).
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
Edit: I forgot to mention, if you get a chance to run the program, try messing around with N - it can go up to at least N=100*10^6 (which even on my i5 quad core takes about 3 seconds for MATLAB to compute, and then that wasn't even printing out matrix A, which I just added for fun to pair up the coordinates with their distance from the origin).
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