/* nag_zero_nonlin_eqns_1 (c05tbc) Example Program. * * Copyright 1998 Numerical Algorithms Group. * * Mark 5, 1998. * Mark 7 revised, 2001. * Mark 8 revised, 2004. */ #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void NAG_CALL f(Integer n, double x[], double fvec[], Integer *userflag, Nag_User *comm); #ifdef __cplusplus } #endif int main(int argc, char *argv[]) { FILE *fpout; Integer exit_status = 0, i, j, n = 9; NagError fail; Nag_User comm; double *fvec = 0, *x = 0, xtol; INIT_FAIL(fail); /* Check for command-line IO options */ fpout = nag_example_file_io(argc, argv, "-results", NULL); fprintf(fpout, "nag_zero_nonlin_eqns_1 (c05tbc) Example Program Results\n"); if (n > 0) { if (!(fvec = NAG_ALLOC(n, double)) || !(x = NAG_ALLOC(n, double))) { fprintf(fpout, "Allocation failure\n"); exit_status = -1; goto END; } } else { fprintf(fpout, "Invalid n.\n"); exit_status = 1; return exit_status; } /* 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(X02AJC); /* nag_zero_nonlin_eqns_1 (c05tbc). * Solution of a system of nonlinear equations (function * values only), thread-safe */ nag_zero_nonlin_eqns_1(n, x, fvec, f, xtol, &comm, &fail); if (fail.code == NE_NOERROR) { fprintf(fpout, "Final approximate solution\n\n"); for (j = 0; j < n; j++) fprintf(fpout, "%12.4f%s", x[j], (j%3 == 2 || j == n-1)?"\n":" "); } else { fprintf(fpout, "Error from nag_zero_nonlin_eqns_1 (c05tbc).\n%s\n", fail.message); if (fail.code == NE_TOO_MANY_FUNC_EVAL || fail.code == NE_XTOL_TOO_SMALL || fail.code == NE_NO_IMPROVEMENT) { fprintf(fpout, "Approximate solution\n\n"); for (i = 0; i < n; i++) fprintf(fpout, "%12.4f%s", x[i], (i%3 == 2 || i == n-1)?"\n":" "); exit_status = 2; } } END: if (fpout != stdout) fclose(fpout); if (fvec) NAG_FREE(fvec); if (x) NAG_FREE(x); return exit_status; } static void NAG_CALL f(Integer n, double x[], double fvec[], Integer *userflag, Nag_User *comm) { Integer k; 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; } }