Java Reference
In-Depth Information
3and prints the resulting approximations of pi.
4 */
5 public class NeedleSimulator
6 {
7 public static void main(String[] args)
8 {
9 Needle n = new Needle();
10 final int TRIES1 = 10000;
11 final int TRIES2 = 1000000;
12
13 for (int i = 1; i <= TRIES1; i++)
14 n.drop();
15 System.out.printf(ÐTries = %d, Tries
/ Hits = %8.5f\nÑ,
16 TRIES1, (double)
n.getTries() / n.getHits());
17
18 for (int i = TRIES1 + 1; i <=
TRIES2; i++)
19 n.drop();
20 System.out.printf(ÐTries = %d, Tries
/ Hits = %8.5f\nÑ,
21 TRIES2, (double)
n.getTries() / n.getHits());
22 }
23 }
Output
Tries = 10000, Tries / Hits = 3.08928
Tries = 1000000, Tries / Hits = 3.14204
The point of this program is not to compute ƚȌthere are far more efficient ways to do
that. Rather, the point is to show how a physical experiment can be simulated on the
computer. Buffon had to physically drop the needle thousands of times and record the
results, which must have been a rather dull activity. The computer can execute the
experiment quickly and accurately.
Simulations are very common computer applications. Many simulations use
essentially the same pattern as the code of this example: In a loop, a large number of
sample values are generated, and the values of certain observations are recorded for
Search WWH ::




Custom Search