/* nag_opt_conj_grad (e04dgc) Example Program. * * Copyright 1991 Numerical Algorithms Group. * * Mark 2, 1991. * Mark 7 revised, 2001. * Mark 8 revised, 2004. * */ #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL objfun(Integer n, double x[], double *objf, double g[], Nag_Comm *comm); #ifdef __cplusplus } #endif int main(int argc, char *argv[]) { FILE *fpout; char *optionsfile = 0; char *outfile = 0; Integer exit_status = 0; Nag_Boolean print; Integer n; Nag_E04_Opt options; double *g = 0, objf, *x = 0; NagError fail; INIT_FAIL(fail); /* Check for command-line IO options */ fpout = nag_example_file_io(argc, argv, "-results", NULL); (void) nag_example_file_io(argc, argv, "-options", &optionsfile); (void) nag_example_file_io(argc, argv, "-nag_write", &outfile); if (!outfile) { outfile = NAG_ALLOC(7, char); strcpy(outfile, "stdout"); } fprintf(fpout, "nag_opt_conj_grad (e04dgc) Example Program Results\n"); /* Initialise options structure and read option values from file */ print = Nag_TRUE; n = 2; /* Number of variables */ if (n >= 1) { if (!(x = NAG_ALLOC(n, double)) || !(g = NAG_ALLOC(n, double))) { fprintf(fpout, "Allocation failure\n"); exit_status = -1; goto END; } } else { fprintf(fpout, "Invalid n.\n"); exit_status = 1; return exit_status; } /* nag_opt_init (e04xxc). * Initialization function for option setting */ nag_opt_init(&options); strcpy(options.outfile, outfile); /* nag_opt_read (e04xyc). * Read options from a text file */ if (strcmp(outfile, "stdout")) fclose(fpout); nag_opt_read("e04dgc", optionsfile, &options, print, options.outfile, &fail); if (strcmp(outfile, "stdout")) { fpout = fopen(outfile, "a"); } if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_opt_read (e04xyc).\n%s\n", fail.message); exit_status = 1; goto END; } /* Set the initial estimate of the solution. */ x[0] = -1.0; x[1] = 1.0; /* Solve the problem. */ /* nag_opt_conj_grad (e04dgc), see above. */ if (strcmp(outfile, "stdout")) fclose(fpout); nag_opt_conj_grad(n, objfun, x, &objf, g, &options, NAGCOMM_NULL, &fail); if (strcmp(outfile, "stdout")) { fpout = fopen(outfile, "a"); } if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_opt_conj_grad (e04dgc).\n%s\n", fail.message); exit_status = 1; goto END; } END: if (fpout != stdout) fclose(fpout); if (x) NAG_FREE(x); if (g) NAG_FREE(g); if (optionsfile) NAG_FREE(optionsfile); if (outfile) NAG_FREE(outfile); return exit_status; } static void NAG_CALL objfun(Integer n, double x[], double *objf, double g[], Nag_Comm *comm) { /* Function to evaluate objective function and its 1st derivatives. */ double ex1, x1, x2; ex1 = exp(x[0]); x1 = x[0]; x2 = x[1]; *objf = ex1*(4*x1*x1 + 2*x2*x2 + 4*x1*x2 + 2*x2 + 1); g[0] = 4*ex1*(2*x1 + x2) + *objf; g[1] = 2*ex1*(2*x2 + 2*x1 + 1); } /* objfun */