
// RandomPi.java
// Andrew Davison, ad@coe.psu.ac.th, June 2021

/* A Monte Carlo simulation to estimate pi.
   https://ggcarvalho.dev/posts/montecarlo/

   Usage:
     > compile RandomPi.java
     > run RandomPi <no. of tries>
   e.g.
     > run RandomPi 10000
*/

import java.util.*;


public class RandomPi
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run RandomPi <no. of tries>");
      return;
    }

    int num = Integer.parseInt(args[0]);

    StdDraw.enableDoubleBuffering();   // for faster rendering
    StdDraw.setCanvasSize(400, 400);
    StdDraw.setScale(-1.2, 1.2);

    StdDraw.setPenColor(StdDraw.BLUE);
    StdDraw.line(-1.1, 0, 1.1, 0); // x-axis
    StdDraw.text(1.1, 0.1, "X");
    StdDraw.line(0, 1.05, 0, -1.1); // y-axis
    StdDraw.text(-0.05, 1.1, "Y");

    Random r = new Random();

    int nSuccess = 0;
    double x, y;
    for (int i = 0; i < num ; i++) {
      x = 2*r.nextDouble()-1;    // -1 to 1
      y = 2*r.nextDouble()-1;
      if (x*x + y*y <= 1.0) {
        nSuccess++;
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.filledCircle(x, y, 0.008);
      }
      else {
        StdDraw.setPenColor(StdDraw.GREEN);
        StdDraw.filledCircle(x, y, 0.008);
      }
    }

    StdDraw.setPenColor(StdDraw.BLACK);
    StdDraw.circle(0, 0, 1);

    double rPi = 4*(double)nSuccess/num;
    System.out.println("Random Pi = " + rPi);
    System.out.println("Java's Pi = " + Math.PI);
    StdDraw.show();

    System.out.printf("Error: %.3f %%\n",
                             100*(Math.PI - rPi)/Math.PI );
  } // end of main()


} // end of RandomPi class

