Homework: Monte Carlo Estimation
In preparation for the lab, carefully review the code below and answer these questions.
- What does this program do?
- What is the program output if the user enters 10000 when prompted for the number of points?
- How would your answer to the above question change if the test in
line 15 used
<=rather than<? - Print the homework or copy and paste the code below in your homework. Draw a box around each statement, and underline each expression, in the code. (Even though technically an assignment in Java is an expression, do not underline entire assignments.)
The Random component provides a pseudo-random number generator that
generates numbers uniformly distributed in the `[0.0,1.0)` interval; the
method call rnd.nextDouble() returns a pseudo-random number in the
`[0.0,1.0)` interval. (In case you're not familiar with the notation
here, `[0.0,1.0)` denotes an interval consisting of all real numbers
between 0.0 inclusive and 1.0 exclusive, i.e., the set of all values `x`
satisfying `0.0 ≤ x < 1.0`.)
1 public static void main(String[] args) {
2 SimpleReader input = new SimpleReader1L();
3 SimpleWriter output = new SimpleWriter1L();
4
5 output.print("Number of points: ");
6 int n = input.nextInteger();
7
8 int ptsInInterval = 0, ptsInSubinterval = 0;
9
10 Random rnd = new Random1L();
11
12 while (ptsInInterval < n) {
13 double x = rnd.nextDouble();
14 ptsInInterval++;
15 if (x < 0.5) {
16 ptsInSubinterval++;
17 }
18 }
19
20 double estimate = (100.0 * ptsInSubinterval) / ptsInInterval;
21 output.println("Estimate of percentage: " + estimate + "%");
22
23 input.close();
24 output.close();
25 }