bundles / scipy 2.0.0.dev0+git20260907.41eeb59 / scipy / differentiate / _differentiate / derivative
function
scipy.differentiate._differentiate:derivative
source: build-install/usr/lib/python3.14/site-packages/scipy/differentiate/_differentiate.py:71
Signature
def derivative(f, x, *, args = (), kwargs = None, tolerances = None, maxiter = 10, order = 8, initial_step = 0.5, step_factor = 2.0, step_direction = 0, preserve_shape = False, callback = None)Summary
Evaluate the derivative of an elementwise, real scalar function numerically.
Extended Summary
For each element of the output of f, derivative approximates the first derivative of f at the corresponding element of x using finite difference differentiation.
This function works elementwise when x, step_direction, and args contain (broadcastable) arrays.
Parameters
f: callableThe function whose derivative is desired. The signature must be
f(xi: ndarray, *argsi) -> ndarraywhere each element of
xiis a finite real number andargsiis a tuple, which may contain an arbitrary number of arrays that are broadcastable withxi.fmust be an elementwise function: each scalar elementf(xi)[j]must equalf(xi[j])for valid indicesj. It must not mutate the arrayxior the arrays inargsi.x: float array_likeAbscissae at which to evaluate the derivative. Must be broadcastable with
argsandstep_direction.args: tuple of array_like, optionalAdditional positional array arguments to be passed to
f. Arrays must be broadcastable with one another and the arrays ofinit. If the callable for which the root is desired requires arguments that are not broadcastable withx, wrap that callable withfsuch thatfaccepts onlyxand broadcastable*args.kwargs: dict of str:array_like, optionalAdditional keyword arguments to be passed to
f. Seeargs.tolerances: dictionary of floats, optionalAbsolute and relative tolerances. Valid keys of the dictionary are:
atol- absolute tolerance on the derivativertol- relative tolerance on the derivative
Iteration will stop when
res.error < atol + rtol * abs(res.df). The defaultatolis the smallest normal number of the appropriate dtype, and the defaultrtolis the square root of the precision of the appropriate dtype.maxiter: int, default: 10The maximum number of iterations of the algorithm to perform. See Notes.
order: int, default: 8The (positive integer) order of the finite difference formula to be used. Odd integers will be rounded up to the next even integer.
initial_step: float array_like, default: 0.5The (absolute) initial step size for the finite difference derivative approximation.
step_factor: float, default: 2.0The factor by which the step size is reduced in each iteration; i.e. the step size in iteration 1 is
initial_step/step_factor. Ifstep_factor < 1, subsequent steps will be greater than the initial step; this may be useful if steps smaller than some threshold are undesirable (e.g. due to subtractive cancellation error).step_direction: int array_likeAn array representing the direction of the finite difference steps (for use when
xlies near to the boundary of the domain of the function.) Must be broadcastable withxand allargs. Where 0 (default), central differences are used; where negative (e.g. -1), steps are non-positive; and where positive (e.g. 1), all steps are non-negative.preserve_shape: bool, default: FalseIn the following, "arguments of
f" refers to the arrayxiand any arrays withinargsi. Letshapebe the broadcasted shape ofxand all elements ofargs(which is conceptually distinct fromxi` and ``argsipassed intof).When
preserve_shape=False(default),fmust accept arguments of any broadcastable shapes.When
preserve_shape=True,fmust accept arguments of shapeshape + (n,), wherenis the number of abscissae at which the function is being evaluated.
In either case, for each scalar element
xi[j]withinxi, the array returned byfmust include the scalarf(xi[j])at the same index. Consequently, the shape of the output is always the shape of the inputxi.See Examples.
callback: callable, optionalAn optional user-supplied function to be called before the first iteration and after each iteration. Called as
callback(res), whereresis a_RichResultsimilar to that returned by derivative (but containing the current iterate's values of all variables). Ifcallbackraises aStopIteration, the algorithm will terminate immediately and derivative will return a result.callbackmust not mutate res or its attributes.
Returns
res: _RichResultAn object similar to an instance of scipy.optimize.OptimizeResult with the following attributes. The descriptions are written as though the values will be scalars; however, if
freturns an array, the outputs will be arrays of the same shape.success
Truewhere the algorithm terminated successfully (status0);Falseotherwise.status
An integer representing the exit status of the algorithm.
0The algorithm converged to the specified tolerances.-1The error estimate increased, so iteration was terminated.-2The maximum number of iterations was reached.-3A non-finite value was encountered.-4Iteration was terminated bycallback.1The algorithm is proceeding normally (incallbackonly).
df
The derivative of
fatx, if the algorithm terminated successfully.error
An estimate of the error: the magnitude of the difference between the current estimate of the derivative and the estimate in the previous iteration.
nit
The number of iterations of the algorithm that were performed.
nfev
The number of points at which
fwas evaluated.x
The value at which the derivative of
fwas evaluated (after broadcasting withargsandstep_direction).
Notes
The implementation was inspired by jacobi [1], numdifftools [2], and DERIVEST [3], but the implementation follows the theory of Taylor series more straightforwardly (and arguably naively so). In the first iteration, the derivative is estimated using a finite difference formula of order order with maximum step size initial_step. Each subsequent iteration, the maximum step size is reduced by step_factor, and the derivative is estimated again until a termination condition is reached. The error estimate is the magnitude of the difference between the current derivative approximation and that of the previous iteration.
The stencils of the finite difference formulae are designed such that abscissae are "nested": after f is evaluated at order + 1 points in the first iteration, f is evaluated at only two new points in each subsequent iteration; order - 1 previously evaluated function values required by the finite difference formula are reused, and two function values (evaluations at the points furthest from x) are unused.
Step sizes are absolute. When the step size is small relative to the magnitude of x, precision is lost; for example, if x is 1e20, the default initial step size of 0.5 cannot be resolved. Accordingly, consider using larger initial step sizes for large magnitudes of x.
The default tolerances are challenging to satisfy at points where the true derivative is exactly zero. If the derivative may be exactly zero, consider specifying an absolute tolerance (e.g. atol=1e-12) to improve convergence.
Examples
Evaluate the derivative of ``np.exp`` at several points ``x``.import numpy as np from scipy.differentiate import derivative f = np.exp df = np.exp # true derivative x = np.linspace(1, 2, 5) res = derivative(f, x)✓
res.df # approximation of the derivative res.error # estimate of the error abs(res.df - df(x)) # true error✗
array([2.26e-14, 3.38e-14, 6.13e-14, 9.68e-14, 1.22e-13])Show the convergence of the approximation as the step size is reduced. Each iteration, the step size is reduced by `step_factor`, so for sufficiently small initial step, each iteration reduces the error by a factor of ``1/step_factor**order`` until finite precision arithmetic inhibits further improvement.
import matplotlib.pyplot as plt iter = list(range(1, 12)) # maximum iterations hfac = 2 # step size reduction per iteration hdir = [-1, 0, 1] # compare left-, central-, and right- steps order = 4 # order of differentiation formula x = 1 ref = df(x) errors = [] # true error for i in iter: res = derivative(f, x, maxiter=i, step_factor=hfac, step_direction=hdir, order=order, # prevent early termination tolerances=dict(atol=0, rtol=0)) errors.append(abs(res.df - ref)) errors = np.array(errors)✓
plt.semilogy(iter, errors[:, 0], label='left differences') plt.semilogy(iter, errors[:, 1], label='central differences') plt.semilogy(iter, errors[:, 2], label='right differences') plt.xlabel('iteration') plt.ylabel('error') plt.legend()✗
<matplotlib.legend.Legend object at 0x7f3f685f6510>
plt.show()
✓
(errors[1, 1] / errors[0, 1], 1 / hfac**order)
✗(np.float64(0.062152231405411804), 0.0625)The implementation is vectorized over `x`, `step_direction`, and `args`. The function is evaluated once before the first iteration to perform input validation and standardization, and once per iteration thereafter.
def f(x, p): f.nit += 1 return x**p f.nit = 0 def df(x, p): return p*x**(p-1) x = np.arange(1, 5) p = np.arange(1, 6).reshape((-1, 1)) hdir = np.arange(-1, 2).reshape((-1, 1, 1)) res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1) np.allclose(res.df, df(x, p)) res.df.shape f.nit✓
2By default, `preserve_shape` is False, and therefore the callable `f` may be called with arrays of any broadcastable shapes. For example:
shapes = [] def f(x, c): shape = np.broadcast_shapes(x.shape, c.shape) shapes.append(shape) return np.sin(c*x) c = [1, 5, 10, 20] res = derivative(f, 0, args=(c,)) shapes✓
[(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]To understand where these shapes are coming from - and to better understand how `derivative` computes accurate results - note that higher values of ``c`` correspond with higher frequency sinusoids. The higher frequency sinusoids make the function's derivative change faster, so more function evaluations are required to achieve the target accuracy:
res.nfev
✓array([11, 13, 15, 17], dtype=int32)The initial ``shape``, ``(4,)``, corresponds with evaluating the function at a single abscissa and all four frequencies; this is used for input validation and to determine the size and dtype of the arrays that store results. The next shape corresponds with evaluating the function at an initial grid of abscissae and all four frequencies. Successive calls to the function evaluate the function at two more abscissae, increasing the effective order of the approximation by two. However, in later function evaluations, the function is evaluated at fewer frequencies because the corresponding derivative has already converged to the required tolerance. This saves function evaluations to improve performance, but it requires the function to accept arguments of any shape. "Vector-valued" functions are unlikely to satisfy this requirement. For example, consider
def f(x): return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]✓
shapes = [] def f(x): shapes.append(x.shape) x0, x1, x2, x3 = x return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2] x = np.zeros(4) res = derivative(f, x, preserve_shape=True) shapes✓
[(4, 1), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]Here, the shape of input ``x`` is ``(4,)``. With ``preserve_shape=True``, the callable ``f`` is always called with argument ``x`` of shape ``(4, n)``, where ``n`` is any number of abscissae.
See also
Aliases
scipy.differentiate.derivative