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

NAG CL Interface Introduction
Example description
/* nag_numdiff_fwd (d04aac) Example Program.
 *
 * Copyright 2022 Numerical Algorithms Group.
 *
 * Mark 28.6, 2022.
 */

#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 exit_status = 0;
  Integer i, k, l, step, nder;
  double hbase, xval;
  /* Arrays */
  double der[14], erest[14], ruser[1];
  double steps[4] = {0.5, 0.05, 0.005, 0.0005};
  /* Nag Types */
  Nag_Comm comm;
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_numdiff_fwd (d04aac) Example Program Results\n");

  /* For communication with user-supplied functions: */
  ruser[0] = -1.0;
  comm.user = ruser;

  /* abs(nder) is largest order derivative required. */
  nder = -7;
  l = NAG_IABS(nder);
  /* nder < 0 and nder is even means only even derivatives,
   * and nder < 0 and nder is odd, only odd derivatives.
   */
  if (nder < 0) {
    step = 2;
  } else {
    step = 1;
  }
  /* Derivatives will be evaluated at x = xval. */
  xval = 0.5;

  printf("\nFour separate runs to calculate the first four odd order "
         "derivatives of\n"
         "   f(x) = 0.5*exp(2.0*x-1.0) at x = 0.5.\n"
         "The exact results are 1, 4, 16 and 64\n\n"
         "Input parameters common to all four runs\n"
         "  xval = %f     nder = %" NAG_IFMT "\n",
         xval, nder);

  for (k = 0; k < 4; k++) {
    /* nag_numdiff_fwd (d04aac).
     * Numerical differentiation, derivatives up to order 14,
     * function of one real variable.
     */
    hbase = steps[k];
    nag_numdiff_fwd(xval, nder, hbase, der, erest, f, &comm, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_numdiff_fwd (d04aac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

    printf("\n"
           "with step length %8.4f  the results are\n"
           "Order        Derivative       Questionable?\n",
           hbase);

    for (i = 0; i < l; i += step)
      if (erest[i] < 0.0) {
        printf("%2" NAG_IFMT " %21s %13s\n", i + 1, "---------", "Yes");
      } else {
        printf("%2" NAG_IFMT " %21.2e %13s\n", i + 1, der[i], "No");
      }
  }

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 0.5 * exp(2.0 * x - 1.0);
}