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

NAG CL Interface Introduction
Example description
/* nag_stat_moments_quad_form (g01nac) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.2, 2024.
 */

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

int main(void) {
  /* Scalars */
  double beta, con;
  Integer exit_status, i, j, l, n, pda, pdsigma;
  NagError fail;
  Nag_OrderType order;

  /* Arrays */
  double *a = 0, *emu = 0, *rkum = 0, *rmom = 0, *sigma = 0;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J - 1) * pda + I - 1]
#define SIGMA(I, J) sigma[(J - 1) * pdsigma + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I - 1) * pda + J - 1]
#define SIGMA(I, J) sigma[(I - 1) * pdsigma + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  exit_status = 0;
  printf("nag_stat_moments_quad_form (g01nac) Example Program Results\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%lf%lf%*[^\n] ", &beta, &con);
  scanf("%" NAG_IFMT "%" NAG_IFMT "%*[^\n] ", &n, &l);

  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * n, double)) || !(emu = NAG_ALLOC(n, double)) ||
      !(rkum = NAG_ALLOC(l, double)) || !(rmom = NAG_ALLOC(l, double)) ||
      !(sigma = NAG_ALLOC(n * n, double))) {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  pda = n;
  pdsigma = n;

  if (l <= 12) {
    /* Compute A, EMU, and SIGMA for simple autoregression */
    for (i = 1; i <= n; ++i) {
      for (j = i; j <= n; ++j)
        A(j, i) = 0.0;
    }
    for (i = 1; i <= n - 1; ++i)
      A(i + 1, i) = 0.5;
    emu[0] = con * beta;
    for (i = 1; i <= n - 1; ++i)
      emu[i] = beta * emu[i - 1];
    SIGMA(1, 1) = 1.0;
    for (i = 2; i <= n; ++i)
      SIGMA(i, i) = beta * beta * SIGMA(i - 1, i - 1) + 1.0;
    for (i = 1; i <= n; ++i) {
      for (j = i + 1; j <= n; ++j)
        SIGMA(j, i) = beta * SIGMA(j - 1, i);
    }

    /* nag_stat_moments_quad_form (g01nac).
     * Cumulants and moments of quadratic forms in Normal
     * variables
     */
    nag_stat_moments_quad_form(order, Nag_ComputeMoments, Nag_MeanInclude, n, a,
                               n, emu, sigma, n, l, rkum, rmom, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_stat_moments_quad_form (g01nac).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

    printf("\n");
    printf(" n = %3" NAG_IFMT " beta = %6.3f con = %6.3f\n", n, beta, con);
    printf("\n");

    printf("    Cumulants       Moments\n");
    printf("\n");
    for (i = 1; i <= l; ++i)
      printf("%3" NAG_IFMT "%13.4e    %13.4e\n", i, rkum[i - 1], rmom[i - 1]);
  }

END:
  NAG_FREE(a);
  NAG_FREE(emu);
  NAG_FREE(rkum);
  NAG_FREE(rmom);
  NAG_FREE(sigma);

  return exit_status;
}