A hit and miss Monte Carlo algorithm for estimating Pi
can easily be typed into Mathematica. The principle here is that a ratio of
two areas is estimated by counting how often pairs of random numbers
fall into each of the two areas (`darts' thrown at a dartboard inscribed
in a square, so the ratio of areas is
).
 | Clear[ndarts,xcoord,ycoord,distance2,nhits,piest];
ndarts=100;
xcoord = Table[Random[]-0.5, {n,1,ndarts}];
ycoord = Table[Random[]-0.5, {n,1,ndarts}];
distance2 =xcoord^2 + ycoord^2;
nhits = Count[distance2, x_ /; x <= .25];
piest = 4.0*nhits/ndarts |
Here the Count command finds how often a condition,
,
is satisfied in the list distance2. This gives how often the darts land
within the dartboard (the distance squared from the center is calculated and
compared with the radius squared, which is
).
The dartboard and the impact points can be displayed nicely by loading the
graphics module located in the file ~hannes/Chem465/dartboard,
 | <<dartboard |
Run the dart calculation a few times varying the number of darts used to
see roughly how good the estimate of pi is.
Hannes Jonsson
Modified by Thomas L. Marchioro II
and the Undergraduate Computational Engineering and Science project