/* nag_zero_nonlin_eqns_deriv_rcomm (c05rdc) Example Program. * * Copyright 2011 Numerical Algorithms Group. * * Mark 23, 2011. */ #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL fcn(Integer n, const double x[], double fvec[], double fjac[], Integer irevcm); #ifdef __cplusplus } #endif int main(void) { Integer exit_status = 0, i, j, n = 9, irevcm; NagError fail; Nag_ScaleType scale_mode; double *diag = 0, *fjac = 0, *fvec = 0, *qtf = 0, *r = 0, *x = 0, *rwsav = 0; Integer *iwsav = 0; double factor, xtol; INIT_FAIL(fail); printf("nag_zero_nonlin_eqns_deriv_rcomm (c05rdc) Example Program Results\n"); if (n > 0) { if (!(diag = NAG_ALLOC(n, double)) || !(fjac = NAG_ALLOC(n*n, double)) || !(fvec = NAG_ALLOC(n, double)) || !(qtf = NAG_ALLOC(n, double)) || !(r = NAG_ALLOC(n*(n+1)/2, double)) || !(x = NAG_ALLOC(n, double)) || !(iwsav = NAG_ALLOC(17, Integer)) || !(rwsav = NAG_ALLOC(4*n + 10, double))) { printf("Allocation failure\n"); exit_status = -1; goto END; } } else { printf("Invalid n.\n"); exit_status = 1; goto END; } /* The following starting values provide a rough solution. */ for (j = 0; j < n; j++) x[j] = -1.0; /* nag_machine_precision (x02ajc). * The machine precision */ xtol = sqrt(nag_machine_precision); for (j = 0; j < n; j++) diag[j] = 1.0; scale_mode = Nag_ScaleProvided; factor = 100.0; irevcm = 0; /* nag_zero_nonlin_eqns_deriv_rcomm (c05rdc). * Solution of a system of nonlinear equations (function values only, * reverse communication) */ do { nag_zero_nonlin_eqns_deriv_rcomm(&irevcm, n, x, fvec, fjac, xtol, scale_mode, diag, factor, r, qtf, iwsav, rwsav, &fail); switch (irevcm) { case 1: /* x and fvec are available for printing */ break; case 2: case 3: fcn(n, x, fvec, fjac, irevcm); break; } } while (irevcm != 0); 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_rcomm (c05rdc).\n%s\n", fail.message); if (fail.code == NE_TOO_SMALL || fail.code == NE_NO_IMPROVEMENT) { printf("Approximate solution\n\n"); for (i = 0; i < n; i++) printf("%12.4f%s", x[i], (i%3 == 2 || i == n-1)?"\n":" "); exit_status = 2; } } END: if (diag) NAG_FREE(diag); if (fjac) NAG_FREE(fjac); if (fvec) NAG_FREE(fvec); if (qtf) NAG_FREE(qtf); if (r) NAG_FREE(r); if (x) NAG_FREE(x); if (iwsav) NAG_FREE(iwsav); if (rwsav) NAG_FREE(rwsav); return exit_status; } static void NAG_CALL fcn(Integer n, const double x[], double fvec[], double fjac[], Integer irevcm) { Integer j, k; if (irevcm == 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 if (irevcm == 3) { for (k = 0; k < n; k++) { for (j = 0; j < n; j++) fjac[j*n + k] = 0.0; fjac[k*n + k] = 3.0 - x[k] * 4.0; if (k > 0) fjac[(k-1)*n + k] = -1.0; if (k < n-1) fjac[(k+1)*n + k] = -2.0; } } }