/* nag_zero_nonlin_eqns_deriv (c05pbc) Example Program. * * Copyright 1991 Numerical Algorithms Group. * * Mark 2, 1991. * Mark 7 revised, 2001. * Mark 8 revised, 2004. */ #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL f(Integer n, const double x[], double fvec[], double fjac[], Integer tdfjac, Integer *userflag); #ifdef __cplusplus } #endif int main(void) { Integer exit_status = 0, j, n = 9, tdfjac; NagError fail; double *fjac = 0, *fvec = 0, *x = 0, xtol; INIT_FAIL(fail); printf("nag_zero_nonlin_eqns_deriv (c05pbc) Example Program Results\n"); /* The following starting values provide a rough solution. */ 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; } } else { printf("Invalid n.\n"); exit_status = 1; return exit_status; } for (j = 0; j < n; j++) x[j] = -1.0; tdfjac = n; /* nag_machine_precision (x02ajc). * The machine precision */ xtol = sqrt(nag_machine_precision); /* nag_zero_nonlin_eqns_deriv (c05pbc). * Solution of a system of nonlinear equations (using first * derivatives) */ nag_zero_nonlin_eqns_deriv(n, x, fvec, fjac, tdfjac, f, xtol, &fail); if (fail.code == NE_NOERROR) { printf("Final approximate solution\n\n"); for (j = 0; j < n; j++) printf("%12.4f%s", x[j], (j%3 == 2 || j == n-1)?"\n":" "); } else { printf("Error from nag_zero_nonlin_eqns_deriv (c05pbc).\n%s\n", fail.message); if (fail.code == NE_TOO_MANY_FUNC_EVAL || fail.code == NE_XTOL_TOO_SMALL || fail.code == NE_NO_IMPROVEMENT) { printf("Approximate solution\n\n"); for (j = 0; j < n; j++) printf("%12.4f%s", x[j], (j%3 == 2 || j == n-1)?"\n":" "); } exit_status = 1; } 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) { #define FJAC(I, J) fjac[((I))*tdfjac+(J)] Integer j, k; if (*userflag != 2) { 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 { 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; } } }