/* nag_zero_cont_func_brent_binsrch (c05auc) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

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

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

int main(void)
{
  /* Scalars */
  Integer exit_status = 0;
  double a, b, eps, eta, h, x;
  NagError fail;
  Nag_Comm comm;
  /* Arrays */
  static double ruser[1] = { -1.0 };

  INIT_FAIL(fail);

  printf("nag_zero_cont_func_brent_binsrch (c05auc) Example Program Results\n");

  x = 1.0;
  h = 0.1;
  eps = 1e-05;
  eta = 0.0;

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

  /* nag_zero_cont_func_brent_binsrch (c05auc).
   * Locates a simple zero of a continuous function of one variable,
   * binary search for an interval containing a zero.
   */
  nag_zero_cont_func_brent_binsrch(&x, h, eps, eta, f, &a, &b, &comm, &fail);
  if (fail.code == NE_NOERROR) {
    printf("Root is %13.5f\n", x);
    printf("Interval searched is [%8.5f,%8.5f]\n", a, b);
  }
  else {
    printf("%s\n", fail.message);
    if (fail.code == NE_PROBABLE_POLE ||
        fail.code == NW_TOO_MUCH_ACC_REQUESTED)
      printf("Final value = %13.5f\n", 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 x - exp(-x);
}