/* nag_numdiff_1d_real (d04aac) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 23, 2011.
 */

#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)
{
  static double ruser[1] = {-1.0};
  Integer exit_status = 0;
  double  hbase;
  Integer i, k, l, start, step;
  double  h_init;
  double  h_reduce;
  double  xval;
  Integer nder;
  double  der[14], erest[14];
  Nag_Comm comm;
  NagError fail;

  INIT_FAIL(fail);

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

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

  /* abs(nder) is largest order derivative required. */
  nder = -7;
  l = fabs(nder);
  /* nder < 0 and nder is even means only even derivatives,
   * and nder < 0 and nder is odd, only odd derivatives.
   */
  if (nder < 0) {
    start = (l % 2 ? 0 : 1);
    step = 2;
  }
  else {
    start = 0;
    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("\n"
         "Four 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 = %ld\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 %f   the results are\n"
             "Order        Derivative       Error estimate\n", hbase);

      for (i = start; i < MIN(l,14); i += step)
        printf("%2ld %21.4e %21.4e\n", i+1, der[i], erest[i]);

      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);
}