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

NAG CL Interface Introduction
Example description
/* nag_rand_dist_dirichlet (g05sec) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.1, 2024.
 */
/* Pre-processor includes */
#include <math.h>
#include <nag.h>
#include <stdio.h>

#define X(I, J) x[(order == Nag_ColMajor) ? (J * pdx + I) : (I * pdx + J)]

int main(void) {
  /* Integer scalar and array declarations */
  Integer exit_status = 0;
  Integer pdx, x_size, i, j, lstate;
  Integer *state = 0;

  /* NAG structures */
  NagError fail;

  /* Double scalar and array declarations */
  double *x = 0;

  /* Set the distribution parameters */
  double a[] = {2.0e0, 2.0e0, 2.0e0, 2.0e0};
  Integer m = 4;

  /* Set the sample size */
  Integer n = 5;

  /* Return the results in column major order */
  Nag_OrderType order = Nag_ColMajor;

  /* Choose the base generator */
  Nag_BaseRNG genid = Nag_Basic;
  Integer subid = 0;

  /* Set the seed */
  Integer seed[] = {1762543};
  Integer lseed = 1;

  /* Initialize the error structure */
  INIT_FAIL(fail);

  printf("nag_rand_dist_dirichlet (g05sec) Example Program Results\n\n");

  /* Get the length of the state array */
  lstate = -1;
  nag_rand_init_repeat(genid, subid, seed, lseed, state, &lstate, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_repeat (g05kfc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  pdx = (order == Nag_ColMajor) ? n : m;
  x_size = (order == Nag_ColMajor) ? pdx * m : pdx * n;

  /* Allocate arrays */
  if (!(x = NAG_ALLOC(x_size, double)) ||
      !(state = NAG_ALLOC(lstate, Integer))) {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Initialize the generator to a repeatable sequence */
  nag_rand_init_repeat(genid, subid, seed, lseed, state, &lstate, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_init_repeat (g05kfc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Generate the variates */
  nag_rand_dist_dirichlet(order, n, m, a, state, x, pdx, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_rand_dist_dirichlet (g05sec).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Display the variates */
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++)
      printf("%10.4f", X(i, j));
    printf("\n");
  }

END:
  NAG_FREE(x);
  NAG_FREE(state);

  return exit_status;
}