/* nag_opt_simplex_easy (e04cbc) Example Program. * * Copyright 2006 Numerical Algorithms Group. * * Mark 9 revised, 2009. */ #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL funct(const Integer n, const double *xc, double *fc, Nag_Comm *comm); static void NAG_CALL monit(const double fmin, const double fmax, const double sim[], const Integer n, const Integer ncall, const double serror, const double vratio, Nag_Comm *comm); #ifdef __cplusplus } #endif struct user { Integer monitoring; FILE *fpout; }; int main(int argc, char *argv[]) { FILE *fpout; /* Scalars */ double f, tolf, tolx; Integer exit_status, i, maxcal = 100, n = 2; struct user s; NagError fail; /* Arrays */ double *x = 0; Nag_Comm comm; exit_status = 0; INIT_FAIL(fail); /* Check for command-line IO options */ fpout = nag_example_file_io(argc, argv, "-results", NULL); fprintf(fpout, "nag_opt_simplex_easy (e04cbc) Example Program Results\n"); /* Allocate memory */ if (!(x = NAG_ALLOC(n, double))) { fprintf(fpout, "Allocation failure\n"); exit_status = -1; goto END; } /* Set monitoring to a nonzero value to obtain monitoring information */ s.monitoring = 0; s.fpout = fpout; comm.p = (Pointer)&s; /* Starting values */ x[0] = -1.0; x[1] = 1.0; tolf = sqrt(X02AJC); tolx = sqrt(tolf); nag_opt_simplex_easy(n, x, &f, tolf, tolx, funct, monit, maxcal, &comm, &fail); if (fail.code == NE_NOERROR) { fprintf(fpout, "The final function value is %12.4f\n", f); fprintf(fpout, "at the point"); for (i = 1; i <= n; ++i) { fprintf(fpout, " %12.4f", x[i-1]); } fprintf(fpout, "\n"); } else { fprintf(fpout, "%s\n", fail.message); exit_status = 1; goto END; } END: if (fpout != stdout) fclose(fpout); if (x) NAG_FREE(x); return exit_status; } static void NAG_CALL funct(const Integer n, const double *xc, double *fc, Nag_Comm *comm) { *fc = exp(xc[0])*(4.0*xc[0]*(xc[0]+xc[1])+2.0*xc[1]*(xc[1]+1.0)+1.0); } static void NAG_CALL monit(const double fmin, const double fmax, const double sim[], const Integer n, const Integer ncall, const double serror, const double vratio, Nag_Comm *comm) { #define SIM(I, J) sim[(J-1)*(n+1) + (I-1)] Integer i, j; struct user *s = (struct user *) comm->p; if (s->monitoring != 0) { fprintf(s->fpout, "\nThere have been %5ld function calls\n", ncall); fprintf(s->fpout, "The smallest function value is %10.4f\n", fmin); fprintf(s->fpout, "\nThe simplex is\n"); for (i = 1; i <= n+1; ++i) { for (j = 1; j <= n; ++j) { fprintf(s->fpout, " %13.4e", SIM(i, j)); } fprintf(s->fpout, "\n"); } fprintf(s->fpout, "\nThe standard deviation in function values at the" " vertices of the simplex is %10.4f\n", serror); fprintf(s->fpout, "The linearized volume ratio of the current simplex" " to the starting one is %10.4f\n", vratio); } }