#NEWLINE# def approx_fprime( x , f , epsilon = None , args = ( ) , kwargs = { #NEWLINE# #INDENT# #NEWLINE# #UNINDENT# } , centered = False ) : #NEWLINE# #INDENT# '\n    Gradient of function, or Jacobian if function f returns 1d array\n\n    Parameters\n    ----------\n    x : array\n        parameters at which the derivative is evaluated\n    f : function\n        `f(*((x,)+args), **kwargs)` returning either one value or 1d array\n    epsilon : float, optional\n        Stepsize, if None, optimal stepsize is used. This is EPS**(1/2)*x for\n        `centered` == False and EPS**(1/3)*x for `centered` == True.\n    args : tuple\n        Tuple of additional arguments for function `f`.\n    kwargs : dict\n        Dictionary of additional keyword arguments for function `f`.\n    centered : bool\n        Whether central difference should be returned. If not, does forward\n        differencing.\n\n    Returns\n    -------\n    grad : array\n        gradient or Jacobian\n\n    Notes\n    -----\n    If f returns a 1d array, it returns a Jacobian. If a 2d array is returned\n    by f (e.g., with a value for each observation), it returns a 3d array\n    with the Jacobian of each observation with shape xk x nobs x xk. I.e.,\n    the Jacobian of the first observation would be [:, 0, :]\n    ' #NEWLINE# n = len ( x ) #NEWLINE# f0 = f ( * ( ( x , ) + args ) , ** kwargs ) #NEWLINE# dim = np . atleast_1d ( f0 ) . shape #NEWLINE# grad = np . zeros ( ( ( n , ) + dim ) , float ) #NEWLINE# ei = np . zeros ( ( n , ) , float ) #NEWLINE# if ( not centered ) : #NEWLINE# #INDENT# epsilon = _get_epsilon ( x , 2 , epsilon , n ) #NEWLINE# for k in range ( n ) : #NEWLINE# #INDENT# ei [ k ] = epsilon [ k ] #NEWLINE# grad [ k , : ] = ( ( f ( * ( ( ( x + ei ) , ) + args ) , ** kwargs ) - f0 ) / epsilon [ k ] ) #NEWLINE# ei [ k ] = 0.0 #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# epsilon = ( _get_epsilon ( x , 3 , epsilon , n ) / 2.0 ) #NEWLINE# for k in range ( len ( x ) ) : #NEWLINE# #INDENT# ei [ k ] = epsilon [ k ] #NEWLINE# grad [ k , : ] = ( ( f ( * ( ( ( x + ei ) , ) + args ) , ** kwargs ) - f ( * ( ( ( x - ei ) , ) + args ) , ** kwargs ) ) / ( 2 * epsilon [ k ] ) ) #NEWLINE# ei [ k ] = 0.0 #NEWLINE# #UNINDENT# #UNINDENT# return grad . squeeze ( ) . T