/* * Author: Moshe Moshonov * Email: moshemosh@mail.tau.ac.il * Date: 08/03/2015 * ID: 123456789 * * Short Description: * This program computes a 1st order derivative of a function using a central * difference scheme. * The function is chosen to be a simple exponent. * * Compilation: g++ my_simple_program.cpp -lm -o my_simple_program * Execute in Shell: ./my_simple_program */ #include #include /* * This function computes the value of function f at point x and returns the * result. * * Parameters: * x - Point to evaluate function. */ double f(double x) { return exp(x); } /* * This function computes the 1st order derivative of function f at point x and returns the * result. * * The derivative is computed using a central difference scheme: * f(x + dx) - f(x - dx) * --------------------- * 2 * dx * * Parameters: * x - Point to evaluate derivative. * dx - Step size to use for approximation (After Taylor expansion). */ double df_dx(double x, double dx) { return (f(x + dx) - f(x - dx)) / (2.0 * dx); } int main() { /* Point to compute f' at. */ double x = 2.0; /* Step size for approximation. */ double dx = 0.0001; printf("f = exp(x)\n\n"); printf("f'(%.7f) = ?\n", x, df_dx(x, dx)); printf("Approximate: %.7f\n", df_dx(x, dx)); printf("Analytic: %.7f\n", f(x)); return 0; }