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

NAG AD Library Introduction
Example description
/* E04AB_T1W_F C++ Header Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 * Mark 30.0, 2024.
 */

#include <dco.hpp>
#include <iostream>
#include <math.h>
#include <nag.h>
#include <nagad.h>
#include <stdio.h>
#include <string>

typedef double                   DCO_BASE_TYPE;
typedef dco::gt1s<DCO_BASE_TYPE> DCO_MODE;
typedef DCO_MODE::type           DCO_TYPE;

int main()
{
  Integer  exit_status = 0, max_fun;
  Integer  ifail;
  DCO_TYPE a, b, e1, e2, f, x;
  DCO_TYPE ruser[1];
  Integer  iuser[1];

  printf("E04AB_T1W_F C++ Header Example Program Results\n\n");

  nag::ad::handle_t ad_handle;
  ifail = 0;

  /* For communication with user-supplied functions: */
  ruser[0] = 1.;
  /* e1 and e2 are set to zero so that nag_opt_one_var_func (e04abc) will
   *  reset them to their default values.
   */
  e1 = 0.0;
  e2 = 0.0;
  /* The minimum is known to lie in the range (3.5, 5.0) */
  a = 3.5;
  b = 5.0;
  /* Allow 30 calls of funct */
  max_fun = 30;

  auto funct = [&](nag::ad::handle_t &      ad_handle,
                const nagad_t1w_w_rtype &xc,
                nagad_t1w_w_rtype &      fc)
              {
                fc = sin(ruser[0] * xc) / xc;
              };
  /* nag_opt_one_var_func (e04abc).
   * Minimizes a function of one variable, using function values only.
   */
  dco::derivative(ruser[0]) = 1.0;
  nag::ad::e04ab(ad_handle, funct, e1, e2, a, b, max_fun, x, f, ifail);

  if (ifail != 0)
  {
    printf("Error from nagad_opt_one_var_func_t1w (nag::ad::e04ab)."
           " %" NAG_IFMT "\n",
           ifail);
    exit_status = 1;
  }
  else
  {
    printf("The minimum lies in the interval %7.5f to %7.5f.\n", dco::value(a),
           dco::value(b));
    printf("Its estimated position is %7.5f,\n", dco::value(x));
    printf("where the function value is %13.4e.\n", dco::value(f));
    printf("%1" NAG_IFMT " function evaluations were required.\n", max_fun);

    printf("dx/druser %26.16f\n", dco::derivative(x));
  }

  return exit_status;
}