/* 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 #ifdef __cplusplus extern "C" { #endif static void objfun(Integer n, double x[], double *f, double g[], Nag_Comm *comm); #ifdef __cplusplus } #endif #define NMAX 4 static void 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(void) { Integer exit_status=0, i, n; NagError fail; double *g=0, objf, *x=0; INIT_FAIL(fail); Vprintf("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)) ) { Vprintf("Allocation failure\n"); exit_status = -1; goto END; } } else { Vprintf("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; Vprintf("\nThe test point is:\n"); for (i = 0; i < n; ++i) Vprintf(" %8.4f", x[i]); Vprintf("\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) { Vprintf("Error from nag_opt_check_deriv (e04hcc).\n%s\n", fail.message); exit_status = 1; goto END; } Vprintf("\nFirst derivatives are consistent with function values.\n\n"); Vprintf("At the test point, objfun gives the function value %11.4e\n", objf); Vprintf("and the 1st derivatives\n\n"); for (i = 0; i < n; ++i) Vprintf(" %9.3e ", g[i]); Vprintf("\n"); END: if (x) NAG_FREE(x); if (g) NAG_FREE(g); return exit_status; }