Game Development Reference
In-Depth Information
The actionPerformed method then creates the sample points using random numbers
generated by the Random object. The location of the sample points is displayed in the panel
on the right-hand side of the GUI display.
// Create the sample points. Generate
// two random numbers representing a data point.
// See if the data point is inside the circle area
// or not.
double x;
double y;
double distance;
int numInCircle = 0;
double piValue = 0.0;
for(int j=0; j<sampleSize; ++j) {
// Generate an x-y point.
x = random.nextDouble();
y = random.nextDouble();
// Display the sample point on the screen.
int xLoc = (int)(200.0*x);
int yLoc = (int)(200.0*y);
drawingPanel.getGraphics().drawString("+", xLoc, yLoc);
Once the sample point is obtained and displayed on the screen, the method determines
whether the sample point lies inside the circle by determining the distance from the point to
the origin of the circle. If the point does lie inside the circle, the number of circle points is incre-
mented. The value of
π
is then computed using Equation (15.10). The value “j+1.0” is used
when computing
π
to correct for the fact that Java uses a zero-based numbering system.
// Determine if the point is inside the circle
// by computing the distance from the point to
// the center of the circle. If the distance is
// less than 1, the point is inside.
distance = Math.sqrt((x-0.5)*(x-0.5) + (y-0.5)*(y-0.5));
if ( distance <= 0.5 ) {
++numInCircle;
}
// Update the value of pi.
piValue = 4.0*numInCircle/(j+1.0);
piValueTextField.setText(""+(float)piValue);
}
}
Play around with the PiEstimator program. Start by setting the sample size to a low value
like 10. You'll notice that the results aren't all that accurate and that they vary quite a bit from
run to run. Increase the sample size to 100 and then 1000 and see what happens to the accuracy
and variability of the results. Try a really big sample size like 29987 and see what happens.
Search WWH ::




Custom Search