def check_anagrad(fun, x0, epsilon, threshold):
N = len(x0)<EOL>f0, ana_grad = fun(x0, do_gradient=True)<EOL>for i in range(N):<EOL><INDENT>xh = x0.copy()<EOL>xh[i] += <NUM_LIT:0.5>*epsilon<EOL>xl = x0.copy()<EOL>xl[i] -= <NUM_LIT:0.5>*epsilon<EOL>num_grad_comp = (fun(xh)-fun(xl))/epsilon<EOL>if abs(num_grad_comp - ana_grad[i]) > threshold:<EOL><INDENT>raise AssertionError("<STR_LIT>" % (i, ana_grad[i], num_grad_comp))<EOL><DEDENT><DEDENT>
Check the analytical gradient using finite differences

       Arguments:
        | ``fun``  --  the function to be tested, more info below
        | ``x0``  --  the reference point around which the function should be
                      tested
        | ``epsilon``  --  a small scalar used for the finite differences
        | ``threshold``  --  the maximum acceptable difference between the
                             analytical gradient and the gradient obtained by
                             finite differentiation

       The function ``fun`` takes a mandatory argument ``x`` and an optional
       argument ``do_gradient``:
        | ``x``  --  the arguments of the function to be tested
        | ``do_gradient``  --  When False, only the function value is returned.
                               When True, a 2-tuple with the function value and
                               the gradient are returned [default=False]