/*
 * Integ2.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Java from Basics'
 * section: `Example - Integration a Second Time'
 *
 * This program extends the program Integ.java found earlier in this chapter.
 * Again it performs a simple integration using the trapezium rule, but this
 * time the end points and number of steps are stored in class constants and
 * the function to be integrated is in a separate method.
 */
public class Integ2
{
  // Constants define the endpoints of the integration
  // and the number of steps.
  public static final double LEFT = -4.5;
  public static final double RIGHT = 17.3;
  public static final int STEPS = 1000;


  // The method 'f' is the integrand
  public static double f(double x)
  {
    // Here we choose the function y = | x*x/3 + 4 |
    // We use a local variable z
    double z;

    z = x*x/3 + 4;

    if (z > 0)
      return z;
    else
      return -z;
  }


  // The method main does the integral
  public static void main(String[] argv)
  {
    double total = 0;
    double sectionwidth = RIGHT - LEFT;
    double stepwidth = sectionwidth / STEPS;
    double x, y;
    int i;

    // We are using the trapezium rule, so each end
    // point has a weighting of one.

    total += f(LEFT);
    total += f(RIGHT);

    // whilst each middle point has weight two.
    
    for (i=1 ; i < STEPS; i++)
    {
      x = LEFT + i*stepwidth;
      y = f(x);

      total += 2 * y;
    }

    // Finally, we multiply by half the step size

    total *= stepwidth / 2;

    System.out.println(total);
  }
}

