bundles / scipy latest / scipy / differentiate / _differentiate / derivative
function
scipy.differentiate._differentiate:derivative
Signature
def derivative ( f , x , * , args = () , 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.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.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).maxiter: int, default: 10The maximum number of iterations of the algorithm to perform. See Notes.
step_direction: integer 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 shapeshapeorshape + (n,), where(n,)is 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 byderivative(but containing the current iterate's values of all variables). Ifcallbackraises aStopIteration, the algorithm will terminate immediately andderivativewill 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
success
status
status
df
df
error
error
nit
nit
nfev
nfev
x
x
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.
Array API Standard Support
derivative has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable SCIPY_ARRAY_API=1 and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.
==================== ==================== ==================== Library CPU GPU ==================== ==================== ==================== NumPy ✅ n/a CuPy n/a ✅ PyTorch ✅ ✅ JAX ⚠️ no JIT ⚠️ no JIT Dask ⛔ n/a ==================== ==================== ====================
See
dev-arrayapifor more information.
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✗
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()✗
plt.show()
✓
(errors[1, 1] / errors[0, 1], 1 / hfac**order)
✗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✓
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✓
res.nfev
✓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✓
See also
Aliases
-
scipy.differentiate.derivative