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

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

#include <iostream>
#include <dco.hpp>
#include <math.h>
#include <nag.h>
#include <nagad.h>
#include <nagx02.h>
#include <nagx04.h>
#include <stdio.h>
#include <string>
using namespace std;

int main()
{
  // Scalars
  int           exit_status = 0;
  const Integer maxfev = 2000, ml = 1, mode = 2, mu = 1, n = 7, nprint = 0;

  cout << "C05QC_P0W_F C++ Header Example Program Results\n\n";

  // problem parameters and starting value
  double ruser[5], x[7];

  ruser[0] = -1.0;
  ruser[1] = 3.0;
  ruser[2] = -2.0;
  ruser[3] = -2.0;
  ruser[4] = -1.0;

  for (int i = 0; i < n; ++i)
  {
    x[i] = -1.0;
  }

  nag::ad::handle_t ad_handle;
  Integer           ifail = 0;
  double            diag[n], fjac[n * n], epsfcn, factor, fvec[n], qtf[n],
      r[n * (n + 1) / 2], xtol;
  Integer nfev;

  xtol   = sqrt(X02AJC);
  epsfcn = 0.;
  factor = 100.;
  for (int i = 0; i < n; ++i)
  {
    diag[i] = 1.;
  }

  auto fcn = [&](nag::ad::handle_t &     ad_handle,
                const Integer &         n,
                const double *x,
                double *fvec,
                Integer &               iflag)
              {
                if (iflag != 0)
                {
                  for (int i = 0; i < n; ++i)
                  {
                    fvec[i] = (ruser[1] + ruser[2] * x[i]) * x[i] - ruser[4];
                  }
                  for (int i = 1; i < n; ++i)
                  {
                    fvec[i] = fvec[i] + ruser[0] * x[i - 1];
                  }
                  for (int i = 0; i < n - 1; ++i)
                  {
                    fvec[i] = fvec[i] + ruser[3] * x[i + 1];
                  }
                }
                iflag = 0;
              };
              
  nag::ad::c05qc(ad_handle, fcn, n, x, fvec, xtol, maxfev, ml, mu, epsfcn, mode,
                 diag, factor, nprint, nfev, fjac, r, qtf, ifail);

  cout.setf(ios::scientific, ios::floatfield);
  cout.precision(4);
  cout << "           Solution:\n";
  for (int i = 0; i < n; ++i)
  {
    cout.width(10);
    cout << i + 1;
    cout.width(20);
    cout << x[i] << endl;
  }

  return exit_status;
}