/* nag_opt_check_deriv (e04hcc) Example Program. * * Copyright 1991 Numerical Algorithms Group. * * Mark 2, 1991. * Mark 7 revised, 2001. * Mark 8 revised, 2004. * */ #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL objfun(Integer n, double x[], double *f, double g[], Nag_Comm *comm); #ifdef __cplusplus } #endif #define NMAX 4 static void NAG_CALL objfun(Integer n, double x[], double *objf, double g[], Nag_Comm *comm) { /* objfun evaluates the objective function and its derivatives. */ double x1, x2, x3, x4; double tmp, tmp1, tmp2, tmp3, tmp4; x1 = x[0]; x2 = x[1]; x3 = x[2]; x4 = x[3]; /* Supply a single function value */ tmp1 = x1 + 10.0*x2; tmp2 = x3 - x4; tmp3 = x2 - 2.0*x3, tmp3 *= tmp3; tmp4 = x1 - x4, tmp4 *= tmp4; *objf = tmp1*tmp1 + 5.0*tmp2*tmp2 + tmp3*tmp3 + 10.0*tmp4*tmp4; if (comm->flag != 0) { /* Calculate the derivatives */ tmp = x1 - x4; g[0] = 2.0*(x1 + 10.0*x2) + 40.0*tmp*tmp*tmp; tmp = x2 - 2.0*x3; g[1] = 20.0*(x1 + 10.0*x2) + 4.0*tmp*tmp*tmp; tmp = x2 - 2.0*x3; g[2] = 10.0*(x3 - x4) - 8.0*tmp*tmp*tmp; tmp = x1 - x4; g[3] = 10.0*(x4 - x3) - 40.0*tmp*tmp*tmp; } } /* objfun */ int main(int argc, char *argv[]) { FILE *fpout; Integer exit_status = 0, i, n; NagError fail; double *g = 0, objf, *x = 0; INIT_FAIL(fail); /* Check for command-line IO options */ fpout = nag_example_file_io(argc, argv, "-results", NULL); fprintf(fpout, "nag_opt_check_deriv (e04hcc) Example Program Results\n"); n = NMAX; 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; } x[0] = 1.46; x[1] = -0.82; x[2] = 0.57; x[3] = 1.21; fprintf(fpout, "\nThe test point is:\n"); for (i = 0; i < n; ++i) fprintf(fpout, " %8.4f", x[i]); fprintf(fpout, "\n"); /* Call derivative checker */ /* nag_opt_check_deriv (e04hcc). * Derivative checker for use with nag_opt_bounds_deriv * (e04kbc) */ nag_opt_check_deriv(n, objfun, x, &objf, g, NAGCOMM_NULL, &fail); if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_opt_check_deriv (e04hcc).\n%s\n", fail.message); exit_status = 1; goto END; } fprintf(fpout, "\nFirst derivatives are consistent with function values.\n\n"); fprintf(fpout, "At the test point, objfun gives the function value %13.4e\n", objf); fprintf(fpout, "and the 1st derivatives\n\n"); for (i = 0; i < n; ++i) fprintf(fpout, " %12.3e ", g[i]); fprintf(fpout, "\n"); END: if (fpout != stdout) fclose(fpout); if (x) NAG_FREE(x); if (g) NAG_FREE(g); return exit_status; }