Prev Next FirstOrder

Comparing Real and Complex Step First Order Derivatives

Description
Running the FirstOrder program (as described below) results in the output below. In this output, h is the step size, f_x(x) is the derivative that is being approximated, rStep(x) is the central difference approximation for the derivative, and cStep(x) is the complex step method approximation for the derivative.
     f_x(x)            = 10
     
     h                 = 0.0001
     f_x(x) - rStep(x) = -5.00033e-08
     f_x(x) - cStep(x) = 5e-08
     
     
     h                 = 1e-05
     f_x(x) - rStep(x) = -5.09601e-10
     f_x(x) - cStep(x) = 5e-10
     
     
     h                 = 1e-06
     f_x(x) - rStep(x) = 3.78579e-10
     f_x(x) - cStep(x) = 5.00044e-12
     
     
     h                 = 1e-07
     f_x(x) - rStep(x) = -5.83867e-09
     f_x(x) - cStep(x) = 4.9738e-14
     


Local Include Files
The program FirstOrder uses the following local include files ExampleFun.h , CentralStep.h , ComplexStep.h .

Running Program
The following commands compile and run FirstOrder and place the output in FirstOrder.out:
 
     g++ -g FirstOrder.cpp -o FirstOrder
     FirstOrder > FirstOrder.out

Source Code
 

# include <iostream>
# include <complex>

# include "ExampleFun.h"
# include "CentralStep.h"
# include "ComplexStep.h"


int main(void)
{    using std::cout;
     using std::endl;
     using std::complex;

     // real and complex types
     typedef double         Real;
     typedef complex<Real>  Comp;

     // real and complex function types
     typedef Real (*RealFun) (const Real &);
     typedef Comp (*CompFun) (const Comp &);

     // first order difference type
     typedef CentralStep<RealFun, Real> RealStep;
     typedef ComplexStep<CompFun, Real> CompStep;

     // real and complex versions of ExampleFun
     Real (*rf) (const Real &x)  = ExampleFun<Real>;
     Comp (*cf) (const Comp &x)  = ExampleFun<Comp>;

     Real x   = 1.;
     Real f_x = ExampleFun_x(x);
     cout << "f_x(x)            = " << f_x << endl;

     Real h = 1e-3;
     int i;
     for(i = 0; i < 4; i++)
     {    // next step size
          h = h / 10.;

          // real and complex step method
          RealStep rStep(rf, h);
          CompStep cStep(cf, h);

          cout << endl;
          cout << "h                 = " << h << endl;
          cout << "f_x(x) - rStep(x) = " 
               <<  f_x - rStep(x) << endl;
          cout << "f_x(x) - cStep(x) = " 
               <<  f_x - cStep(x) << endl;
          cout << endl;
     }

     return 0;
}


Input File: FirstOrder.cpp