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

NAG CL Interface Introduction
Example description
/* nag_fit_dim1_minimax_polynomial (e02alc) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.0, 2024.
 */
#include <math.h>
#include <nag.h>

int main(void) {

  /* Scalars */
  Integer exit_status = 0;
  double dxx, ref, s, t, xx;
  Integer i, j, m, n, neval;
  /* Local Arrays */
  double *a = 0, *x = 0, *y = 0;
  /* NAG types */
  NagError fail;

  INIT_FAIL(fail);

  printf(
      "nag_fit_dim1_minimax_polynomial (e02alc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");

  /* n is number of data points to be fitted,
   * m is degree of fitting polynomial
   * neval is number of evaluation points of fitted polynomial
   */
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%*[^\n] ", &n, &m, &neval);

  if (!(a = NAG_ALLOC((m + 1), double)) || !(x = NAG_ALLOC((n), double)) ||
      !(y = NAG_ALLOC((n), double))) {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  for (i = 0; i < n; i++)
    scanf("%lf%lf", &x[i], &y[i]);
  scanf("%*[^\n] ");

  /* Fit minimax polynomial of degree m using
   * nag_fit_dim1_minimax_polynomial (e02alc).
   */
  nag_fit_dim1_minimax_polynomial(n, x, y, m, a, &ref, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_fit_dim1_minimax_polynomial (e02alc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  printf("\n  Polynomial coefficients\n");
  for (i = 0; i < m + 1; i++)
    printf("     %12.4e \n", a[i]);
  printf("\n\n  Reference deviation = %10.2e\n\n", ref);
  printf("  x      Fit     exp(x)   Residual\n");

  /* The neval evaluation points are equispaced on [0,1]. */
  dxx = 1.0 / (double)(neval - 1);
  for (j = 0; j < neval; j++) {
    xx = (double)(j)*dxx;
    s = a[m];
    for (i = m - 1; i >= 0; i--)
      s = s * xx + a[i];
    t = exp(xx);
    printf("%5.2f%9.4f%9.4f%11.2e\n", xx, s, t, s - t);
  }
END:
  NAG_FREE(a);
  NAG_FREE(x);
  NAG_FREE(y);

  return exit_status;
}