def check_derivative(fun, jac, x0, bounds=((- np.inf), np.inf), args=(), kwargs={}):
 J_to_test = jac(x0, *args, **kwargs)
 if issparse(J_to_test):
  J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test, args=args, kwargs=kwargs)
  J_to_test = csr_matrix(J_to_test)
  abs_err = (J_to_test - J_diff)
  (i, j, abs_err_data) = find(abs_err)
  J_diff_data = np.asarray(J_diff[(i, j)]).ravel()
  return np.max((np.abs(abs_err_data) / np.maximum(1, np.abs(J_diff_data))))
 else:
  J_diff = approx_derivative(fun, x0, bounds=bounds, args=args, kwargs=kwargs)
  abs_err = np.abs((J_to_test - J_diff))
  return np.max((abs_err / np.maximum(1, np.abs(J_diff))))

def check_derivative ( fun , jac , x0 , bounds = ( ( - np . inf ) , np . inf ) , args = ( ) , kwargs = { } ) : J_to_test = jac ( x0 , * args , ** kwargs ) if issparse ( J_to_test ) : J_diff = approx_derivative ( fun , x0 , bounds = bounds , sparsity = J_to_test , args = args , kwargs = kwargs ) J_to_test = csr_matrix ( J_to_test ) abs_err = ( J_to_test - J_diff ) ( i , j , abs_err_data ) = find ( abs_err ) J_diff_data = np . asarray ( J_diff [ ( i , j ) ] ) . ravel ( ) return np . max ( ( np . abs ( abs_err_data ) / np . maximum ( 1 , np . abs ( J_diff_data ) ) ) ) else : J_diff = approx_derivative ( fun , x0 , bounds = bounds , args = args , kwargs = kwargs ) abs_err = np . abs ( ( J_to_test - J_diff ) ) return np . max ( ( abs_err / np . maximum ( 1 , np . abs ( J_diff ) ) ) )
check correctness of a function computing derivatives by comparison with a finite difference approximation .