/*
 * Limit.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Java from Basics'
 * section: `Example - Limiting Processes'
 *
 * This program considers the simple iteration scheme
 * x(n+1) = x(n) / ( x(n) + 1)
 * It repeatedly performs the iteration to a starting value in order to find
 * the limit to which the value of x converges. Note that the method `abs' is
 * used before it is defined. Such out of order usage is possible in Java.
 */
public class Limit
{
  // Constants define number of iterations,
  // starting point and final error required.
  public static final int STEPS = 1000;
  public static final double START = 1.0;
  public static final double ERROR = 10e-6;


  // The method 'f' is to be iterated
  public static double f(double x)
  {
    return x / (x+1);
  }


  // The method 'main' does the iteration
  public static void main(String[] argv)
  {
    double current, last;
    int i=1;

    last = START;
    current = f(START);
    System.out.println(START);

    // Iterate until either we've done as many steps
    // as required or the convergence has become slow
    // enough that we may be near the limit of the series.
    while ((i <= STEPS) && (abs(current-last) > ERROR))
    {
      System.out.println(current);
      last = current;
      current = f(current);
      i++;
    }

    // Check whether it did converge and print
    // appropriate text.
    if ((i == STEPS) && (abs(current-last) > ERROR))
      System.out.println("No convergence");
    else
      System.out.println("Convergent to: " + current);
  }


  // The method 'abs' returns the absolute value
  // of a floating point number.
  public static double abs(double s)
  {
    if (s>0)
      return s;
    else
      return -s;
  }
}

