///////////////////////////////////////////////////////////////////////////
//                                                                       //
// Program file name: Bond.java                                          //
//                                                                       //
// © Tao Pang 2006                                                       //
//                                                                       //
// Last modified: January 18, 2006                                       //
//                                                                       //
// (1) This Java program is part of the book, "An Introduction to        //
//     Computational Physics, 2nd Edition," written by Tao Pang and      //
//     published by Cambridge University Press on January 19, 2006.      //
//                                                                       //
// (2) No warranties, express or implied, are made for this program.     //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

// An example of calculating the bond length of NaCl.

import java.lang.*;
public class Bond {
  static final double e2 = 14.4, v0 = 1090, r0 = 0.33;
  public static void main(String argv[]) {
    double del = 1e-6, r = 2, dr = 0.1;
    int n = 20;
    r = secant2(n, del, r, dr);
    System.out.println("The bond length is " + r +
      " angstroms");
  }

// Method to carry out the secant search for the
// maximum of g(x) via the root of f(x)=dg(x)/dx=0.

  public static double secant2(int n, double del,
    double x, double dx) {
    int k = 0;
    double x1 = x+dx, x2 = 0;
    double g0 = g(x);
    double g1 = g(x1);
    if (g1 > g0) x1 = x-dx;
    while ((Math.abs(dx)>del) && (k<n)) {
      double d = f(x1)-f(x);
      dx = -(x1-x)*f(x1)/d;
      x2 = x1+dx;
      double g2 = g(x2);
      if (g2 > g1) x2 = x1-dx;
      x  = x1;
      x1 = x2;
      g1 = g2;
      k++;
    }
    if (k==n) System.out.println("Convergence not" +
      " found after " + n + " iterations");
    return x1;
  }

// Method to provide function g(x)=-e2/x+v0*exp(-x/r0).

  public static double g(double x) {
    return -e2/x+v0*Math.exp(-x/r0);
  }

// Method to provide function f(x)=-dg(x)/dx.

  public static double f(double x) {
    return -e2/(x*x)+v0*Math.exp(-x/r0)/r0;
  }
}
