def check_delta(fun, x, dxs, period=None):
dn1s = []<EOL>dn2s = []<EOL>dnds = []<EOL>for dx in dxs:<EOL><INDENT>f0, grad0 = fun(x, do_gradient=True)<EOL>f1, grad1 = fun(x+dx, do_gradient=True)<EOL>grad = <NUM_LIT:0.5>*(grad0+grad1)<EOL>d1 = f1 - f0<EOL>if period is not None:<EOL><INDENT>d1 -= np.floor(d1/period + <NUM_LIT:0.5>)*period<EOL><DEDENT>if hasattr(d1, '<STR_LIT>'):<EOL><INDENT>norm = np.linalg.norm<EOL><DEDENT>else:<EOL><INDENT>norm = abs<EOL><DEDENT>d2 = np.dot(grad, dx)<EOL>dn1s.append(norm(d1))<EOL>dn2s.append(norm(d2))<EOL>dnds.append(norm(d1-d2))<EOL><DEDENT>dn1s = np.array(dn1s)<EOL>dn2s = np.array(dn2s)<EOL>dnds = np.array(dnds)<EOL>threshold = np.median(dn1s)<EOL>mask = dn1s > threshold<EOL>if not (dnds[mask] < threshold).all():<EOL><INDENT>raise AssertionError((<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>% (threshold,<EOL>'<STR_LIT:U+0020>'.join('<STR_LIT>' % v for v in dn1s[mask]),<EOL>'<STR_LIT:U+0020>'.join('<STR_LIT>' % v for v in dn2s[mask]),<EOL>'<STR_LIT:U+0020>'.join('<STR_LIT>' % v for v in dnds[mask])<EOL>))<EOL><DEDENT>
Check the difference between two function values using the analytical gradient

       Arguments:
        | ``fun``  --  The function to be tested, more info below.
        | ``x``  --  The argument vector.
        | ``dxs``  --  A matrix where each row is a vector of small differences
                       to be added to the argument vector.

       Optional argument:
        | ``period``  --  If the function value is periodic, one may provide the
                          period such that differences are computed using
                          periodic boundary conditions.

       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]

       For every row in dxs, the following computation is repeated:

       1) D1 = 'f(x+dx) - f(x)' is computed.
       2) D2 = '0.5 (grad f(x+dx) + grad f(x)) . dx' is computed.

       A threshold is set to the median of the D1 set. For each case where |D1|
       is larger than the threshold, |D1 - D2|, should be smaller than the
       threshold.