/* nag_numdiff_1d_real (d04aac) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 */

#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagd04.h>

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

int main(void)
{
  /* Scalars */
  Integer   exit_status = 0;
  Integer   i, k, l, step, nder;
  double    hbase, h_init, h_reduce, xval;
  /* Arrays */
  double    der[14], erest[14], ruser[1];
  /* Nag Types */
  Nag_Comm  comm;
  NagError  fail;

  INIT_FAIL(fail);

  printf("nag_numdiff_1d_real (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 = abs(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;
  }
  /* Initial step size. */
  h_init = 0.5;
  hbase = h_init;
  /* Reduction factor applied to successive step sizes. */
  h_reduce = 0.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"
         "   fun(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_1d_real (d04aac).
     * Numerical differentiation, derivatives up to order 14,
     * function of one real variable.
     */
    nag_numdiff_1d_real(xval, nder, hbase, der, erest, fun, &comm, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_numdiff_1d_real (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.3e %13s\n", i + 1, der[i], "No");
      }

    hbase = hbase * h_reduce;
  }

END:
  return exit_status;
}

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