Differentiation
===============

Finite difference approximation of derivatives (``diff``)
---------------------------------------------------------

The function ``diff`` computes a derivative of a given function. It uses a simple two-point finite difference approximation, but increases the working precision to get good results. The step size is chosen roughly equal to the ``eps`` of the working precision, and the function values are computed at twice the working precision; for reasonably smooth functions, this typically gives full accuracy::

    >>> from mpmath import *
    >>> mp.dps = 15
    >>> print diff(cos, 1)
    -0.841470984807897
    >>> print -sin(1)
    -0.841470984807897

One-sided derivatives can be computed by specifying the ``direction`` parameter. With ``direction = 0`` (default), ``diff`` uses a central difference (f(x-h), f(x+h)). With ``direction = 1``, it uses a forward difference (f(x), f(x+h)), and with ``direction = -1``, a backward difference (f(x-h), f(x))::

    >>> print diff(abs, 0, direction=0)
    0.0
    >>> print diff(abs, 0, direction=1)
    1.0
    >>> print diff(abs, 0, direction=-1)
    -1.0

Differentiation by integration (``diffc``)
------------------------------------------

Although the finite difference approximation can be applied recursively to compute n-th order derivatives, this is inefficient for large n since 2^n evaluation points are required, using 2^n-fold extra precision. As an alternative, the function ``diffc`` computes derivatives of arbitrary order by means of complex contour integration. It is for example able to compute a 13th-order derivative of sin (here at x = 0)::

    >>> mp.dps = 15
    >>> print diffc(sin, 0, 13)
    (0.9999987024793 - 6.23819166183936e-13j)

The accuracy can be improved by increasing the radius of the integration contour (provided that the function is well-behaved within this region)::

    >>> print diffc(sin, 0, 13, radius=5)
    (1.0 + 1.44139403318761e-23j)
