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

NAG AD Library Introduction
Example description
#include "dco.hpp"
/* S01BA_A1W_F C++ Header Example Program.
 *
 * Copyright 2021 Numerical Algorithms Group.
 * Mark 27.2, 2021.
 */

#include <iostream>
#include <nag.h>
#include <nagad.h>
#include <stdio.h>
#include <string>
using namespace std;

int main(void)
{
  int exit_status = 0;

  // Input and output variables
  nagad_a1w_w_rtype x, y;

  cout << "S01BA_A1W_F C++ Header Example Program Results\n\n";
  // Skip heading in data file
  string mystr;
  getline(cin, mystr);

  // Read number of x values
  Integer n;
  cin >> n;

  // Create AD tape
  dco::ga1s<double>::global_tape = dco::ga1s<double>::tape_t::create();

  // Create AD configuration data object
  Integer ifail     = -1;
  void *  ad_handle = 0;
  nag::ad::x10aa(ad_handle, ifail);
  if (ifail != 0)
    {
      exit_status = 1;
      goto END;
    }

  cout << "       x       y=ln(1+x)     dy/dx\n";
  cout.setf(ios::scientific, ios::floatfield);
  cout.setf(ios::right);
  cout.precision(4);

  // Loop over x values
  for (Integer i = 0; i < n; ++i)
    {
      // Read next x
      double xr;
      cin >> xr;
      x = xr;
      // Register x, i.e. differentiate w.r.t. x
      dco::ga1s<double>::global_tape->register_variable(x);

      // Call NAG AD Routine
      ifail = -1;
      nag::ad::s01ba(ad_handle, x, y, ifail);
      if (ifail != 0)
        {
          exit_status = 2;
          goto END;
        }

      // Reset adjoints, increment y, and evaluate adjoint of y w.r.t. x
      dco::ga1s<double>::global_tape->zero_adjoints();
      double inc = 1.0;
      dco::derivative(y) += inc;
      dco::ga1s<double>::global_tape->sparse_interpret() = true;
      dco::ga1s<double>::global_tape->interpret_adjoint();
      if (ifail != 0)
        {
          exit_status = 3;
          goto END;
        }

      // Get derivative, dydx and output values
      double dydx;
      dydx = dco::derivative(x);

      cout.width(12);
      cout << dco::value(x);
      cout.width(12);
      cout << dco::value(y);
      cout.width(12);
      cout << dydx << endl;
    }

END:
  // Remove computational data object and tape
  nag::ad::x10ab(ad_handle, ifail);
  dco::ga1s<double>::tape_t::remove(dco::ga1s<double>::global_tape);

  return exit_status;
}