/* nag_1d_minimax_polynomial (e02alc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 24, 2013.
 */
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nage02.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_1d_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("%ld%ld%ld%*[^\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_1d_minimax_polynomial (e02alc).
   */ 
  nag_1d_minimax_polynomial(n, x, y, m, a, &ref, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_1d_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;
}