/* nag_opt_lsq_check_deriv (e04yac) Example Program * * Copyright 1991 Numerical Algorithms Group. * * Mark 2, 1991. * Mark 7 revised, 2001. * */ #include #include #include #include #ifdef __cplusplus extern "C" { #endif static void lsqfun(Integer m, Integer n, double x[], double fvec[], double fjac[], Integer tdj, Nag_Comm *comm); #ifdef __cplusplus } #endif int main(void) { #define MMAX 15 #define NMAX 3 #define Y(I) comm.user[I] #define T(I,J) comm.user[(I)*NMAX + (J) + MMAX] double fjac[MMAX][NMAX], fvec[MMAX], x[NMAX]; double work[MMAX + MMAX*NMAX]; Integer i, j, m, n, tdj; Nag_Comm comm; static NagError fail; Vprintf("e04yac Example Program Results\n"); Vscanf(" %*[^\n]"); /* Skip heading in data file */ n = 3; m = 15; tdj = NMAX; fail.print = TRUE; /* Allocate memory to communication array */ comm.user = work; /* Observations t (j = 0, 1, 2) are held in T(i, j) * (i = 0, 1, 2, . . . , 14) */ for (i = 0; i < m; ++i) { Vscanf("%lf", &Y(i)); for (j = 0; j < n; ++j) Vscanf("%lf", &T(i,j)); } /* Set up an arbitrary point at which to check the 1st derivatives */ x[0] = 0.19; x[1] = -1.34; x[2] = 0.88; Vprintf("\nThe test point is "); for (j = 0; j < n; ++j) Vprintf(" %9.3e", x[j]); Vprintf("\n"); fail.print = TRUE; e04yac(m, n, lsqfun, x, fvec, &fjac[0][0], tdj, &comm, &fail); if (fail.code != NE_NOERROR) return EXIT_FAILURE; Vprintf("\nDerivatives are consistent with residual values.\n"); Vprintf("\nAt the test point, lsqfun() gives\n\n"); Vprintf(" Residuals 1st derivatives\n"); for (i = 0; i < m; ++i) { Vprintf(" %9.3e ", fvec[i]); for (j = 0; j < n; ++j) Vprintf(" %9.3e", fjac[i][j]); Vprintf("\n"); } return EXIT_SUCCESS; } static void lsqfun(Integer m, Integer n, double x[], double fvec[], double fjac[], Integer tdj, Nag_Comm *comm) { /* Function to evaluate the residuals and their 1st derivatives. */ #define YC(I) comm->user[(I)] #define TC(I,J) comm->user[(I)*NMAX + (J) + MMAX] #define FJAC(I,J) fjac[(I)*tdj + (J)] Integer i; double denom, dummy; for (i = 0; i < m; ++i) { denom = x[1]*TC(i,1) + x[2]*TC(i,2); if (comm->flag != 1) fvec[i] = x[0] + TC(i,0)/denom - YC(i); if (comm->flag != 0) { FJAC(i,0) = 1.0; dummy = -1.0 / (denom * denom); FJAC(i,1) = TC(i,0)*TC(i,1)*dummy; FJAC(i,2) = TC(i,0)*TC(i,2)*dummy; } } } /* lsqfun */