/* nag_zero_cont_func_cntin (c05awc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */

#include <nag.h>
#include <nagx04.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <math.h>
#include <nagc05.h>
#include <nagx02.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static double NAG_CALL f(double x, Nag_Comm *comm);
#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  Integer nfmax, exit_status = 0;
  int i;
  double eps, eta, x;
  /* Arrays */
  static double ruser[1] = { -1.0 };

  NagError fail;
  Nag_Comm comm;

  printf("nag_zero_cont_func_cntin (c05awc) Example Program Results\n");

  /* For communication with user-supplied functions: */
  comm.user = ruser;

  for (i = 3; i <= 4; i++) {
    eps = pow(10.0, -i);
    x = 1.0;
    eta = 0.0;
    nfmax = 200;

    INIT_FAIL(fail);

    /* nag_zero_cont_func_cntin (c05awc).
     * Locates a zero of a continuous function.
     */
    nag_zero_cont_func_cntin(&x, eps, eta, f, nfmax, &comm, &fail);

    if (fail.code == NE_NOERROR) {
      printf("\nWith eps = %10.2e, root is %14.5f\n", eps, x);
    }
    else {
      printf("Error from nag_zero_cont_func_cntin (c05awc) %s\n",
             fail.message);

      if (fail.code == NE_TOO_MANY_CALLS ||
          fail.code == NE_SECANT_ITER_FAILED) {
        printf("\nWith eps = %10.2e, final value is %14.5f\n", eps, x);
      }

      exit_status = 1;
      goto END;
    }
  }

END:

  return exit_status;
}

static double NAG_CALL f(double x, Nag_Comm *comm)
{
  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback f, first invocation.)\n");
    comm->user[0] = 0.0;
  }
  return exp(-x) - x;
}