Game Development Reference
In-Depth Information
as computed by Equation (15.10) increases
with an increasing number of sample points. And because Monte Carlo simulations are prob-
abilistic, a different answer will be obtained every time the simulation is run. The difference
between subsequent simulations should decrease with increasing sample size.
Let's write a simple code that will use a Monte Carlo simulation to estimate
Like all Monte Carlo simulations, the accuracy of
π
according to
Equation (15.10). The GUI for the PiEstimator class is shown in Figure 15-9. It has two text field
components—one allows the user to input the sample size to be used, and the other displays
the computed value of
π
. There is a Start button that starts the simulation, and a Reset button
that clears the display. On the right-hand side of the GUI is a panel that shows the circle and the
square and where the sample points lie.
π
Figure 15-9. A typical screen shot when the PiEstimator program is run
We won't go over the entire PiEstimator class code listing, but we will discuss the
actionPerformed method that is called when the Start button is pressed. The first thing the
method does is to extract the sample size value from the text field. It then creates a Random
object that will generate the random x-y coordinate points. The Random object is “seeded” by
default with the current time in milliseconds. The seed will be different every time the method
is called so the random number sequence will be different.
// The actionPerformed() method is called when
// the Start button is pressed.
public void actionPerformed(ActionEvent event) {
// Extract sample size number from text field
int sampleSize = Integer.parseInt(sampleSizeTextField.getText());
// Create a Random object to generate random
// numbers. The object is seeded with the current
// time.
Random random = new Random();
Search WWH ::




Custom Search