The original code, written in `MonteCarlo.java`, generates pseudo-random numbers in...

September 3, 2025 at 06:06 PM

import components.random.Random; import components.random.Random1L; import components.simplereader.SimpleReader; import components.simplereader.SimpleReader1L; import components.simplewriter.SimpleWriter; import components.simplewriter.SimpleWriter1L; /** * Monte Carlo Estimate: compute percentage of pseudo-random points in [0.0,1.0) * interval that fall in the left half subinterval [0.0,0.5). */ public final class MonteCarlo { /** * Private constructor so this utility class cannot be instantiated. */ private MonteCarlo() { } /** * Main method. * * @param args * the command line arguments; unused here */ public static void main(String[] args) { /* * Open input and output streams */ SimpleReader input = new SimpleReader1L(); SimpleWriter output = new SimpleWriter1L(); /* * Constant to convert a ratio into a percentage */ final double percentageFactor = 100.0; /* * Ask user for number of points to generate */ output.print("Number of points: "); int n = input.nextInteger(); /* * Declare counters and initialize them */ int ptsInInterval = 0, ptsInSubinterval = 0; /* * Create pseudo-random number generator */ Random rnd = new Random1L(); /* * Generate points and count how many fall in [0.0,0.5) interval */ while (ptsInInterval < n) { /* * Generate pseudo-random number in [0.0,1.0) interval */ double x = rnd.nextDouble(); /* * Increment total number of generated points */ ptsInInterval++; /* * Check if point is in [0.0,0.5) interval and increment counter if * it is */ if (x < 0.5) { ptsInSubinterval++; } } /* * Estimate percentage of points generated in [0.0,1.0) interval that * fall in the [0.0,0.5) subinterval */ double estimate = (percentageFactor * ptsInSubinterval) / ptsInInterval; output.println("Estimate of percentage: " + estimate + "%"); /* * Close input and output streams */ input.close(); output.close(); } } Modify MonteCarlo.java so that it generates 2-dimensional points in the [0.0,2.0) x [0.0,2.0) square and estimates the area of the circle of radius 1 centered at (1.0,1.0). (See the Monte Carlo slides for this lab for some additional information.) Run your program with different number of points and discuss the following questions with your partner: What is the area of a circle of radius 1? How well does your program estimate it? How is the estimate affected by the number of points generated?

The original code, written in MonteCarlo.java, generates pseudo-random numbers in the range [0.0, 1.0) and estimates the percentage of these points that lie in the range [0.0, 0.5). Below, I explain how to modify this program to estimate the area of a circle with radius 1 centered at (1.0, 1.0) using the Monte Carlo method.


Modified Code Explanation

Instead of generating 1D points in [0.0, 1.0), modify the code to generate 2D points (x, y) in the square [0.0, 2.0) x [0.0, 2.0) and evaluate how many of them fall inside a circle of radius 1 centered at (1.0, 1.0).

Steps for modification:

  1. Adjust the random point generation to produce both x and y coordinates in the range [0.0, 2.0).
  2. Use the equation of a circle to determine whether the point (x, y) lies inside or on the circle: [ \text{Point is inside circle if: } (x - 1.0)^2 + (y - 1.0)^2 \leq 1^2 ]
  3. Count how many generated points fall inside the circle.
  4. Use the ratio of points inside the circle (ptsInCircle) to total points generated (ptsInSquare) multiplied by the area of the square (4.0 since [0.0, 2.0) x [0.0, 2.0) has an area of (2.0 \times 2.0 = 4.0)) to estimate the area of the circle.

Here is the modified program:


public final class MonteCarlo {

    /**
     * Private constructor so this utility class cannot be instantiated.
     */
    private MonteCarlo() {
    }

    /**
     * Main method.
     *
     * @param args
     *            the command line arguments; unused here
     */
    public static void main(String[] args) {
        /*
         * Open input and output streams
         */
        SimpleReader input = new SimpleReader1L();
        SimpleWriter output = new SimpleWriter1L();
        /*
         * Constant for the area of the square (2.0 x 2.0)
         */
        final double squareArea = 4.0;
        /*
         * Ask user for number of points to generate
         */
        output.print("Number of points: ");
        int n = input.nextInteger();
        /*
         * Declare counters and initialize them
         */
        int ptsInSquare = 0, ptsInCircle = 0;
        /*
         * Create pseudo-random number generator
         */
        Random rnd = new Random1L();
        /*
         * Generate random points and count how many fall in the circle
         */
        while (ptsInSquare < n) {
            /*
             * Generate pseudo-random x and y coordinates in [0.0, 2.0)
             */
            double x = 2.0 * rnd.nextDouble(); // [0.0, 2.0)
            double y = 2.0 * rnd.nextDouble(); // [0.0, 2.0)
            /*
             * Increment total number of generated points
             */
            ptsInSquare++;
            /*
             * Check if point is in the circle and increment counter if it is
             */
            if (Math.pow(x - 1.0, 2) + Math.pow(y - 1.0, 2) <= 1.0) {
                ptsInCircle++;
            }
        }
        /*
         * Estimate the area of the circle based on the ratio of points in the
         * circle to points in the square
         */
        double circleAreaEstimate = (squareArea * ptsInCircle) / ptsInSquare;
        output.println("Estimate of circle area: " + circleAreaEstimate);
        /*
         * Close input and output streams
         */
        input.close();
        output.close();
    }

}

Key Changes

  1. The random number generator now produces both x and y coordinates in [0.0, 2.0).
  2. A new condition checks whether the point (x, y) lies inside the circle using the equation ((x - 1.0)^2 + (y - 1.0)^2 \leq 1^2).
  3. The estimated circle area is calculated as: [ \text{circleAreaEstimate} = \frac{\text{ptsInCircle}}{\text{ptsInSquare}} \times \text{squareArea} ]

Questions

  1. What is the area of a circle of radius 1? The area of a circle is calculated using the formula: [ \text{area} = \pi r^2 ] Substituting (r = 1), the actual area of the circle is: [ \pi \approx 3.14159 ]

  2. How well does your program estimate it?

    • The program will give a reasonably accurate estimate of (\pi) using the Monte Carlo method.
    • The accuracy improves as the number of points increases since the ratio of points within the circle versus the square converges to the true ratio.
  3. How is the estimate affected by the number of points generated?

    • For a low number of points ((n)), there will be more variability due to randomness, leading to less accurate estimates.
    • As (n) increases, the randomness averages out, reducing the error and producing a result closer to the true value of (\pi).

Example Outputs (Estimates)

If run with 500, 1000, and 10,000 points, the outputs might look like:

  • For (n = 500): Estimated area = 3.09
  • For (n = 1000): Estimated area = 3.14
  • For (n = 10,000): Estimated area = 3.1415

As (n) increases, the estimate becomes more accurate and approaches the true area ((\pi)).

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node