Example description
/* nag_roots_sys_func_aa (c05mbc) Example Program.
 *
 * Copyright 2019 Numerical Algorithms Group.
 *
 * Mark 27.0, 2019.
 */

#include <nag.h>
#include <stdio.h>
#include <math.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static void NAG_CALL f(Integer n, const double x[], double fvec[],
                           Nag_Comm *comm, Integer *iflag);
#ifdef __cplusplus
}
#endif

int main(void)
{
  static double ruser[1] = { -1.0 };
  Integer exit_status = 0, i, n = 4, m = 2, astart = 0;
  double *fvec = 0, *x = 0, atol, rtol, cndtol = 0.0;
  /* Nag Types */
  NagError fail;
  Nag_Comm comm;

  INIT_FAIL(fail);

  printf("nag_roots_sys_func_aa (c05mbc) Example Program Results\n");

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

  if (n > 0) {
    if (!(fvec = NAG_ALLOC(n, double)) || !(x = NAG_ALLOC(n, double)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid n.\n");
    exit_status = 1;
    goto END;
  }

  /* The following starting values provide a rough solution. */
    x[0] = 2.0;
    x[1] = 0.5;
    x[2] = 2.0;
    x[3] = 0.5;

  /* nag_machine_precision (x02ajc).
   * The machine precision
   */
  atol = sqrt(nag_machine_precision);
  rtol = sqrt(nag_machine_precision);

  /* nag_roots_sys_func_aa (c05mbc).
   * Solution of a system of nonlinear equations using
   * Anderson acceleration
   */
  nag_roots_sys_func_aa(f, n, x, fvec, atol, rtol, m, cndtol, astart,
                          &comm, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_roots_sys_func_aa (c05mbc).\n%s\n",
           fail.message);
    exit_status = 1;
    if (fail.code != NE_TOO_MANY_FEVALS &&
        fail.code != NE_NO_IMPROVEMENT)
      goto END;
  }

  printf(fail.code == NE_NOERROR ? "Final approximate" : "Approximate");
  printf(" solution\n\n");
  for (i = 0; i < n; i++)
    printf("%12.4f  ", x[i]);

  printf("\n");

  if (fail.code != NE_NOERROR)
    exit_status = 2;

END:
  NAG_FREE(fvec);
  NAG_FREE(x);
  return exit_status;
}

static void NAG_CALL f(Integer n, const double x[], double fvec[],
                         Nag_Comm *comm, Integer *iflag)
{

  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback f, first invocation.)\n");
    comm->user[0] = 0.0;
  }

 fvec[0] = cos(x[2]) - x[0];
 fvec[1] = sqrt(1.0 - x[3]*x[3])- x[1];
 fvec[2] = sin(x[0]) - x[2];
 fvec[3] = x[1]*x[1] - x[3];

  /* Set iflag negative to terminate execution for any reason. */
  *iflag = 0;
}