/* 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 #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL f(Integer n, double xc[], double fvecc[], double fjacc[], Integer tdj, Integer *userflag); #ifdef __cplusplus } #endif int main(int argc, char *argv[]) { FILE *fpout; #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); /* Check for command-line IO options */ fpout = nag_example_file_io(argc, argv, "-results", NULL); fprintf(fpout, "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))) { fprintf(fpout, "Allocation failure\n"); exit_status = -1; goto END; } tdfjac = n; } else { fprintf(fpout, "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; fprintf(fpout, "The test point is "); for (j = 0; j < n; ++j) fprintf(fpout, "%13.3e", x[j]); fprintf(fpout, "\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) { fprintf(fpout, "Error from nag_check_deriv (c05zbc).\n%s\n", fail.message); exit_status = 1; goto END; } fprintf(fpout, "1st derivatives are consistent with residual values.\n\n"); fprintf(fpout, "At the test point, f() gives\n\n"); fprintf(fpout, " Residuals 1st derivatives\n\n"); for (i = 0; i < n; ++i) { fprintf(fpout, "%13.3e", fvec[i]); for (j = 0; j < n; ++j) fprintf(fpout, "%13.3e", FJAC(i, j)); fprintf(fpout, "\n"); } END: if (fpout != stdout) fclose(fpout); 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, 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; } } }