Go to the first, previous, next, last section, table of contents.


Numerical Differentiation

The functions described in this chapter compute numerical derivatives by finite differencing. An adaptive algorithm is used to find the best choice of finite difference and to estimate the error in the derivative. These functions are declared in the header file `gsl_diff.h'

Functions

Function: int gsl_diff_central (const gsl_function *f, double x, double *result, double *abserr)
This function computes the numerical derivative of the function f at the point x using an adaptive central difference algorithm. The derivative is returned in result and an estimate of its absolute error is returned in abserr.

Function: int gsl_diff_forward (const gsl_function *f, double x, double *result, double *abserr)
This function computes the numerical derivative of the function f at the point x using an adaptive forward difference algorithm. The function is evaluated only at points greater than x and at x itself. The derivative is returned in result and an estimate of its absolute error is returned in abserr. This function should be used if f(x) has a singularity or is undefined for values less than x.

Function: int gsl_diff_backward (const gsl_function *f, double x, double *result, double *abserr)
This function computes the numerical derivative of the function f at the point x using an adaptive backward difference algorithm. The function is evaluated only at points less than x and at x itself. The derivative is returned in result and an estimate of its absolute error is returned in abserr. This function should be used if f(x) has a singularity or is undefined for values greater than x.

Example

The following code estimates the derivative of the function f(x) = x^{3/2} at x=2 and at x=0. The function f(x) is undefined for x<0 so the derivative at x=0 is computed using gsl_diff_forward.

#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_diff.h>

double f (double x, void * params)
{
  return pow (x, 1.5);
}

int
main (void)
{
  gsl_function F;
  double result, abserr;

  F.function = &f;
  F.params = 0;

  printf("f(x) = x^(3/2)\n");

  gsl_diff_central (&F, 2.0, &result, &abserr);
  printf("x = 2.0\n");
  printf("f'(x) = %.10f +/- %.5f\n", result, abserr);
  printf("exact = %.10f\n\n", 1.5 * sqrt(2.0));

  gsl_diff_forward (&F, 0.0, &result, &abserr);
  printf("x = 0.0\n");
  printf("f'(x) = %.10f +/- %.5f\n", result, abserr);
  printf("exact = %.10f\n", 0.0);

  return 0;
}

Here is the output of the program,

$ ./demo 
f(x) = x^(3/2)

x = 2.0
f'(x) = 2.1213203435 +/- 0.01490
exact = 2.1213203436

x = 0.0
f'(x) = 0.0012172897 +/- 0.05028
exact = 0.0000000000

References and Further Reading

The algorithms used by these functions are described in the following book,


Go to the first, previous, next, last section, table of contents.