NAG Library Manual, Mark 27.3
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_roots_contfn_cntin (c05awc) Example Program.
 *
 * Copyright 2021 Numerical Algorithms Group.
 *
 * Mark 27.3, 2021.
 */

#include <math.h>
#include <nag.h>
#include <stdio.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_roots_contfn_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_roots_contfn_cntin (c05awc).
     * Locates a zero of a continuous function.
     */
    nag_roots_contfn_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_roots_contfn_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;
}