/* C05RB_P0W_F C++ Header Example Program.
*
* Copyright 2021 Numerical Algorithms Group.
* Mark 27.3, 2021.
*/
#include <iostream>
#include <math.h>
#include <nag.h>
#include <nagad.h>
#include <nagx02.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
// Scalars
int exit_status = 0;
const Integer n = 7;
cout << "C05RB_P0W_F C++ Header Example Program Results\n\n";
// problem parameters and starting value
double r[5], x[7];
r[0] = -1.0;
r[1] = 3.0;
r[2] = -2.0;
r[3] = -2.0;
r[4] = -1.0;
for (int i = 0; i < n; ++i)
{
x[i] = -1.0;
}
Integer ifail = 0;
nag::ad::handle_t ad_handle;
double fvec[n], fjac[n * n], xtol;
xtol = sqrt(X02AJC);
auto fcn = [&](nag::ad::handle_t & ad_handle,
const Integer & n,
const double *x,
double *fvec,
double *fjac,
Integer & iflag)
{
if (iflag != 2)
{
for (int i = 0; i < n; ++i)
{
fvec[i] = (r[1] + r[2] * x[i]) * x[i] - r[4];
}
for (int i = 1; i < n; ++i)
{
fvec[i] = fvec[i] + r[0] * x[i - 1];
}
for (int i = 0; i < n - 1; ++i)
{
fvec[i] = fvec[i] + r[3] * x[i + 1];
}
}
else
{
for (int i = 0; i < n * n; ++i)
{
fjac[i] = 0.0;
}
fjac[0] = r[1] + 2.0 * r[2] * x[0];
fjac[n] = r[3];
for (int i = 1; i < n - 1; ++i)
{
int k = i * n + i;
fjac[k - n] = r[0];
fjac[k] = r[1] + 2.0 * r[2] * x[i];
fjac[k + n] = r[3];
}
fjac[n * n - n - 1] = r[0];
fjac[n * n - 1] = r[1] + 2.0 * r[2] * x[n - 1];
}
iflag = 0;
};
nag::ad::c05rb(ad_handle, fcn, n, x, fvec, fjac, xtol, 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;
}