/* nag_numdiff_1d_real (d04aac) Example Program. * * Copyright 2011, Numerical Algorithms Group. * * Mark 23, 2011. */ #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static double NAG_CALL fun(double x, Nag_Comm *comm); #ifdef __cplusplus } #endif int main(void) { Integer exit_status = 0; double hbase; Integer i, k, l, start, step; double h_init; double h_reduce; double xval; Integer nder; double der[14], erest[14]; NagError fail; INIT_FAIL(fail); printf("nag_numdiff_1d_real (d04aac) Example Program Results\n"); /* abs(nder) is largest order derivative required. */ nder = -7; l = fabs(nder); /* nder < 0 and nder is even means only even derivatives, * and nder < 0 and nder is odd, only odd derivatives. */ if (nder < 0) { start = (l % 2 ? 0 : 1); step = 2; } else { start = 0; step = 1; } /* Initial step size. */ h_init = 0.5; hbase = h_init; /* Reduction factor applied to successive step sizes. */ h_reduce = 0.1; /* Derivatives will be evaluated at x = xval. */ xval = 0.5; printf("\n" "Four separate runs to calculate the first four odd order derivatives " "of\n" " fun(x) = 0.5*exp(2.0*x-1.0) at x = 0.5.\n" "The exact results are 1, 4, 16 and 64\n\n" "Input parameters common to all four runs\n" " xval = %f nder = %ld\n", xval, nder); for (k = 0; k < 4; k++) { /* nag_numdiff_1d_real (d04aac). * Numerical differentiation, derivatives up to order 14, * function of one real variable. */ nag_numdiff_1d_real(xval, nder, hbase, der, erest, fun, NAGCOMM_NULL, &fail); if (fail.code != NE_NOERROR) { printf("Error from nag_numdiff_1d_real (d04aac).\n%s\n", fail.message); exit_status = 1; goto END; } printf("\n" "with step length %f the results are\n" "Order Derivative Error estimate\n", hbase); for (i = start; i < MIN(l,14); i += step) printf("%2ld %21.4e %21.4e\n", i+1, der[i], erest[i]); hbase = hbase * h_reduce; } END: return exit_status; } static double NAG_CALL fun(double x, Nag_Comm *comm) { return 0.5*exp(2.0*x - 1.0); }