![]() |
Object-oriented Scientific Computing Library: Version 0.910
|
Differentiation is performed by descendants of deriv and the classes are provided. These allow one to calculate either first, second, and third derivatives. The GSL approach is used in gsl_deriv, and the CERNLIB routine is used in cern_deriv. Both of these compute derivatives for a function specified using a descendant of funct. For functions which are tabulated over equally-spaced abscissas, the class eqi_deriv is provided which applies the formulas from Abramowitz and Stegun at a specified order. The class cern_deriv is slower and sometimes more accurate, but also fails more often than gsl_deriv, which never calls the error handler.
Warning: For gsl_deriv and cern_deriv, the second and third derivatives are calculated by naive repeated application of the code for the first derivative and can be particularly troublesome if the function is not sufficiently smooth. Error estimation is not provided for second and third derivatives.
This example computes first and second derivatives of
with both gsl_deriv and cern_deriv .
/* Example: ex_deriv.cpp ------------------------------------------------------------------- An example to demonstrate numerical differentiation */ #include <cmath> #include <o2scl/test_mgr.h> #include <o2scl/funct.h> #include <o2scl/ovector_tlate.h> #include <o2scl/gsl_deriv.h> #include <o2scl/cern_deriv.h> using namespace std; using namespace o2scl; class cl { public: // This is the function we'll take the derivative of double function(double x) { return sin(2.0*x)+0.5; } }; int main(void) { test_mgr t; t.set_output_level(2); // The class and associated function cl acl; funct_mfptr<cl> f1(&acl,&cl::function); gsl_deriv<> gd; // Note that the GSL derivative routine requires an initial stepsize gd.h=1.0e-3; cern_deriv<> cd; // Compute the first derivative using the gsl_deriv class and // verify that the answer is correct double d1=gd.calc(1.0,f1); t.test_rel(d1,2.0*cos(2.0),1.0e-10,"gsl_deriv"); // Compute the first derivative using the cern_deriv class and // verify that the answer is correct double d2=cd.calc(1.0,f1); t.test_rel(d2,2.0*cos(2.0),1.0e-10,"cern_deriv"); // Compute the second derivative also double d3=gd.calc2(1.0,f1); t.test_rel(d3,-4.0*sin(2.0),5.0e-7,"gsl_deriv"); double d4=cd.calc2(1.0,f1); t.test_rel(d4,-4.0*sin(2.0),1.0e-8,"cern_deriv"); t.report(); return 0; } // End of example
Documentation generated with Doxygen. Provided under the GNU Free Documentation License (see License Information).