Skip to content

polykin.math¤

derivative_centered ¤

derivative_centered(
    f: Callable[[float], float], x: float, h: float = 0.0
) -> tuple[float, float]

Calculate the numerical derivative of a scalar function using the centered finite-difference scheme.

\[ f'(x) = \frac{f(x + h) - f(x - h)}{2 h} + O(h^2) \]

References

PARAMETER DESCRIPTION
f

Function to be diferentiated.

TYPE: Callable[[float], float]

x

Differentiation point.

TYPE: float

h

Finite-difference step. If 0, it will be set to the theoretical optimum value \(h=\sqrt[3]{3\epsilon}\).

TYPE: float DEFAULT: 0.0

RETURNS DESCRIPTION
tuple[float, float]

Tuple with derivative and mean function value, \((f'(x), f(x))\).

Examples:

Evaluate the numerical derivative of f(x)=x**3 at x=1.

>>> from polykin.math import derivative_centered
>>> def f(x): return x**3
>>> derivative_centered(f, 1.)
(3.0000000003141882, 1.0000000009152836)
Source code in src/polykin/math/derivatives.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def derivative_centered(f: Callable[[float], float],
                        x: float,
                        h: float = 0.
                        ) -> tuple[float, float]:
    r"""Calculate the numerical derivative of a scalar function using the
    centered finite-difference scheme.

    $$ f'(x) = \frac{f(x + h) - f(x - h)}{2 h} + O(h^2) $$

    **References**

    *   J. Martins and A. Ning. Engineering Design Optimization. Cambridge
    University Press, 2021.
    *   [boost/math/differentiation/finite_difference.hpp](https://www.boost.org/doc/libs/1_80_0/boost/math/differentiation/finite_difference.hpp).

    Parameters
    ----------
    f : Callable[[float], float]
        Function to be diferentiated.
    x : float
        Differentiation point.
    h : float
        Finite-difference step. If `0`, it will be set to the theoretical
        optimum value $h=\sqrt[3]{3\epsilon}$.

    Returns
    -------
    tuple[float, float]
        Tuple with derivative and mean function value, $(f'(x), f(x))$.

    Examples
    --------
    Evaluate the numerical derivative of f(x)=x**3 at x=1.
    >>> from polykin.math import derivative_centered
    >>> def f(x): return x**3
    >>> derivative_centered(f, 1.)
    (3.0000000003141882, 1.0000000009152836)
    """

    if h == 0:
        h = cbrt(3*eps)    # ~ 1e-5

    h *= (1 + abs(x))

    fp = f(x + h)
    fm = f(x - h)
    df = (fp - fm)/(2*h)
    fx = (fp + fm)/2

    return (df, fx)