/* nag_zero_cont_func_brent (c05ayc) 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)
{
  static double ruser[1] = { -1.0 };
  Integer exit_status = 0;
  double a, b;
  double x, eta, eps;
  NagError fail;
  Nag_Comm comm;

  INIT_FAIL(fail);

  printf("nag_zero_cont_func_brent (c05ayc) Example Program Results\n");

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

  a = 0.0;
  b = 1.0;
  eps = 1e-05;
  eta = 0.0;

  /* nag_zero_cont_func_brent (c05ayc).
   * Zero of a continuous function using Brent's algorithm
   */
  nag_zero_cont_func_brent(a, b, eps, eta, f, &x, &comm, &fail);
  if (fail.code == NE_NOERROR) {
    printf("Zero = %12.5f\n", x);
  }
  else {
    printf("%s\n", fail.message);
    if (fail.code == NE_TOO_SMALL || fail.code == NE_PROBABLE_POLE)
      printf("Final point = %12.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 exp(-x) - x;
}