bundles / scipy 1.17.1 / scipy / optimize / _numdiff / check_derivative
function
scipy.optimize._numdiff:check_derivative
source: /scipy/optimize/_numdiff.py :886
Signature
def check_derivative ( fun , jac , x0 , bounds = (-inf, inf) , args = () , kwargs = None ) Summary
Check correctness of a function computing derivatives (Jacobian or gradient) by comparison with a finite difference approximation.
Parameters
fun: callableFunction of which to estimate the derivatives. The argument x passed to this function is ndarray of shape (n,) (never a scalar even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
jac: callableFunction which computes Jacobian matrix of
fun. It must work with argument x the same way asfun. The return value must be array_like or sparse array with an appropriate shape.x0: array_like of shape (n,) or floatPoint at which to estimate the derivatives. Float will be converted to 1-D array.
bounds: 2-tuple of array_like, optionalLower and upper bounds on independent variables. Defaults to no bounds. Each bound must match the size of
x0or be a scalar, in the latter case the bound will be the same for all variables. Use it to limit the range of function evaluation.args, kwargs: tuple and dict, optionalAdditional arguments passed to
funandjac. Both empty by default. The calling signature isfun(x, *args, **kwargs)and the same forjac.
Returns
accuracy: floatThe maximum among all relative errors for elements with absolute values higher than 1 and absolute errors for elements with absolute values less or equal than 1. If accuracy is on the order of 1e-6 or lower, then it is likely that your
jacimplementation is correct.
Examples
import numpy as np from scipy.optimize._numdiff import check_derivative def f(x, c1, c2): return np.array([x[0] * np.sin(c1 * x[1]), x[0] * np.cos(c2 * x[1])]) def jac(x, c1, c2): return np.array([ [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])], [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])] ]) x0 = np.array([1.0, 0.5 * np.pi])✓
check_derivative(f, jac, x0, args=(1, 2))
✗See also
- approx_derivative
Compute finite difference approximation of derivative.
Aliases
-
scipy.optimize._numdiff.check_derivative