/* nag_check_deriv (c05zbc) 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 NAG_CALL f(Integer n, const double xc[], double fvecc[], double fjacc[], Integer tdj, Integer *userflag); #ifdef __cplusplus } #endif int main(void) { #define FJAC(I, J) fjac[(I) *tdfjac + J] Integer exit_status = 0, i, j, n, tdfjac; NagError fail; double *fjac = 0, *fvec = 0, *x = 0; INIT_FAIL(fail); printf("nag_check_deriv (c05zbc) Example Program Results\n"); n = 3; if (n > 0) { if (!(fjac = NAG_ALLOC(n*n, double)) || !(fvec = NAG_ALLOC(n, double)) || !(x = NAG_ALLOC(n, double))) { printf("Allocation failure\n"); exit_status = -1; goto END; } tdfjac = n; } else { printf("Invalid n.\n"); exit_status = 1; return exit_status; } /* Set up an arbitrary point at which to check the 1st derivatives */ x[0] = 9.2e-01; x[1] = 1.3e-01; x[2] = 5.4e-01; printf("The test point is "); for (j = 0; j < n; ++j) printf("%13.3e", x[j]); printf("\n\n"); /* nag_check_deriv (c05zbc). * Derivative checker for nag_zero_nonlin_eqns_deriv * (c05pbc) */ nag_check_deriv(n, x, fvec, fjac, tdfjac, f, &fail); if (fail.code != NE_NOERROR) { printf("Error from nag_check_deriv (c05zbc).\n%s\n", fail.message); exit_status = 1; goto END; } printf("1st derivatives are consistent with residual values.\n\n"); printf("At the test point, f() gives\n\n"); printf(" Residuals 1st derivatives\n\n"); for (i = 0; i < n; ++i) { printf("%13.3e", fvec[i]); for (j = 0; j < n; ++j) printf("%13.3e", FJAC(i, j)); printf("\n"); } END: if (fjac) NAG_FREE(fjac); if (fvec) NAG_FREE(fvec); if (x) NAG_FREE(x); return exit_status; } static void NAG_CALL f(Integer n, const double x[], double fvec[], double fjac[], Integer tdfjac, Integer *userflag) { Integer j, k; if (*userflag != 2) { /* Calculate the function values */ for (k = 0; k < n; k++) { fvec[k] = (3.0-x[k]*2.0) * x[k] + 1.0; if (k > 0) fvec[k] -= x[k-1]; if (k < n-1) fvec[k] -= x[k+1] * 2.0; } } else { /* Calculate the corresponding first derivatives */ for (k = 0; k < n; k++) { for (j = 0; j < n; j++) FJAC(k, j) = 0.0; FJAC(k, k) = 3.0 - x[k] * 4.0; if (k > 0) FJAC(k, k-1) = -1.0; if (k < n-1) FJAC(k, k+1) = -2.0; } } }