// Lecture 2. Example 1. "Numerical derivative" // Complile: g++ -o numderivative numderivative.cc -lm #include using namespace std; #include #include #define PRECISION float // Set precision level PRECISION f (PRECISION x ) { return exp(x); // function of interest } PRECISION exact_derivative (PRECISION x ) { return exp(x); // its exact analytical derivative } PRECISION num_derivative (PRECISION x, PRECISION h ) { return (f(x + h) - f(x))/h; // its numerical derivative } main() { PRECISION x = 1.0; PRECISION h=0.0; PRECISION ErrPrev = 100.0; PRECISION Error = 100.0; // Sanity check. Comment out. // cout << f(x) << endl; // Output results: cout << endl; cout << endl; cout << "--------------------Example--------------------------" << endl; cout << "Evaluate (approximate) numerical derivative of a specified function using df/dx ~ [f(x+h) - f(x)]/h. Compare with an exact result. Make your own conclusions. " << endl; cout << endl; cout << " step size h" << " Exact value of df/dx " << " Approximate df/dx " << " Relative error (%) " << endl; for (int i=0; i >= -20; i-- ) { if (ErrPrev > Error) ErrPrev = Error; h = pow(10.0, (PRECISION)(i) ); Error = 100.0*fabs( (exact_derivative(x) - num_derivative(x, h))/exact_derivative(x) ); // cout << " " << exact_derivative(x) << " " << h << " " << num_derivative(x, h) << " " << 100.0*fabs(exact_derivative(x) - num_derivative(x, h))/exact_derivative(x) << endl; printf("%5.3e %s %10.7f %s %10.7f %s %7.5f \n", h, " ", exact_derivative(x), " ", num_derivative(x, h), " ", Error ) ; } if (ErrPrev > Error ) { cout << endl; cout << "It works! (seems like....)" << endl; cout << endl; } else { cout << endl; cout << " CONCLUSION: The difference between theory and pratice is larger in practice than in theory " << endl; cout << endl; } }