/*
 * PIComputation.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Java from Basics'
 * section: `Example - Computation of Pi'
 *
 * This program computes pi. It forms a square grid of points across the
 * region |x| < 1, |y| < 1. It then counts how many of these points are inside
 * a unit circle centred on the origin, and uses this to estimate the area of
 * the circle relative to that of the square region, and hence to compute pi.
 * Note that we use a method call to initialize the constant PI.
 */
public class PIComputation
{
  // Constant number of grid squares per unit
  public static final int GRID = 100;

  // The constant PI to be computed
  public static final double PI = computePi();


  // The method 'inside' checks if the point x, y
  // lies inside a unit square centred on the origin.
  public static boolean inside(double x, double y)
  {
    // Use Pythagoras's theorem.
    if (x*x + y*y <= 1)
       return true;
    else
      return false;
  }


  // The method 'computePi' steps across the grid in the
  // square |x|<=1, |y|<=1, counting the number of
  // grid points inside a unit circle.
  public static double computePi()
  {
    int count = 0;
    double x, y;

    // Set up two loops to step across the grid
    // We consider the middle point in each
    // grid square.
    for (int xstep=-GRID; xstep<GRID; xstep++)
    {
      // Calculate the x position
      x = (xstep + 0.5) / GRID;
    
      for (int ystep=-GRID; ystep<GRID; ystep++)
      {
        // Calculate the y position
        y = (ystep + 0.5) / GRID;

        // Count that point if it is inside
        if (inside(x,y))
          count++;
      }
    }

    // Finally, the area of the square should be 4,
    // whilst the area of the circle is Pi.
    // Divide by the number of squares per unit
    // area to compute Pi.

    return ((double)count) / (GRID*GRID);
  }


  // The main method just prints the constant.
  public static void main(String[] argv)
  {
    System.out.println(PI);
  }
}

