Skip to content

polykin.math¤

derivative_complex ¤

derivative_complex(
    f: Callable[[complex], complex], x: float
) -> tuple[float, float]

Calculate the numerical derivative of a scalar function using the complex differentiation method.

\[ f'(x) = \frac{\text{Im}\left(f(x + i h) \right)}{h} + O(h^2) \]

Note

This method is efficient, very accurate, and not ill-conditioned. However, its application is restricted to real functions that can be evaluated with complex inputs, but which per se do not implement complex arithmetic.

References

PARAMETER DESCRIPTION
f

Function to be diferentiated.

TYPE: Callable[[complex], complex]

x

Diferentiation point.

TYPE: float

RETURNS DESCRIPTION
tuple[float, float]

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

Examples:

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

>>> from polykin.math import derivative_complex
>>> def f(x): return x**3
>>> derivative_complex(f, 1.)
(3.0, 1.0)
Source code in src/polykin/math/derivatives.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def derivative_complex(f: Callable[[complex], complex],
                       x: float
                       ) -> tuple[float, float]:
    r"""Calculate the numerical derivative of a scalar function using the
    complex differentiation method.

    $$ f'(x) = \frac{\text{Im}\left(f(x + i h) \right)}{h} + O(h^2) $$

    !!! note

        This method is efficient, very accurate, and not ill-conditioned.
        However, its application is restricted to real functions that can be
        evaluated with complex inputs, but which per se do not implement
        complex arithmetic.

    **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[[complex], complex]
        Function to be diferentiated.
    x : float
        Diferentiation point.

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

    Examples
    --------
    Evaluate the numerical derivative of f(x)=x**3 at x=1.
    >>> from polykin.math import derivative_complex
    >>> def f(x): return x**3
    >>> derivative_complex(f, 1.)
    (3.0, 1.0)
    """
    fz = f(complex(x, eps))
    return (fz.imag/eps, fz.real)