{"kind":"task","effective_mode":"full","benchmark":{"kind":"benchmark","effective_mode":"full","slug":"longbench-v2","formal_name":"LongBench v2","introduction":"長い資料の深い理解と推論を、多肢選択問題で評価するベンチマークです。公式紹介では503問を収録し、単一・複数文書の質問応答やコードリポジトリ理解などを扱います。\n\nLongBench v2 evaluates deep understanding and reasoning over long contexts through multiple-choice questions. Its official description lists 503 questions spanning tasks such as single-document and multi-document QA and code-repository understanding.","introduction_ja":"","introduction_en":"","category":"Category not supplied","task_count":null,"acquisition_status":"Acquisition status not supplied","official_url":"https://huggingface.co/datasets/zai-org/LongBench-v2","indexing_mode":"noindex"},"task_id":"263aa241-406b-5f65-9445-029efb98de5a","task_key":"train--66fa208bbb02136c067c5fc1","task_revision_id":"1","upstream_id":"66fa208bbb02136c067c5fc1","short_description":"In the function that calculates the derivative of given functions, which of the…","config":"","split":"train","body":"{\"choice_A\":\"singular, addprec, function\",\"choice_B\":\"h, method, direction\",\"choice_C\":\"relative, fc, y\",\"choice_D\":\"radius, x, step\",\"context\":\"\\\"\\\"\\\"\\nImplements the PSLQ algorithm for integer relation detection,\\nand derivative algorithms for constant recognition.\\n\\\"\\\"\\\"\\n\\nfrom .libmp.backend import xrange\\nfrom .libmp import int_types, sqrt_fixed\\n\\n# round to nearest integer (can be done more elegantly...)\\ndef round_fixed(x, prec):\\n    return ((x + (1<<(prec-1))) >> prec) << prec\\n\\nclass IdentificationMethods(object):\\n    pass\\n\\n\\ndef pslq(ctx, x, tol=None, maxcoeff=1000, maxsteps=100, verbose=False):\\n    r\\\"\\\"\\\"\\n    Given a vector of real numbers `x = [x_0, x_1, ..., x_n]`, ``pslq(x)``\\n    uses the PSLQ algorithm to find a list of integers\\n    `[c_0, c_1, ..., c_n]` such that\\n\\n    .. math ::\\n\\n        |c_1 x_1 + c_2 x_2 + ... + c_n x_n| < \\\\mathrm{tol}\\n\\n    and such that `\\\\max |c_k| < \\\\mathrm{maxcoeff}`. If no such vector\\n    exists, :func:`~mpmath.pslq` returns ``None``. The tolerance defaults to\\n    3/4 of the working precision.\\n\\n    **Examples**\\n\\n    Find rational approximations for `\\\\pi`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> pslq([-1, pi], tol=0.01)\\n        [22, 7]\\n        >>> pslq([-1, pi], tol=0.001)\\n        [355, 113]\\n        >>> mpf(22)/7; mpf(355)/113; +pi\\n        3.14285714285714\\n        3.14159292035398\\n        3.14159265358979\\n\\n    Pi is not a rational number with denominator less than 1000::\\n\\n        >>> pslq([-1, pi])\\n        >>>\\n\\n    To within the standard precision, it can however be approximated\\n    by at least one rational number with denominator less than `10^{12}`::\\n\\n        >>> p, q = pslq([-1, pi], maxcoeff=10**12)\\n        >>> print(p); print(q)\\n        238410049439\\n        75888275702\\n        >>> mpf(p)/q\\n        3.14159265358979\\n\\n    The PSLQ algorithm can be applied to long vectors. For example,\\n    we can investigate the rational (in)dependence of integer square\\n    roots::\\n\\n        >>> mp.dps = 30\\n        >>> pslq([sqrt(n) for n in range(2, 5+1)])\\n        >>>\\n        >>> pslq([sqrt(n) for n in range(2, 6+1)])\\n        >>>\\n        >>> pslq([sqrt(n) for n in range(2, 8+1)])\\n        [2, 0, 0, 0, 0, 0, -1]\\n\\n    **Machin formulas**\\n\\n    A famous formula for `\\\\pi` is Machin's,\\n\\n    .. math ::\\n\\n        \\\\frac{\\\\pi}{4} = 4 \\\\operatorname{acot} 5 - \\\\operatorname{acot} 239\\n\\n    There are actually infinitely many formulas of this type. Two\\n    others are\\n\\n    .. math ::\\n\\n        \\\\frac{\\\\pi}{4} = \\\\operatorname{acot} 1\\n\\n        \\\\frac{\\\\pi}{4} = 12 \\\\operatorname{acot} 49 + 32 \\\\operatorname{acot} 57\\n            + 5 \\\\operatorname{acot} 239 + 12 \\\\operatorname{acot} 110443\\n\\n    We can easily verify the formulas using the PSLQ algorithm::\\n\\n        >>> mp.dps = 30\\n        >>> pslq([pi/4, acot(1)])\\n        [1, -1]\\n        >>> pslq([pi/4, acot(5), acot(239)])\\n        [1, -4, 1]\\n        >>> pslq([pi/4, acot(49), acot(57), acot(239), acot(110443)])\\n        [1, -12, -32, 5, -12]\\n\\n    We could try to generate a custom Machin-like formula by running\\n    the PSLQ algorithm with a few inverse cotangent values, for example\\n    acot(2), acot(3) ... acot(10). Unfortunately, there is a linear\\n    dependence among these values, resulting in only that dependence\\n    being detected, with a zero coefficient for `\\\\pi`::\\n\\n        >>> pslq([pi] + [acot(n) for n in range(2,11)])\\n        [0, 1, -1, 0, 0, 0, -1, 0, 0, 0]\\n\\n    We get better luck by removing linearly dependent terms::\\n\\n        >>> pslq([pi] + [acot(n) for n in range(2,11) if n not in (3, 5)])\\n        [1, -8, 0, 0, 4, 0, 0, 0]\\n\\n    In other words, we found the following formula::\\n\\n        >>> 8*acot(2) - 4*acot(7)\\n        3.14159265358979323846264338328\\n        >>> +pi\\n        3.14159265358979323846264338328\\n\\n    **Algorithm**\\n\\n    This is a fairly direct translation to Python of the pseudocode given by\\n    David Bailey, \\\"The PSLQ Integer Relation Algorithm\\\":\\n    http://www.cecm.sfu.ca/organics/papers/bailey/paper/html/node3.html\\n\\n    The present implementation uses fixed-point instead of floating-point\\n    arithmetic, since this is significantly (about 7x) faster.\\n    \\\"\\\"\\\"\\n\\n    n = len(x)\\n    if n < 2:\\n        raise ValueError(\\\"n cannot be less than 2\\\")\\n\\n    # At too low precision, the algorithm becomes meaningless\\n    prec = ctx.prec\\n    if prec < 53:\\n        raise ValueError(\\\"prec cannot be less than 53\\\")\\n\\n    if verbose and prec // max(2,n) < 5:\\n        print(\\\"Warning: precision for PSLQ may be too low\\\")\\n\\n    target = int(prec * 0.75)\\n\\n    if tol is None:\\n        tol = ctx.mpf(2)**(-target)\\n    else:\\n        tol = ctx.convert(tol)\\n\\n    extra = 60\\n    prec += extra\\n\\n    if verbose:\\n        print(\\\"PSLQ using prec %i and tol %s\\\" % (prec, ctx.nstr(tol)))\\n\\n    tol = ctx.to_fixed(tol, prec)\\n    assert tol\\n\\n    # Convert to fixed-point numbers. The dummy None is added so we can\\n    # use 1-based indexing. (This just allows us to be consistent with\\n    # Bailey's indexing. The algorithm is 100 lines long, so debugging\\n    # a single wrong index can be painful.)\\n    x = [None] + [ctx.to_fixed(ctx.mpf(xk), prec) for xk in x]\\n\\n    # Sanity check on magnitudes\\n    minx = min(abs(xx) for xx in x[1:])\\n    if not minx:\\n        raise ValueError(\\\"PSLQ requires a vector of nonzero numbers\\\")\\n    if minx < tol//100:\\n        if verbose:\\n            print(\\\"STOPPING: (one number is too small)\\\")\\n        return None\\n\\n    g = sqrt_fixed((4<<prec)//3, prec)\\n    A = {}\\n    B = {}\\n    H = {}\\n    # Initialization\\n    # step 1\\n    for i in xrange(1, n+1):\\n        for j in xrange(1, n+1):\\n            A[i,j] = B[i,j] = (i==j) << prec\\n            H[i,j] = 0\\n    # step 2\\n    s = [None] + [0] * n\\n    for k in xrange(1, n+1):\\n        t = 0\\n        for j in xrange(k, n+1):\\n            t += (x[j]**2 >> prec)\\n        s[k] = sqrt_fixed(t, prec)\\n    t = s[1]\\n    y = x[:]\\n    for k in xrange(1, n+1):\\n        y[k] = (x[k] << prec) // t\\n        s[k] = (s[k] << prec) // t\\n    # step 3\\n    for i in xrange(1, n+1):\\n        for j in xrange(i+1, n):\\n            H[i,j] = 0\\n        if i <= n-1:\\n            if s[i]:\\n                H[i,i] = (s[i+1] << prec) // s[i]\\n            else:\\n                H[i,i] = 0\\n        for j in range(1, i):\\n            sjj1 = s[j]*s[j+1]\\n            if sjj1:\\n                H[i,j] = ((-y[i]*y[j])<<prec)//sjj1\\n            else:\\n                H[i,j] = 0\\n    # step 4\\n    for i in xrange(2, n+1):\\n        for j in xrange(i-1, 0, -1):\\n            #t = floor(H[i,j]/H[j,j] + 0.5)\\n            if H[j,j]:\\n                t = round_fixed((H[i,j] << prec)//H[j,j], prec)\\n            else:\\n                #t = 0\\n                continue\\n            y[j] = y[j] + (t*y[i] >> prec)\\n            for k in xrange(1, j+1):\\n                H[i,k] = H[i,k] - (t*H[j,k] >> prec)\\n            for k in xrange(1, n+1):\\n                A[i,k] = A[i,k] - (t*A[j,k] >> prec)\\n                B[k,j] = B[k,j] + (t*B[k,i] >> prec)\\n    # Main algorithm\\n    for REP in range(maxsteps):\\n        # Step 1\\n        m = -1\\n        szmax = -1\\n        for i in range(1, n):\\n            h = H[i,i]\\n            sz = (g**i * abs(h)) >> (prec*(i-1))\\n            if sz > szmax:\\n                m = i\\n                szmax = sz\\n        # Step 2\\n        y[m], y[m+1] = y[m+1], y[m]\\n        for i in xrange(1,n+1): H[m,i], H[m+1,i] = H[m+1,i], H[m,i]\\n        for i in xrange(1,n+1): A[m,i], A[m+1,i] = A[m+1,i], A[m,i]\\n        for i in xrange(1,n+1): B[i,m], B[i,m+1] = B[i,m+1], B[i,m]\\n        # Step 3\\n        if m <= n - 2:\\n            t0 = sqrt_fixed((H[m,m]**2 + H[m,m+1]**2)>>prec, prec)\\n            # A zero element probably indicates that the precision has\\n            # been exhausted. XXX: this could be spurious, due to\\n            # using fixed-point arithmetic\\n            if not t0:\\n                break\\n            t1 = (H[m,m] << prec) // t0\\n            t2 = (H[m,m+1] << prec) // t0\\n            for i in xrange(m, n+1):\\n                t3 = H[i,m]\\n                t4 = H[i,m+1]\\n                H[i,m] = (t1*t3+t2*t4) >> prec\\n                H[i,m+1] = (-t2*t3+t1*t4) >> prec\\n        # Step 4\\n        for i in xrange(m+1, n+1):\\n            for j in xrange(min(i-1, m+1), 0, -1):\\n                try:\\n                    t = round_fixed((H[i,j] << prec)//H[j,j], prec)\\n                # Precision probably exhausted\\n                except ZeroDivisionError:\\n                    break\\n                y[j] = y[j] + ((t*y[i]) >> prec)\\n                for k in xrange(1, j+1):\\n                    H[i,k] = H[i,k] - (t*H[j,k] >> prec)\\n                for k in xrange(1, n+1):\\n                    A[i,k] = A[i,k] - (t*A[j,k] >> prec)\\n                    B[k,j] = B[k,j] + (t*B[k,i] >> prec)\\n        # Until a relation is found, the error typically decreases\\n        # slowly (e.g. a factor 1-10) with each step TODO: we could\\n        # compare err from two successive iterations. If there is a\\n        # large drop (several orders of magnitude), that indicates a\\n        # \\\"high quality\\\" relation was detected. Reporting this to\\n        # the user somehow might be useful.\\n        best_err = maxcoeff<<prec\\n        for i in xrange(1, n+1):\\n            err = abs(y[i])\\n            # Maybe we are done?\\n            if err < tol:\\n                # We are done if the coefficients are acceptable\\n                vec = [int(round_fixed(B[j,i], prec) >> prec) for j in \\\\\\n                range(1,n+1)]\\n                if max(abs(v) for v in vec) < maxcoeff:\\n                    if verbose:\\n                        print(\\\"FOUND relation at iter %i/%i, error: %s\\\" % \\\\\\n                            (REP, maxsteps, ctx.nstr(err / ctx.mpf(2)**prec, 1)))\\n                    return vec\\n            best_err = min(err, best_err)\\n        # Calculate a lower bound for the norm. We could do this\\n        # more exactly (using the Euclidean norm) but there is probably\\n        # no practical benefit.\\n        recnorm = max(abs(h) for h in H.values())\\n        if recnorm:\\n            norm = ((1 << (2*prec)) // recnorm) >> prec\\n            norm //= 100\\n        else:\\n            norm = ctx.inf\\n        if verbose:\\n            print(\\\"%i/%i:  Error: %8s   Norm: %s\\\" % \\\\\\n                (REP, maxsteps, ctx.nstr(best_err / ctx.mpf(2)**prec, 1), norm))\\n        if norm >= maxcoeff:\\n            break\\n    if verbose:\\n        print(\\\"CANCELLING after step %i/%i.\\\" % (REP, maxsteps))\\n        print(\\\"Could not find an integer relation. Norm bound: %s\\\" % norm)\\n    return None\\n\\ndef findpoly(ctx, x, n=1, **kwargs):\\n    r\\\"\\\"\\\"\\n    ``findpoly(x, n)`` returns the coefficients of an integer\\n    polynomial `P` of degree at most `n` such that `P(x) \\\\approx 0`.\\n    If no polynomial having `x` as a root can be found,\\n    :func:`~mpmath.findpoly` returns ``None``.\\n\\n    :func:`~mpmath.findpoly` works by successively calling :func:`~mpmath.pslq` with\\n    the vectors `[1, x]`, `[1, x, x^2]`, `[1, x, x^2, x^3]`, ...,\\n    `[1, x, x^2, .., x^n]` as input. Keyword arguments given to\\n    :func:`~mpmath.findpoly` are forwarded verbatim to :func:`~mpmath.pslq`. In\\n    particular, you can specify a tolerance for `P(x)` with ``tol``\\n    and a maximum permitted coefficient size with ``maxcoeff``.\\n\\n    For large values of `n`, it is recommended to run :func:`~mpmath.findpoly`\\n    at high precision; preferably 50 digits or more.\\n\\n    **Examples**\\n\\n    By default (degree `n = 1`), :func:`~mpmath.findpoly` simply finds a linear\\n    polynomial with a rational root::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> findpoly(0.7)\\n        [-10, 7]\\n\\n    The generated coefficient list is valid input to ``polyval`` and\\n    ``polyroots``::\\n\\n        >>> nprint(polyval(findpoly(phi, 2), phi), 1)\\n        -2.0e-16\\n        >>> for r in polyroots(findpoly(phi, 2)):\\n        ...     print(r)\\n        ...\\n        -0.618033988749895\\n        1.61803398874989\\n\\n    Numbers of the form `m + n \\\\sqrt p` for integers `(m, n, p)` are\\n    solutions to quadratic equations. As we find here, `1+\\\\sqrt 2`\\n    is a root of the polynomial `x^2 - 2x - 1`::\\n\\n        >>> findpoly(1+sqrt(2), 2)\\n        [1, -2, -1]\\n        >>> findroot(lambda x: x**2 - 2*x - 1, 1)\\n        2.4142135623731\\n\\n    Despite only containing square roots, the following number results\\n    in a polynomial of degree 4::\\n\\n        >>> findpoly(sqrt(2)+sqrt(3), 4)\\n        [1, 0, -10, 0, 1]\\n\\n    In fact, `x^4 - 10x^2 + 1` is the *minimal polynomial* of\\n    `r = \\\\sqrt 2 + \\\\sqrt 3`, meaning that a rational polynomial of\\n    lower degree having `r` as a root does not exist. Given sufficient\\n    precision, :func:`~mpmath.findpoly` will usually find the correct\\n    minimal polynomial of a given algebraic number.\\n\\n    **Non-algebraic numbers**\\n\\n    If :func:`~mpmath.findpoly` fails to find a polynomial with given\\n    coefficient size and tolerance constraints, that means no such\\n    polynomial exists.\\n\\n    We can verify that `\\\\pi` is not an algebraic number of degree 3 with\\n    coefficients less than 1000::\\n\\n        >>> mp.dps = 15\\n        >>> findpoly(pi, 3)\\n        >>>\\n\\n    It is always possible to find an algebraic approximation of a number\\n    using one (or several) of the following methods:\\n\\n        1. Increasing the permitted degree\\n        2. Allowing larger coefficients\\n        3. Reducing the tolerance\\n\\n    One example of each method is shown below::\\n\\n        >>> mp.dps = 15\\n        >>> findpoly(pi, 4)\\n        [95, -545, 863, -183, -298]\\n        >>> findpoly(pi, 3, maxcoeff=10000)\\n        [836, -1734, -2658, -457]\\n        >>> findpoly(pi, 3, tol=1e-7)\\n        [-4, 22, -29, -2]\\n\\n    It is unknown whether Euler's constant is transcendental (or even\\n    irrational). We can use :func:`~mpmath.findpoly` to check that if is\\n    an algebraic number, its minimal polynomial must have degree\\n    at least 7 and a coefficient of magnitude at least 1000000::\\n\\n        >>> mp.dps = 200\\n        >>> findpoly(euler, 6, maxcoeff=10**6, tol=1e-100, maxsteps=1000)\\n        >>>\\n\\n    Note that the high precision and strict tolerance is necessary\\n    for such high-degree runs, since otherwise unwanted low-accuracy\\n    approximations will be detected. It may also be necessary to set\\n    maxsteps high to prevent a premature exit (before the coefficient\\n    bound has been reached). Running with ``verbose=True`` to get an\\n    idea what is happening can be useful.\\n    \\\"\\\"\\\"\\n    x = ctx.mpf(x)\\n    if n < 1:\\n        raise ValueError(\\\"n cannot be less than 1\\\")\\n    if x == 0:\\n        return [1, 0]\\n    xs = [ctx.mpf(1)]\\n    for i in range(1,n+1):\\n        xs.append(x**i)\\n        a = ctx.pslq(xs, **kwargs)\\n        if a is not None:\\n            return a[::-1]\\n\\ndef fracgcd(p, q):\\n    x, y = p, q\\n    while y:\\n        x, y = y, x % y\\n    if x != 1:\\n        p //= x\\n        q //= x\\n    if q == 1:\\n        return p\\n    return p, q\\n\\ndef pslqstring(r, constants):\\n    q = r[0]\\n    r = r[1:]\\n    s = []\\n    for i in range(len(r)):\\n        p = r[i]\\n        if p:\\n            z = fracgcd(-p,q)\\n            cs = constants[i][1]\\n            if cs == '1':\\n                cs = ''\\n            else:\\n                cs = '*' + cs\\n            if isinstance(z, int_types):\\n                if z > 0: term = str(z) + cs\\n                else:     term = (\\\"(%s)\\\" % z) + cs\\n            else:\\n                term = (\\\"(%s/%s)\\\" % z) + cs\\n            s.append(term)\\n    s = ' + '.join(s)\\n    if '+' in s or '*' in s:\\n        s = '(' + s + ')'\\n    return s or '0'\\n\\ndef prodstring(r, constants):\\n    q = r[0]\\n    r = r[1:]\\n    num = []\\n    den = []\\n    for i in range(len(r)):\\n        p = r[i]\\n        if p:\\n            z = fracgcd(-p,q)\\n            cs = constants[i][1]\\n            if isinstance(z, int_types):\\n                if abs(z) == 1: t = cs\\n                else:           t = '%s**%s' % (cs, abs(z))\\n                ([num,den][z<0]).append(t)\\n            else:\\n                t = '%s**(%s/%s)' % (cs, abs(z[0]), z[1])\\n                ([num,den][z[0]<0]).append(t)\\n    num = '*'.join(num)\\n    den = '*'.join(den)\\n    if num and den: return \\\"(%s)/(%s)\\\" % (num, den)\\n    if num: return num\\n    if den: return \\\"1/(%s)\\\" % den\\n\\ndef quadraticstring(ctx,t,a,b,c):\\n    if c < 0:\\n        a,b,c = -a,-b,-c\\n    u1 = (-b+ctx.sqrt(b**2-4*a*c))/(2*c)\\n    u2 = (-b-ctx.sqrt(b**2-4*a*c))/(2*c)\\n    if abs(u1-t) < abs(u2-t):\\n        if b:  s = '((%s+sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c)\\n        else:  s = '(sqrt(%s)/%s)' % (-4*a*c,2*c)\\n    else:\\n        if b:  s = '((%s-sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c)\\n        else:  s = '(-sqrt(%s)/%s)' % (-4*a*c,2*c)\\n    return s\\n\\n# Transformation y = f(x,c), with inverse function x = f(y,c)\\n# The third entry indicates whether the transformation is\\n# redundant when c = 1\\ntransforms = [\\n  (lambda ctx,x,c: x*c, '$y/$c', 0),\\n  (lambda ctx,x,c: x/c, '$c*$y', 1),\\n  (lambda ctx,x,c: c/x, '$c/$y', 0),\\n  (lambda ctx,x,c: (x*c)**2, 'sqrt($y)/$c', 0),\\n  (lambda ctx,x,c: (x/c)**2, '$c*sqrt($y)', 1),\\n  (lambda ctx,x,c: (c/x)**2, '$c/sqrt($y)', 0),\\n  (lambda ctx,x,c: c*x**2, 'sqrt($y)/sqrt($c)', 1),\\n  (lambda ctx,x,c: x**2/c, 'sqrt($c)*sqrt($y)', 1),\\n  (lambda ctx,x,c: c/x**2, 'sqrt($c)/sqrt($y)', 1),\\n  (lambda ctx,x,c: ctx.sqrt(x*c), '$y**2/$c', 0),\\n  (lambda ctx,x,c: ctx.sqrt(x/c), '$c*$y**2', 1),\\n  (lambda ctx,x,c: ctx.sqrt(c/x), '$c/$y**2', 0),\\n  (lambda ctx,x,c: c*ctx.sqrt(x), '$y**2/$c**2', 1),\\n  (lambda ctx,x,c: ctx.sqrt(x)/c, '$c**2*$y**2', 1),\\n  (lambda ctx,x,c: c/ctx.sqrt(x), '$c**2/$y**2', 1),\\n  (lambda ctx,x,c: ctx.exp(x*c), 'log($y)/$c', 0),\\n  (lambda ctx,x,c: ctx.exp(x/c), '$c*log($y)', 1),\\n  (lambda ctx,x,c: ctx.exp(c/x), '$c/log($y)', 0),\\n  (lambda ctx,x,c: c*ctx.exp(x), 'log($y/$c)', 1),\\n  (lambda ctx,x,c: ctx.exp(x)/c, 'log($c*$y)', 1),\\n  (lambda ctx,x,c: c/ctx.exp(x), 'log($c/$y)', 0),\\n  (lambda ctx,x,c: ctx.ln(x*c), 'exp($y)/$c', 0),\\n  (lambda ctx,x,c: ctx.ln(x/c), '$c*exp($y)', 1),\\n  (lambda ctx,x,c: ctx.ln(c/x), '$c/exp($y)', 0),\\n  (lambda ctx,x,c: c*ctx.ln(x), 'exp($y/$c)', 1),\\n  (lambda ctx,x,c: ctx.ln(x)/c, 'exp($c*$y)', 1),\\n  (lambda ctx,x,c: c/ctx.ln(x), 'exp($c/$y)', 0),\\n]\\n\\ndef identify(ctx, x, constants=[], tol=None, maxcoeff=1000, full=False,\\n    verbose=False):\\n    r\\\"\\\"\\\"\\n    Given a real number `x`, ``identify(x)`` attempts to find an exact\\n    formula for `x`. This formula is returned as a string. If no match\\n    is found, ``None`` is returned. With ``full=True``, a list of\\n    matching formulas is returned.\\n\\n    As a simple example, :func:`~mpmath.identify` will find an algebraic\\n    formula for the golden ratio::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> identify(phi)\\n        '((1+sqrt(5))/2)'\\n\\n    :func:`~mpmath.identify` can identify simple algebraic numbers and simple\\n    combinations of given base constants, as well as certain basic\\n    transformations thereof. More specifically, :func:`~mpmath.identify`\\n    looks for the following:\\n\\n        1. Fractions\\n        2. Quadratic algebraic numbers\\n        3. Rational linear combinations of the base constants\\n        4. Any of the above after first transforming `x` into `f(x)` where\\n           `f(x)` is `1/x`, `\\\\sqrt x`, `x^2`, `\\\\log x` or `\\\\exp x`, either\\n           directly or with `x` or `f(x)` multiplied or divided by one of\\n           the base constants\\n        5. Products of fractional powers of the base constants and\\n           small integers\\n\\n    Base constants can be given as a list of strings representing mpmath\\n    expressions (:func:`~mpmath.identify` will ``eval`` the strings to numerical\\n    values and use the original strings for the output), or as a dict of\\n    formula:value pairs.\\n\\n    In order not to produce spurious results, :func:`~mpmath.identify` should\\n    be used with high precision; preferably 50 digits or more.\\n\\n    **Examples**\\n\\n    Simple identifications can be performed safely at standard\\n    precision. Here the default recognition of rational, algebraic,\\n    and exp/log of algebraic numbers is demonstrated::\\n\\n        >>> mp.dps = 15\\n        >>> identify(0.22222222222222222)\\n        '(2/9)'\\n        >>> identify(1.9662210973805663)\\n        'sqrt(((24+sqrt(48))/8))'\\n        >>> identify(4.1132503787829275)\\n        'exp((sqrt(8)/2))'\\n        >>> identify(0.881373587019543)\\n        'log(((2+sqrt(8))/2))'\\n\\n    By default, :func:`~mpmath.identify` does not recognize `\\\\pi`. At standard\\n    precision it finds a not too useful approximation. At slightly\\n    increased precision, this approximation is no longer accurate\\n    enough and :func:`~mpmath.identify` more correctly returns ``None``::\\n\\n        >>> identify(pi)\\n        '(2**(176/117)*3**(20/117)*5**(35/39))/(7**(92/117))'\\n        >>> mp.dps = 30\\n        >>> identify(pi)\\n        >>>\\n\\n    Numbers such as `\\\\pi`, and simple combinations of user-defined\\n    constants, can be identified if they are provided explicitly::\\n\\n        >>> identify(3*pi-2*e, ['pi', 'e'])\\n        '(3*pi + (-2)*e)'\\n\\n    Here is an example using a dict of constants. Note that the\\n    constants need not be \\\"atomic\\\"; :func:`~mpmath.identify` can just\\n    as well express the given number in terms of expressions\\n    given by formulas::\\n\\n        >>> identify(pi+e, {'a':pi+2, 'b':2*e})\\n        '((-2) + 1*a + (1/2)*b)'\\n\\n    Next, we attempt some identifications with a set of base constants.\\n    It is necessary to increase the precision a bit.\\n\\n        >>> mp.dps = 50\\n        >>> base = ['sqrt(2)','pi','log(2)']\\n        >>> identify(0.25, base)\\n        '(1/4)'\\n        >>> identify(3*pi + 2*sqrt(2) + 5*log(2)/7, base)\\n        '(2*sqrt(2) + 3*pi + (5/7)*log(2))'\\n        >>> identify(exp(pi+2), base)\\n        'exp((2 + 1*pi))'\\n        >>> identify(1/(3+sqrt(2)), base)\\n        '((3/7) + (-1/7)*sqrt(2))'\\n        >>> identify(sqrt(2)/(3*pi+4), base)\\n        'sqrt(2)/(4 + 3*pi)'\\n        >>> identify(5**(mpf(1)/3)*pi*log(2)**2, base)\\n        '5**(1/3)*pi*log(2)**2'\\n\\n    An example of an erroneous solution being found when too low\\n    precision is used::\\n\\n        >>> mp.dps = 15\\n        >>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)'])\\n        '((11/25) + (-158/75)*pi + (76/75)*e + (44/15)*sqrt(2))'\\n        >>> mp.dps = 50\\n        >>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)'])\\n        '1/(3*pi + (-4)*e + 2*sqrt(2))'\\n\\n    **Finding approximate solutions**\\n\\n    The tolerance ``tol`` defaults to 3/4 of the working precision.\\n    Lowering the tolerance is useful for finding approximate matches.\\n    We can for example try to generate approximations for pi::\\n\\n        >>> mp.dps = 15\\n        >>> identify(pi, tol=1e-2)\\n        '(22/7)'\\n        >>> identify(pi, tol=1e-3)\\n        '(355/113)'\\n        >>> identify(pi, tol=1e-10)\\n        '(5**(339/269))/(2**(64/269)*3**(13/269)*7**(92/269))'\\n\\n    With ``full=True``, and by supplying a few base constants,\\n    ``identify`` can generate almost endless lists of approximations\\n    for any number (the output below has been truncated to show only\\n    the first few)::\\n\\n        >>> for p in identify(pi, ['e', 'catalan'], tol=1e-5, full=True):\\n        ...     print(p)\\n        ...  # doctest: +ELLIPSIS\\n        e/log((6 + (-4/3)*e))\\n        (3**3*5*e*catalan**2)/(2*7**2)\\n        sqrt(((-13) + 1*e + 22*catalan))\\n        log(((-6) + 24*e + 4*catalan)/e)\\n        exp(catalan*((-1/5) + (8/15)*e))\\n        catalan*(6 + (-6)*e + 15*catalan)\\n        sqrt((5 + 26*e + (-3)*catalan))/e\\n        e*sqrt(((-27) + 2*e + 25*catalan))\\n        log(((-1) + (-11)*e + 59*catalan))\\n        ((3/20) + (21/20)*e + (3/20)*catalan)\\n        ...\\n\\n    The numerical values are roughly as close to `\\\\pi` as permitted by the\\n    specified tolerance:\\n\\n        >>> e/log(6-4*e/3)\\n        3.14157719846001\\n        >>> 135*e*catalan**2/98\\n        3.14166950419369\\n        >>> sqrt(e-13+22*catalan)\\n        3.14158000062992\\n        >>> log(24*e-6+4*catalan)-1\\n        3.14158791577159\\n\\n    **Symbolic processing**\\n\\n    The output formula can be evaluated as a Python expression.\\n    Note however that if fractions (like '2/3') are present in\\n    the formula, Python's :func:`~mpmath.eval()` may erroneously perform\\n    integer division. Note also that the output is not necessarily\\n    in the algebraically simplest form::\\n\\n        >>> identify(sqrt(2))\\n        '(sqrt(8)/2)'\\n\\n    As a solution to both problems, consider using SymPy's\\n    :func:`~mpmath.sympify` to convert the formula into a symbolic expression.\\n    SymPy can be used to pretty-print or further simplify the formula\\n    symbolically::\\n\\n        >>> from sympy import sympify # doctest: +SKIP\\n        >>> sympify(identify(sqrt(2))) # doctest: +SKIP\\n        2**(1/2)\\n\\n    Sometimes :func:`~mpmath.identify` can simplify an expression further than\\n    a symbolic algorithm::\\n\\n        >>> from sympy import simplify # doctest: +SKIP\\n        >>> x = sympify('-1/(-3/2+(1/2)*5**(1/2))*(3/2-1/2*5**(1/2))**(1/2)') # doctest: +SKIP\\n        >>> x # doctest: +SKIP\\n        (3/2 - 5**(1/2)/2)**(-1/2)\\n        >>> x = simplify(x) # doctest: +SKIP\\n        >>> x # doctest: +SKIP\\n        2/(6 - 2*5**(1/2))**(1/2)\\n        >>> mp.dps = 30 # doctest: +SKIP\\n        >>> x = sympify(identify(x.evalf(30))) # doctest: +SKIP\\n        >>> x # doctest: +SKIP\\n        1/2 + 5**(1/2)/2\\n\\n    (In fact, this functionality is available directly in SymPy as the\\n    function :func:`~mpmath.nsimplify`, which is essentially a wrapper for\\n    :func:`~mpmath.identify`.)\\n\\n    **Miscellaneous issues and limitations**\\n\\n    The input `x` must be a real number. All base constants must be\\n    positive real numbers and must not be rationals or rational linear\\n    combinations of each other.\\n\\n    The worst-case computation time grows quickly with the number of\\n    base constants. Already with 3 or 4 base constants,\\n    :func:`~mpmath.identify` may require several seconds to finish. To search\\n    for relations among a large number of constants, you should\\n    consider using :func:`~mpmath.pslq` directly.\\n\\n    The extended transformations are applied to x, not the constants\\n    separately. As a result, ``identify`` will for example be able to\\n    recognize ``exp(2*pi+3)`` with ``pi`` given as a base constant, but\\n    not ``2*exp(pi)+3``. It will be able to recognize the latter if\\n    ``exp(pi)`` is given explicitly as a base constant.\\n\\n    \\\"\\\"\\\"\\n\\n    solutions = []\\n\\n    def addsolution(s):\\n        if verbose: print(\\\"Found: \\\", s)\\n        solutions.append(s)\\n\\n    x = ctx.mpf(x)\\n\\n    # Further along, x will be assumed positive\\n    if x == 0:\\n        if full: return ['0']\\n        else:    return '0'\\n    if x < 0:\\n        sol = ctx.identify(-x, constants, tol, maxcoeff, full, verbose)\\n        if sol is None:\\n            return sol\\n        if full:\\n            return [\\\"-(%s)\\\"%s for s in sol]\\n        else:\\n            return \\\"-(%s)\\\" % sol\\n\\n    if tol:\\n        tol = ctx.mpf(tol)\\n    else:\\n        tol = ctx.eps**0.7\\n    M = maxcoeff\\n\\n    if constants:\\n        if isinstance(constants, dict):\\n            constants = [(ctx.mpf(v), name) for (name, v) in sorted(constants.items())]\\n        else:\\n            namespace = dict((name, getattr(ctx,name)) for name in dir(ctx))\\n            constants = [(eval(p, namespace), p) for p in constants]\\n    else:\\n        constants = []\\n\\n    # We always want to find at least rational terms\\n    if 1 not in [value for (name, value) in constants]:\\n        constants = [(ctx.mpf(1), '1')] + constants\\n\\n    # PSLQ with simple algebraic and functional transformations\\n    for ft, ftn, red in transforms:\\n        for c, cn in constants:\\n            if red and cn == '1':\\n                continue\\n            t = ft(ctx,x,c)\\n            # Prevent exponential transforms from wreaking havoc\\n            if abs(t) > M**2 or abs(t) < tol:\\n                continue\\n            # Linear combination of base constants\\n            r = ctx.pslq([t] + [a[0] for a in constants], tol, M)\\n            s = None\\n            if r is not None and max(abs(uw) for uw in r) <= M and r[0]:\\n                s = pslqstring(r, constants)\\n            # Quadratic algebraic numbers\\n            else:\\n                q = ctx.pslq([ctx.one, t, t**2], tol, M)\\n                if q is not None and len(q) == 3 and q[2]:\\n                    aa, bb, cc = q\\n                    if max(abs(aa),abs(bb),abs(cc)) <= M:\\n                        s = quadraticstring(ctx,t,aa,bb,cc)\\n            if s:\\n                if cn == '1' and ('/$c' in ftn):\\n                    s = ftn.replace('$y', s).replace('/$c', '')\\n                else:\\n                    s = ftn.replace('$y', s).replace('$c', cn)\\n                addsolution(s)\\n                if not full: return solutions[0]\\n\\n            if verbose:\\n                print(\\\".\\\")\\n\\n    # Check for a direct multiplicative formula\\n    if x != 1:\\n        # Allow fractional powers of fractions\\n        ilogs = [2,3,5,7]\\n        # Watch out for existing fractional powers of fractions\\n        logs = []\\n        for a, s in constants:\\n            if not sum(bool(ctx.findpoly(ctx.ln(a)/ctx.ln(i),1)) for i in ilogs):\\n                logs.append((ctx.ln(a), s))\\n        logs = [(ctx.ln(i),str(i)) for i in ilogs] + logs\\n        r = ctx.pslq([ctx.ln(x)] + [a[0] for a in logs], tol, M)\\n        if r is not None and max(abs(uw) for uw in r) <= M and r[0]:\\n            addsolution(prodstring(r, logs))\\n            if not full: return solutions[0]\\n\\n    if full:\\n        return sorted(solutions, key=len)\\n    else:\\n        return None\\n\\nIdentificationMethods.pslq = pslq\\nIdentificationMethods.findpoly = findpoly\\nIdentificationMethods.identify = identify\\n\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\n\\ndef monitor(f, input='print', output='print'):\\n    \\\"\\\"\\\"\\n    Returns a wrapped copy of *f* that monitors evaluation by calling\\n    *input* with every input (*args*, *kwargs*) passed to *f* and\\n    *output* with every value returned from *f*. The default action\\n    (specify using the special string value ``'print'``) is to print\\n    inputs and outputs to stdout, along with the total evaluation\\n    count::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 5; mp.pretty = False\\n        >>> diff(monitor(exp), 1)   # diff will eval f(x-h) and f(x+h)\\n        in  0 (mpf('0.99999999906867742538452148'),) {}\\n        out 0 mpf('2.7182818259274480055282064')\\n        in  1 (mpf('1.0000000009313225746154785'),) {}\\n        out 1 mpf('2.7182818309906424675501024')\\n        mpf('2.7182808')\\n\\n    To disable either the input or the output handler, you may\\n    pass *None* as argument.\\n\\n    Custom input and output handlers may be used e.g. to store\\n    results for later analysis::\\n\\n        >>> mp.dps = 15\\n        >>> input = []\\n        >>> output = []\\n        >>> findroot(monitor(sin, input.append, output.append), 3.0)\\n        mpf('3.1415926535897932')\\n        >>> len(input)  # Count number of evaluations\\n        9\\n        >>> print(input[3]); print(output[3])\\n        ((mpf('3.1415076583334066'),), {})\\n        8.49952562843408e-5\\n        >>> print(input[4]); print(output[4])\\n        ((mpf('3.1415928201669122'),), {})\\n        -1.66577118985331e-7\\n\\n    \\\"\\\"\\\"\\n    if not input:\\n        input = lambda v: None\\n    elif input == 'print':\\n        incount = [0]\\n        def input(value):\\n            args, kwargs = value\\n            print(\\\"in  %s %r %r\\\" % (incount[0], args, kwargs))\\n            incount[0] += 1\\n    if not output:\\n        output = lambda v: None\\n    elif output == 'print':\\n        outcount = [0]\\n        def output(value):\\n            print(\\\"out %s %r\\\" % (outcount[0], value))\\n            outcount[0] += 1\\n    def f_monitored(*args, **kwargs):\\n        input((args, kwargs))\\n        v = f(*args, **kwargs)\\n        output(v)\\n        return v\\n    return f_monitored\\n\\ndef timing(f, *args, **kwargs):\\n    \\\"\\\"\\\"\\n    Returns time elapsed for evaluating ``f()``. Optionally arguments\\n    may be passed to time the execution of ``f(*args, **kwargs)``.\\n\\n    If the first call is very quick, ``f`` is called\\n    repeatedly and the best time is returned.\\n    \\\"\\\"\\\"\\n    once = kwargs.get('once')\\n    if 'once' in kwargs:\\n        del kwargs['once']\\n    if args or kwargs:\\n        if len(args) == 1 and not kwargs:\\n            arg = args[0]\\n            g = lambda: f(arg)\\n        else:\\n            g = lambda: f(*args, **kwargs)\\n    else:\\n        g = f\\n    from timeit import default_timer as clock\\n    t1=clock(); v=g(); t2=clock(); t=t2-t1\\n    if t > 0.05 or once:\\n        return t\\n    for i in range(3):\\n        t1=clock();\\n        # Evaluate multiple times because the timer function\\n        # has a significant overhead\\n        g();g();g();g();g();g();g();g();g();g()\\n        t2=clock()\\n        t=min(t,(t2-t1)/10)\\n    return t\\n\\n\\n\\\"\\\"\\\"\\nThis module complements the math and cmath builtin modules by providing\\nfast machine precision versions of some additional functions (gamma, ...)\\nand wrapping math/cmath functions so that they can be called with either\\nreal or complex arguments.\\n\\\"\\\"\\\"\\n\\nimport operator\\nimport math\\nimport cmath\\n\\n# Irrational (?) constants\\npi = 3.1415926535897932385\\ne = 2.7182818284590452354\\nsqrt2 = 1.4142135623730950488\\nsqrt5 = 2.2360679774997896964\\nphi = 1.6180339887498948482\\nln2 = 0.69314718055994530942\\nln10 = 2.302585092994045684\\neuler = 0.57721566490153286061\\ncatalan = 0.91596559417721901505\\nkhinchin = 2.6854520010653064453\\napery = 1.2020569031595942854\\n\\nlogpi = 1.1447298858494001741\\n\\ndef _mathfun_real(f_real, f_complex):\\n    def f(x, **kwargs):\\n        if type(x) is float:\\n            return f_real(x)\\n        if type(x) is complex:\\n            return f_complex(x)\\n        try:\\n            x = float(x)\\n            return f_real(x)\\n        except (TypeError, ValueError):\\n            x = complex(x)\\n            return f_complex(x)\\n    f.__name__ = f_real.__name__\\n    return f\\n\\ndef _mathfun(f_real, f_complex):\\n    def f(x, **kwargs):\\n        if type(x) is complex:\\n            return f_complex(x)\\n        try:\\n            return f_real(float(x))\\n        except (TypeError, ValueError):\\n            return f_complex(complex(x))\\n    f.__name__ = f_real.__name__\\n    return f\\n\\ndef _mathfun_n(f_real, f_complex):\\n    def f(*args, **kwargs):\\n        try:\\n            return f_real(*(float(x) for x in args))\\n        except (TypeError, ValueError):\\n            return f_complex(*(complex(x) for x in args))\\n    f.__name__ = f_real.__name__\\n    return f\\n\\n# Workaround for non-raising log and sqrt in Python 2.5 and 2.4\\n# on Unix system\\ntry:\\n    math.log(-2.0)\\n    def math_log(x):\\n        if x <= 0.0:\\n            raise ValueError(\\\"math domain error\\\")\\n        return math.log(x)\\n    def math_sqrt(x):\\n        if x < 0.0:\\n            raise ValueError(\\\"math domain error\\\")\\n        return math.sqrt(x)\\nexcept (ValueError, TypeError):\\n    math_log = math.log\\n    math_sqrt = math.sqrt\\n\\npow = _mathfun_n(operator.pow, lambda x, y: complex(x)**y)\\nlog = _mathfun_n(math_log, cmath.log)\\nsqrt = _mathfun(math_sqrt, cmath.sqrt)\\nexp = _mathfun_real(math.exp, cmath.exp)\\n\\ncos = _mathfun_real(math.cos, cmath.cos)\\nsin = _mathfun_real(math.sin, cmath.sin)\\ntan = _mathfun_real(math.tan, cmath.tan)\\n\\nacos = _mathfun(math.acos, cmath.acos)\\nasin = _mathfun(math.asin, cmath.asin)\\natan = _mathfun_real(math.atan, cmath.atan)\\n\\ncosh = _mathfun_real(math.cosh, cmath.cosh)\\nsinh = _mathfun_real(math.sinh, cmath.sinh)\\ntanh = _mathfun_real(math.tanh, cmath.tanh)\\n\\nfloor = _mathfun_real(math.floor,\\n    lambda z: complex(math.floor(z.real), math.floor(z.imag)))\\nceil = _mathfun_real(math.ceil,\\n    lambda z: complex(math.ceil(z.real), math.ceil(z.imag)))\\n\\n\\ncos_sin = _mathfun_real(lambda x: (math.cos(x), math.sin(x)),\\n                        lambda z: (cmath.cos(z), cmath.sin(z)))\\n\\ncbrt = _mathfun(lambda x: x**(1./3), lambda z: z**(1./3))\\n\\ndef nthroot(x, n):\\n    r = 1./n\\n    try:\\n        return float(x) ** r\\n    except (ValueError, TypeError):\\n        return complex(x) ** r\\n\\ndef _sinpi_real(x):\\n    if x < 0:\\n        return -_sinpi_real(-x)\\n    n, r = divmod(x, 0.5)\\n    r *= pi\\n    n %= 4\\n    if n == 0: return math.sin(r)\\n    if n == 1: return math.cos(r)\\n    if n == 2: return -math.sin(r)\\n    if n == 3: return -math.cos(r)\\n\\ndef _cospi_real(x):\\n    if x < 0:\\n        x = -x\\n    n, r = divmod(x, 0.5)\\n    r *= pi\\n    n %= 4\\n    if n == 0: return math.cos(r)\\n    if n == 1: return -math.sin(r)\\n    if n == 2: return -math.cos(r)\\n    if n == 3: return math.sin(r)\\n\\ndef _sinpi_complex(z):\\n    if z.real < 0:\\n        return -_sinpi_complex(-z)\\n    n, r = divmod(z.real, 0.5)\\n    z = pi*complex(r, z.imag)\\n    n %= 4\\n    if n == 0: return cmath.sin(z)\\n    if n == 1: return cmath.cos(z)\\n    if n == 2: return -cmath.sin(z)\\n    if n == 3: return -cmath.cos(z)\\n\\ndef _cospi_complex(z):\\n    if z.real < 0:\\n        z = -z\\n    n, r = divmod(z.real, 0.5)\\n    z = pi*complex(r, z.imag)\\n    n %= 4\\n    if n == 0: return cmath.cos(z)\\n    if n == 1: return -cmath.sin(z)\\n    if n == 2: return -cmath.cos(z)\\n    if n == 3: return cmath.sin(z)\\n\\ncospi = _mathfun_real(_cospi_real, _cospi_complex)\\nsinpi = _mathfun_real(_sinpi_real, _sinpi_complex)\\n\\ndef tanpi(x):\\n    try:\\n        return sinpi(x) / cospi(x)\\n    except OverflowError:\\n        if complex(x).imag > 10:\\n            return 1j\\n        if complex(x).imag < 10:\\n            return -1j\\n        raise\\n\\ndef cotpi(x):\\n    try:\\n        return cospi(x) / sinpi(x)\\n    except OverflowError:\\n        if complex(x).imag > 10:\\n            return -1j\\n        if complex(x).imag < 10:\\n            return 1j\\n        raise\\n\\nINF = 1e300*1e300\\nNINF = -INF\\nNAN = INF-INF\\nEPS = 2.2204460492503131e-16\\n\\n_exact_gamma = (INF, 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0,\\n  362880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,\\n  1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0,\\n  121645100408832000.0, 2432902008176640000.0)\\n\\n_max_exact_gamma = len(_exact_gamma)-1\\n\\n# Lanczos coefficients used by the GNU Scientific Library\\n_lanczos_g = 7\\n_lanczos_p = (0.99999999999980993, 676.5203681218851, -1259.1392167224028,\\n     771.32342877765313, -176.61502916214059, 12.507343278686905,\\n     -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)\\n\\ndef _gamma_real(x):\\n    _intx = int(x)\\n    if _intx == x:\\n        if _intx <= 0:\\n            #return (-1)**_intx * INF\\n            raise ZeroDivisionError(\\\"gamma function pole\\\")\\n        if _intx <= _max_exact_gamma:\\n            return _exact_gamma[_intx]\\n    if x < 0.5:\\n        # TODO: sinpi\\n        return pi / (_sinpi_real(x)*_gamma_real(1-x))\\n    else:\\n        x -= 1.0\\n        r = _lanczos_p[0]\\n        for i in range(1, _lanczos_g+2):\\n            r += _lanczos_p[i]/(x+i)\\n        t = x + _lanczos_g + 0.5\\n        return 2.506628274631000502417 * t**(x+0.5) * math.exp(-t) * r\\n\\ndef _gamma_complex(x):\\n    if not x.imag:\\n        return complex(_gamma_real(x.real))\\n    if x.real < 0.5:\\n        # TODO: sinpi\\n        return pi / (_sinpi_complex(x)*_gamma_complex(1-x))\\n    else:\\n        x -= 1.0\\n        r = _lanczos_p[0]\\n        for i in range(1, _lanczos_g+2):\\n            r += _lanczos_p[i]/(x+i)\\n        t = x + _lanczos_g + 0.5\\n        return 2.506628274631000502417 * t**(x+0.5) * cmath.exp(-t) * r\\n\\ngamma = _mathfun_real(_gamma_real, _gamma_complex)\\n\\ndef rgamma(x):\\n    try:\\n        return 1./gamma(x)\\n    except ZeroDivisionError:\\n        return x*0.0\\n\\ndef factorial(x):\\n    return gamma(x+1.0)\\n\\ndef arg(x):\\n    if type(x) is float:\\n        return math.atan2(0.0,x)\\n    return math.atan2(x.imag,x.real)\\n\\n# XXX: broken for negatives\\ndef loggamma(x):\\n    if type(x) not in (float, complex):\\n        try:\\n            x = float(x)\\n        except (ValueError, TypeError):\\n            x = complex(x)\\n    try:\\n        xreal = x.real\\n        ximag = x.imag\\n    except AttributeError:   # py2.5\\n        xreal = x\\n        ximag = 0.0\\n    # Reflection formula\\n    # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0003/\\n    if xreal < 0.0:\\n        if abs(x) < 0.5:\\n            v = log(gamma(x))\\n            if ximag == 0:\\n                v = v.conjugate()\\n            return v\\n        z = 1-x\\n        try:\\n            re = z.real\\n            im = z.imag\\n        except AttributeError:   # py2.5\\n            re = z\\n            im = 0.0\\n        refloor = floor(re)\\n        if im == 0.0:\\n            imsign = 0\\n        elif im < 0.0:\\n            imsign = -1\\n        else:\\n            imsign = 1\\n        return (-pi*1j)*abs(refloor)*(1-abs(imsign)) + logpi - \\\\\\n            log(sinpi(z-refloor)) - loggamma(z) + 1j*pi*refloor*imsign\\n    if x == 1.0 or x == 2.0:\\n        return x*0\\n    p = 0.\\n    while abs(x) < 11:\\n        p -= log(x)\\n        x += 1.0\\n    s = 0.918938533204672742 + (x-0.5)*log(x) - x\\n    r = 1./x\\n    r2 = r*r\\n    s += 0.083333333333333333333*r; r *= r2\\n    s += -0.0027777777777777777778*r; r *= r2\\n    s += 0.00079365079365079365079*r; r *= r2\\n    s += -0.0005952380952380952381*r; r *= r2\\n    s += 0.00084175084175084175084*r; r *= r2\\n    s += -0.0019175269175269175269*r; r *= r2\\n    s += 0.0064102564102564102564*r; r *= r2\\n    s += -0.02955065359477124183*r\\n    return s + p\\n\\n_psi_coeff = [\\n0.083333333333333333333,\\n-0.0083333333333333333333,\\n0.003968253968253968254,\\n-0.0041666666666666666667,\\n0.0075757575757575757576,\\n-0.021092796092796092796,\\n0.083333333333333333333,\\n-0.44325980392156862745,\\n3.0539543302701197438,\\n-26.456212121212121212]\\n\\ndef _digamma_real(x):\\n    _intx = int(x)\\n    if _intx == x:\\n        if _intx <= 0:\\n            raise ZeroDivisionError(\\\"polygamma pole\\\")\\n    if x < 0.5:\\n        x = 1.0-x\\n        s = pi*cotpi(x)\\n    else:\\n        s = 0.0\\n    while x < 10.0:\\n        s -= 1.0/x\\n        x += 1.0\\n    x2 = x**-2\\n    t = x2\\n    for c in _psi_coeff:\\n        s -= c*t\\n        if t < 1e-20:\\n            break\\n        t *= x2\\n    return s + math_log(x) - 0.5/x\\n\\ndef _digamma_complex(x):\\n    if not x.imag:\\n        return complex(_digamma_real(x.real))\\n    if x.real < 0.5:\\n        x = 1.0-x\\n        s = pi*cotpi(x)\\n    else:\\n        s = 0.0\\n    while abs(x) < 10.0:\\n        s -= 1.0/x\\n        x += 1.0\\n    x2 = x**-2\\n    t = x2\\n    for c in _psi_coeff:\\n        s -= c*t\\n        if abs(t) < 1e-20:\\n            break\\n        t *= x2\\n    return s + cmath.log(x) - 0.5/x\\n\\ndigamma = _mathfun_real(_digamma_real, _digamma_complex)\\n\\n# TODO: could implement complex erf and erfc here. Need\\n# to find an accurate method (avoiding cancellation)\\n# for approx. 1 < abs(x) < 9.\\n\\n_erfc_coeff_P = [\\n    1.0000000161203922312,\\n    2.1275306946297962644,\\n    2.2280433377390253297,\\n    1.4695509105618423961,\\n    0.66275911699770787537,\\n    0.20924776504163751585,\\n    0.045459713768411264339,\\n    0.0063065951710717791934,\\n    0.00044560259661560421715][::-1]\\n\\n_erfc_coeff_Q = [\\n    1.0000000000000000000,\\n    3.2559100272784894318,\\n    4.9019435608903239131,\\n    4.4971472894498014205,\\n    2.7845640601891186528,\\n    1.2146026030046904138,\\n    0.37647108453729465912,\\n    0.080970149639040548613,\\n    0.011178148899483545902,\\n    0.00078981003831980423513][::-1]\\n\\ndef _polyval(coeffs, x):\\n    p = coeffs[0]\\n    for c in coeffs[1:]:\\n        p = c + x*p\\n    return p\\n\\ndef _erf_taylor(x):\\n    # Taylor series assuming 0 <= x <= 1\\n    x2 = x*x\\n    s = t = x\\n    n = 1\\n    while abs(t) > 1e-17:\\n        t *= x2/n\\n        s -= t/(n+n+1)\\n        n += 1\\n        t *= x2/n\\n        s += t/(n+n+1)\\n        n += 1\\n    return 1.1283791670955125739*s\\n\\ndef _erfc_mid(x):\\n    # Rational approximation assuming 0 <= x <= 9\\n    return exp(-x*x)*_polyval(_erfc_coeff_P,x)/_polyval(_erfc_coeff_Q,x)\\n\\ndef _erfc_asymp(x):\\n    # Asymptotic expansion assuming x >= 9\\n    x2 = x*x\\n    v = exp(-x2)/x*0.56418958354775628695\\n    r = t = 0.5 / x2\\n    s = 1.0\\n    for n in range(1,22,4):\\n        s -= t\\n        t *= r * (n+2)\\n        s += t\\n        t *= r * (n+4)\\n        if abs(t) < 1e-17:\\n            break\\n    return s * v\\n\\ndef erf(x):\\n    \\\"\\\"\\\"\\n    erf of a real number.\\n    \\\"\\\"\\\"\\n    x = float(x)\\n    if x != x:\\n        return x\\n    if x < 0.0:\\n        return -erf(-x)\\n    if x >= 1.0:\\n        if x >= 6.0:\\n            return 1.0\\n        return 1.0 - _erfc_mid(x)\\n    return _erf_taylor(x)\\n\\ndef erfc(x):\\n    \\\"\\\"\\\"\\n    erfc of a real number.\\n    \\\"\\\"\\\"\\n    x = float(x)\\n    if x != x:\\n        return x\\n    if x < 0.0:\\n        if x < -6.0:\\n            return 2.0\\n        return 2.0-erfc(-x)\\n    if x > 9.0:\\n        return _erfc_asymp(x)\\n    if x >= 1.0:\\n        return _erfc_mid(x)\\n    return 1.0 - _erf_taylor(x)\\n\\ngauss42 = [\\\\\\n(0.99839961899006235, 0.0041059986046490839),\\n(-0.99839961899006235, 0.0041059986046490839),\\n(0.9915772883408609, 0.009536220301748501),\\n(-0.9915772883408609,0.009536220301748501),\\n(0.97934250806374812, 0.014922443697357493),\\n(-0.97934250806374812, 0.014922443697357493),\\n(0.96175936533820439,0.020227869569052644),\\n(-0.96175936533820439, 0.020227869569052644),\\n(0.93892355735498811, 0.025422959526113047),\\n(-0.93892355735498811,0.025422959526113047),\\n(0.91095972490412735, 0.030479240699603467),\\n(-0.91095972490412735, 0.030479240699603467),\\n(0.87802056981217269,0.03536907109759211),\\n(-0.87802056981217269, 0.03536907109759211),\\n(0.8402859832618168, 0.040065735180692258),\\n(-0.8402859832618168,0.040065735180692258),\\n(0.7979620532554873, 0.044543577771965874),\\n(-0.7979620532554873, 0.044543577771965874),\\n(0.75127993568948048,0.048778140792803244),\\n(-0.75127993568948048, 0.048778140792803244),\\n(0.70049459055617114, 0.052746295699174064),\\n(-0.70049459055617114,0.052746295699174064),\\n(0.64588338886924779, 0.056426369358018376),\\n(-0.64588338886924779, 0.056426369358018376),\\n(0.58774459748510932, 0.059798262227586649),\\n(-0.58774459748510932, 0.059798262227586649),\\n(0.5263957499311922, 0.062843558045002565),\\n(-0.5263957499311922, 0.062843558045002565),\\n(0.46217191207042191, 0.065545624364908975),\\n(-0.46217191207042191, 0.065545624364908975),\\n(0.39542385204297503, 0.067889703376521934),\\n(-0.39542385204297503, 0.067889703376521934),\\n(0.32651612446541151, 0.069862992492594159),\\n(-0.32651612446541151, 0.069862992492594159),\\n(0.25582507934287907, 0.071454714265170971),\\n(-0.25582507934287907, 0.071454714265170971),\\n(0.18373680656485453, 0.072656175243804091),\\n(-0.18373680656485453, 0.072656175243804091),\\n(0.11064502720851986, 0.073460813453467527),\\n(-0.11064502720851986, 0.073460813453467527),\\n(0.036948943165351772, 0.073864234232172879),\\n(-0.036948943165351772, 0.073864234232172879)]\\n\\nEI_ASYMP_CONVERGENCE_RADIUS = 40.0\\n\\ndef ei_asymp(z, _e1=False):\\n    r = 1./z\\n    s = t = 1.0\\n    k = 1\\n    while 1:\\n        t *= k*r\\n        s += t\\n        if abs(t) < 1e-16:\\n            break\\n        k += 1\\n    v = s*exp(z)/z\\n    if _e1:\\n        if type(z) is complex:\\n            zreal = z.real\\n            zimag = z.imag\\n        else:\\n            zreal = z\\n            zimag = 0.0\\n        if zimag == 0.0 and zreal > 0.0:\\n            v += pi*1j\\n    else:\\n        if type(z) is complex:\\n            if z.imag > 0:\\n                v += pi*1j\\n            if z.imag < 0:\\n                v -= pi*1j\\n    return v\\n\\ndef ei_taylor(z, _e1=False):\\n    s = t = z\\n    k = 2\\n    while 1:\\n        t = t*z/k\\n        term = t/k\\n        if abs(term) < 1e-17:\\n            break\\n        s += term\\n        k += 1\\n    s += euler\\n    if _e1:\\n        s += log(-z)\\n    else:\\n        if type(z) is float or z.imag == 0.0:\\n            s += math_log(abs(z))\\n        else:\\n            s += cmath.log(z)\\n    return s\\n\\ndef ei(z, _e1=False):\\n    typez = type(z)\\n    if typez not in (float, complex):\\n        try:\\n            z = float(z)\\n            typez = float\\n        except (TypeError, ValueError):\\n            z = complex(z)\\n            typez = complex\\n    if not z:\\n        return -INF\\n    absz = abs(z)\\n    if absz > EI_ASYMP_CONVERGENCE_RADIUS:\\n        return ei_asymp(z, _e1)\\n    elif absz <= 2.0 or (typez is float and z > 0.0):\\n        return ei_taylor(z, _e1)\\n    # Integrate, starting from whichever is smaller of a Taylor\\n    # series value or an asymptotic series value\\n    if typez is complex and z.real > 0.0:\\n        zref = z / absz\\n        ref = ei_taylor(zref, _e1)\\n    else:\\n        zref = EI_ASYMP_CONVERGENCE_RADIUS * z / absz\\n        ref = ei_asymp(zref, _e1)\\n    C = (zref-z)*0.5\\n    D = (zref+z)*0.5\\n    s = 0.0\\n    if type(z) is complex:\\n        _exp = cmath.exp\\n    else:\\n        _exp = math.exp\\n    for x,w in gauss42:\\n        t = C*x+D\\n        s += w*_exp(t)/t\\n    ref -= C*s\\n    return ref\\n\\ndef e1(z):\\n    # hack to get consistent signs if the imaginary part if 0\\n    # and signed\\n    typez = type(z)\\n    if type(z) not in (float, complex):\\n        try:\\n            z = float(z)\\n            typez = float\\n        except (TypeError, ValueError):\\n            z = complex(z)\\n            typez = complex\\n    if typez is complex and not z.imag:\\n        z = complex(z.real, 0.0)\\n    # end hack\\n    return -ei(-z, _e1=True)\\n\\n_zeta_int = [\\\\\\n-0.5,\\n0.0,\\n1.6449340668482264365,1.2020569031595942854,1.0823232337111381915,\\n1.0369277551433699263,1.0173430619844491397,1.0083492773819228268,\\n1.0040773561979443394,1.0020083928260822144,1.0009945751278180853,\\n1.0004941886041194646,1.0002460865533080483,1.0001227133475784891,\\n1.0000612481350587048,1.0000305882363070205,1.0000152822594086519,\\n1.0000076371976378998,1.0000038172932649998,1.0000019082127165539,\\n1.0000009539620338728,1.0000004769329867878,1.0000002384505027277,\\n1.0000001192199259653,1.0000000596081890513,1.0000000298035035147,\\n1.0000000149015548284]\\n\\n_zeta_P = [-3.50000000087575873, -0.701274355654678147,\\n-0.0672313458590012612, -0.00398731457954257841,\\n-0.000160948723019303141, -4.67633010038383371e-6,\\n-1.02078104417700585e-7, -1.68030037095896287e-9,\\n-1.85231868742346722e-11][::-1]\\n\\n_zeta_Q = [1.00000000000000000, -0.936552848762465319,\\n-0.0588835413263763741, -0.00441498861482948666,\\n-0.000143416758067432622, -5.10691659585090782e-6,\\n-9.58813053268913799e-8, -1.72963791443181972e-9,\\n-1.83527919681474132e-11][::-1]\\n\\n_zeta_1 = [3.03768838606128127e-10, -1.21924525236601262e-8,\\n2.01201845887608893e-7, -1.53917240683468381e-6,\\n-5.09890411005967954e-7, 0.000122464707271619326,\\n-0.000905721539353130232, -0.00239315326074843037,\\n0.084239750013159168, 0.418938517907442414, 0.500000001921884009]\\n\\n_zeta_0 = [-3.46092485016748794e-10, -6.42610089468292485e-9,\\n1.76409071536679773e-7, -1.47141263991560698e-6, -6.38880222546167613e-7,\\n0.000122641099800668209, -0.000905894913516772796, -0.00239303348507992713,\\n0.0842396947501199816, 0.418938533204660256, 0.500000000000000052]\\n\\ndef zeta(s):\\n    \\\"\\\"\\\"\\n    Riemann zeta function, real argument\\n    \\\"\\\"\\\"\\n    if not isinstance(s, (float, int)):\\n        try:\\n            s = float(s)\\n        except (ValueError, TypeError):\\n            try:\\n                s = complex(s)\\n                if not s.imag:\\n                    return complex(zeta(s.real))\\n            except (ValueError, TypeError):\\n                pass\\n            raise NotImplementedError\\n    if s == 1:\\n        raise ValueError(\\\"zeta(1) pole\\\")\\n    if s >= 27:\\n        return 1.0 + 2.0**(-s) + 3.0**(-s)\\n    n = int(s)\\n    if n == s:\\n        if n >= 0:\\n            return _zeta_int[n]\\n        if not (n % 2):\\n            return 0.0\\n    if s <= 0.0:\\n        return 2.**s*pi**(s-1)*_sinpi_real(0.5*s)*_gamma_real(1-s)*zeta(1-s)\\n    if s <= 2.0:\\n        if s <= 1.0:\\n            return _polyval(_zeta_0,s)/(s-1)\\n        return _polyval(_zeta_1,s)/(s-1)\\n    z = _polyval(_zeta_P,s) / _polyval(_zeta_Q,s)\\n    return 1.0 + 2.0**(-s) + 3.0**(-s) + 4.0**(-s)*z\\n\\n\\nimport operator\\n\\nfrom . import libmp\\n\\nfrom .libmp.backend import basestring\\n\\nfrom .libmp import (\\n    int_types, MPZ_ONE,\\n    prec_to_dps, dps_to_prec, repr_dps,\\n    round_floor, round_ceiling,\\n    fzero, finf, fninf, fnan,\\n    mpf_le, mpf_neg,\\n    from_int, from_float, from_str, from_rational,\\n    mpi_mid, mpi_delta, mpi_str,\\n    mpi_abs, mpi_pos, mpi_neg, mpi_add, mpi_sub,\\n    mpi_mul, mpi_div, mpi_pow_int, mpi_pow,\\n    mpi_from_str,\\n    mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow,\\n    mpci_abs, mpci_pow, mpci_exp, mpci_log,\\n    ComplexResult,\\n    mpf_hash, mpc_hash)\\nfrom .matrices.matrices import _matrix\\n\\nmpi_zero = (fzero, fzero)\\n\\nfrom .ctx_base import StandardBaseContext\\n\\nnew = object.__new__\\n\\ndef convert_mpf_(x, prec, rounding):\\n    if hasattr(x, \\\"_mpf_\\\"): return x._mpf_\\n    if isinstance(x, int_types): return from_int(x, prec, rounding)\\n    if isinstance(x, float): return from_float(x, prec, rounding)\\n    if isinstance(x, basestring): return from_str(x, prec, rounding)\\n    raise NotImplementedError\\n\\n\\nclass ivmpf(object):\\n    \\\"\\\"\\\"\\n    Interval arithmetic class. Precision is controlled by iv.prec.\\n    \\\"\\\"\\\"\\n\\n    def __new__(cls, x=0):\\n        return cls.ctx.convert(x)\\n\\n    def cast(self, cls, f_convert):\\n        a, b = self._mpi_\\n        if a == b:\\n            return cls(f_convert(a))\\n        raise ValueError\\n\\n    def __int__(self):\\n        return self.cast(int, libmp.to_int)\\n\\n    def __float__(self):\\n        return self.cast(float, libmp.to_float)\\n\\n    def __complex__(self):\\n        return self.cast(complex, libmp.to_float)\\n\\n    def __hash__(self):\\n        a, b = self._mpi_\\n        if a == b:\\n            return mpf_hash(a)\\n        else:\\n            return hash(self._mpi_)\\n\\n    @property\\n    def real(self): return self\\n\\n    @property\\n    def imag(self): return self.ctx.zero\\n\\n    def conjugate(self): return self\\n\\n    @property\\n    def a(self):\\n        a, b = self._mpi_\\n        return self.ctx.make_mpf((a, a))\\n\\n    @property\\n    def b(self):\\n        a, b = self._mpi_\\n        return self.ctx.make_mpf((b, b))\\n\\n    @property\\n    def mid(self):\\n        ctx = self.ctx\\n        v = mpi_mid(self._mpi_, ctx.prec)\\n        return ctx.make_mpf((v, v))\\n\\n    @property\\n    def delta(self):\\n        ctx = self.ctx\\n        v = mpi_delta(self._mpi_, ctx.prec)\\n        return ctx.make_mpf((v,v))\\n\\n    @property\\n    def _mpci_(self):\\n        return self._mpi_, mpi_zero\\n\\n    def _compare(*args):\\n        raise TypeError(\\\"no ordering relation is defined for intervals\\\")\\n\\n    __gt__ = _compare\\n    __le__ = _compare\\n    __gt__ = _compare\\n    __ge__ = _compare\\n\\n    def __contains__(self, t):\\n        t = self.ctx.mpf(t)\\n        return (self.a <= t.a) and (t.b <= self.b)\\n\\n    def __str__(self):\\n        return mpi_str(self._mpi_, self.ctx.prec)\\n\\n    def __repr__(self):\\n        if self.ctx.pretty:\\n            return str(self)\\n        a, b = self._mpi_\\n        n = repr_dps(self.ctx.prec)\\n        a = libmp.to_str(a, n)\\n        b = libmp.to_str(b, n)\\n        return \\\"mpi(%r, %r)\\\" % (a, b)\\n\\n    def _compare(s, t, cmpfun):\\n        if not hasattr(t, \\\"_mpi_\\\"):\\n            try:\\n                t = s.ctx.convert(t)\\n            except:\\n                return NotImplemented\\n        return cmpfun(s._mpi_, t._mpi_)\\n\\n    def __eq__(s, t): return s._compare(t, libmp.mpi_eq)\\n    def __ne__(s, t): return s._compare(t, libmp.mpi_ne)\\n    def __lt__(s, t): return s._compare(t, libmp.mpi_lt)\\n    def __le__(s, t): return s._compare(t, libmp.mpi_le)\\n    def __gt__(s, t): return s._compare(t, libmp.mpi_gt)\\n    def __ge__(s, t): return s._compare(t, libmp.mpi_ge)\\n\\n    def __abs__(self):\\n        return self.ctx.make_mpf(mpi_abs(self._mpi_, self.ctx.prec))\\n    def __pos__(self):\\n        return self.ctx.make_mpf(mpi_pos(self._mpi_, self.ctx.prec))\\n    def __neg__(self):\\n        return self.ctx.make_mpf(mpi_neg(self._mpi_, self.ctx.prec))\\n\\n    def ae(s, t, rel_eps=None, abs_eps=None):\\n        return s.ctx.almosteq(s, t, rel_eps, abs_eps)\\n\\nclass ivmpc(object):\\n\\n    def __new__(cls, re=0, im=0):\\n        re = cls.ctx.convert(re)\\n        im = cls.ctx.convert(im)\\n        y = new(cls)\\n        y._mpci_ = re._mpi_, im._mpi_\\n        return y\\n\\n    def __hash__(self):\\n        (a, b), (c,d) = self._mpci_\\n        if a == b and c == d:\\n            return mpc_hash((a, c))\\n        else:\\n            return hash(self._mpci_)\\n\\n    def __repr__(s):\\n        if s.ctx.pretty:\\n            return str(s)\\n        return \\\"iv.mpc(%s, %s)\\\" % (repr(s.real), repr(s.imag))\\n\\n    def __str__(s):\\n        return \\\"(%s + %s*j)\\\" % (str(s.real), str(s.imag))\\n\\n    @property\\n    def a(self):\\n        (a, b), (c,d) = self._mpci_\\n        return self.ctx.make_mpf((a, a))\\n\\n    @property\\n    def b(self):\\n        (a, b), (c,d) = self._mpci_\\n        return self.ctx.make_mpf((b, b))\\n\\n    @property\\n    def c(self):\\n        (a, b), (c,d) = self._mpci_\\n        return self.ctx.make_mpf((c, c))\\n\\n    @property\\n    def d(self):\\n        (a, b), (c,d) = self._mpci_\\n        return self.ctx.make_mpf((d, d))\\n\\n    @property\\n    def real(s):\\n        return s.ctx.make_mpf(s._mpci_[0])\\n\\n    @property\\n    def imag(s):\\n        return s.ctx.make_mpf(s._mpci_[1])\\n\\n    def conjugate(s):\\n        a, b = s._mpci_\\n        return s.ctx.make_mpc((a, mpf_neg(b)))\\n\\n    def overlap(s, t):\\n        t = s.ctx.convert(t)\\n        real_overlap = (s.a <= t.a <= s.b) or (s.a <= t.b <= s.b) or (t.a <= s.a <= t.b) or (t.a <= s.b <= t.b)\\n        imag_overlap = (s.c <= t.c <= s.d) or (s.c <= t.d <= s.d) or (t.c <= s.c <= t.d) or (t.c <= s.d <= t.d)\\n        return real_overlap and imag_overlap\\n\\n    def __contains__(s, t):\\n        t = s.ctx.convert(t)\\n        return t.real in s.real and t.imag in s.imag\\n\\n    def _compare(s, t, ne=False):\\n        if not isinstance(t, s.ctx._types):\\n            try:\\n                t = s.ctx.convert(t)\\n            except:\\n                return NotImplemented\\n        if hasattr(t, '_mpi_'):\\n            tval = t._mpi_, mpi_zero\\n        elif hasattr(t, '_mpci_'):\\n            tval = t._mpci_\\n        if ne:\\n            return s._mpci_ != tval\\n        return s._mpci_ == tval\\n\\n    def __eq__(s, t): return s._compare(t)\\n    def __ne__(s, t): return s._compare(t, True)\\n\\n    def __lt__(s, t): raise TypeError(\\\"complex intervals cannot be ordered\\\")\\n    __le__ = __gt__ = __ge__ = __lt__\\n\\n    def __neg__(s): return s.ctx.make_mpc(mpci_neg(s._mpci_, s.ctx.prec))\\n    def __pos__(s): return s.ctx.make_mpc(mpci_pos(s._mpci_, s.ctx.prec))\\n    def __abs__(s): return s.ctx.make_mpf(mpci_abs(s._mpci_, s.ctx.prec))\\n\\n    def ae(s, t, rel_eps=None, abs_eps=None):\\n        return s.ctx.almosteq(s, t, rel_eps, abs_eps)\\n\\ndef _binary_op(f_real, f_complex):\\n    def g_complex(ctx, sval, tval):\\n        return ctx.make_mpc(f_complex(sval, tval, ctx.prec))\\n    def g_real(ctx, sval, tval):\\n        try:\\n            return ctx.make_mpf(f_real(sval, tval, ctx.prec))\\n        except ComplexResult:\\n            sval = (sval, mpi_zero)\\n            tval = (tval, mpi_zero)\\n            return g_complex(ctx, sval, tval)\\n    def lop_real(s, t):\\n        if isinstance(t, _matrix): return NotImplemented\\n        ctx = s.ctx\\n        if not isinstance(t, ctx._types): t = ctx.convert(t)\\n        if hasattr(t, \\\"_mpi_\\\"): return g_real(ctx, s._mpi_, t._mpi_)\\n        if hasattr(t, \\\"_mpci_\\\"): return g_complex(ctx, (s._mpi_, mpi_zero), t._mpci_)\\n        return NotImplemented\\n    def rop_real(s, t):\\n        ctx = s.ctx\\n        if not isinstance(t, ctx._types): t = ctx.convert(t)\\n        if hasattr(t, \\\"_mpi_\\\"): return g_real(ctx, t._mpi_, s._mpi_)\\n        if hasattr(t, \\\"_mpci_\\\"): return g_complex(ctx, t._mpci_, (s._mpi_, mpi_zero))\\n        return NotImplemented\\n    def lop_complex(s, t):\\n        if isinstance(t, _matrix): return NotImplemented\\n        ctx = s.ctx\\n        if not isinstance(t, s.ctx._types):\\n            try:\\n                t = s.ctx.convert(t)\\n            except (ValueError, TypeError):\\n                return NotImplemented\\n        return g_complex(ctx, s._mpci_, t._mpci_)\\n    def rop_complex(s, t):\\n        ctx = s.ctx\\n        if not isinstance(t, s.ctx._types):\\n            t = s.ctx.convert(t)\\n        return g_complex(ctx, t._mpci_, s._mpci_)\\n    return lop_real, rop_real, lop_complex, rop_complex\\n\\nivmpf.__add__, ivmpf.__radd__, ivmpc.__add__, ivmpc.__radd__ = _binary_op(mpi_add, mpci_add)\\nivmpf.__sub__, ivmpf.__rsub__, ivmpc.__sub__, ivmpc.__rsub__ = _binary_op(mpi_sub, mpci_sub)\\nivmpf.__mul__, ivmpf.__rmul__, ivmpc.__mul__, ivmpc.__rmul__ = _binary_op(mpi_mul, mpci_mul)\\nivmpf.__div__, ivmpf.__rdiv__, ivmpc.__div__, ivmpc.__rdiv__ = _binary_op(mpi_div, mpci_div)\\nivmpf.__pow__, ivmpf.__rpow__, ivmpc.__pow__, ivmpc.__rpow__ = _binary_op(mpi_pow, mpci_pow)\\n\\nivmpf.__truediv__ = ivmpf.__div__; ivmpf.__rtruediv__ = ivmpf.__rdiv__\\nivmpc.__truediv__ = ivmpc.__div__; ivmpc.__rtruediv__ = ivmpc.__rdiv__\\n\\nclass ivmpf_constant(ivmpf):\\n    def __new__(cls, f):\\n        self = new(cls)\\n        self._f = f\\n        return self\\n    def _get_mpi_(self):\\n        prec = self.ctx._prec[0]\\n        a = self._f(prec, round_floor)\\n        b = self._f(prec, round_ceiling)\\n        return a, b\\n    _mpi_ = property(_get_mpi_)\\n\\nclass MPIntervalContext(StandardBaseContext):\\n\\n    def __init__(ctx):\\n        ctx.mpf = type('ivmpf', (ivmpf,), {})\\n        ctx.mpc = type('ivmpc', (ivmpc,), {})\\n        ctx._types = (ctx.mpf, ctx.mpc)\\n        ctx._constant = type('ivmpf_constant', (ivmpf_constant,), {})\\n        ctx._prec = [53]\\n        ctx._set_prec(53)\\n        ctx._constant._ctxdata = ctx.mpf._ctxdata = ctx.mpc._ctxdata = [ctx.mpf, new, ctx._prec]\\n        ctx._constant.ctx = ctx.mpf.ctx = ctx.mpc.ctx = ctx\\n        ctx.pretty = False\\n        StandardBaseContext.__init__(ctx)\\n        ctx._init_builtins()\\n\\n    def _mpi(ctx, a, b=None):\\n        if b is None:\\n            return ctx.mpf(a)\\n        return ctx.mpf((a,b))\\n\\n    def _init_builtins(ctx):\\n        ctx.one = ctx.mpf(1)\\n        ctx.zero = ctx.mpf(0)\\n        ctx.inf = ctx.mpf('inf')\\n        ctx.ninf = -ctx.inf\\n        ctx.nan = ctx.mpf('nan')\\n        ctx.j = ctx.mpc(0,1)\\n        ctx.exp = ctx._wrap_mpi_function(libmp.mpi_exp, libmp.mpci_exp)\\n        ctx.sqrt = ctx._wrap_mpi_function(libmp.mpi_sqrt)\\n        ctx.ln = ctx._wrap_mpi_function(libmp.mpi_log, libmp.mpci_log)\\n        ctx.cos = ctx._wrap_mpi_function(libmp.mpi_cos, libmp.mpci_cos)\\n        ctx.sin = ctx._wrap_mpi_function(libmp.mpi_sin, libmp.mpci_sin)\\n        ctx.tan = ctx._wrap_mpi_function(libmp.mpi_tan)\\n        ctx.gamma = ctx._wrap_mpi_function(libmp.mpi_gamma, libmp.mpci_gamma)\\n        ctx.loggamma = ctx._wrap_mpi_function(libmp.mpi_loggamma, libmp.mpci_loggamma)\\n        ctx.rgamma = ctx._wrap_mpi_function(libmp.mpi_rgamma, libmp.mpci_rgamma)\\n        ctx.factorial = ctx._wrap_mpi_function(libmp.mpi_factorial, libmp.mpci_factorial)\\n        ctx.fac = ctx.factorial\\n\\n        ctx.eps = ctx._constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1))\\n        ctx.pi = ctx._constant(libmp.mpf_pi)\\n        ctx.e = ctx._constant(libmp.mpf_e)\\n        ctx.ln2 = ctx._constant(libmp.mpf_ln2)\\n        ctx.ln10 = ctx._constant(libmp.mpf_ln10)\\n        ctx.phi = ctx._constant(libmp.mpf_phi)\\n        ctx.euler = ctx._constant(libmp.mpf_euler)\\n        ctx.catalan = ctx._constant(libmp.mpf_catalan)\\n        ctx.glaisher = ctx._constant(libmp.mpf_glaisher)\\n        ctx.khinchin = ctx._constant(libmp.mpf_khinchin)\\n        ctx.twinprime = ctx._constant(libmp.mpf_twinprime)\\n\\n    def _wrap_mpi_function(ctx, f_real, f_complex=None):\\n        def g(x, **kwargs):\\n            if kwargs:\\n                prec = kwargs.get('prec', ctx._prec[0])\\n            else:\\n                prec = ctx._prec[0]\\n            x = ctx.convert(x)\\n            if hasattr(x, \\\"_mpi_\\\"):\\n                return ctx.make_mpf(f_real(x._mpi_, prec))\\n            if hasattr(x, \\\"_mpci_\\\"):\\n                return ctx.make_mpc(f_complex(x._mpci_, prec))\\n            raise ValueError\\n        return g\\n\\n    @classmethod\\n    def _wrap_specfun(cls, name, f, wrap):\\n        if wrap:\\n            def f_wrapped(ctx, *args, **kwargs):\\n                convert = ctx.convert\\n                args = [convert(a) for a in args]\\n                prec = ctx.prec\\n                try:\\n                    ctx.prec += 10\\n                    retval = f(ctx, *args, **kwargs)\\n                finally:\\n                    ctx.prec = prec\\n                return +retval\\n        else:\\n            f_wrapped = f\\n        setattr(cls, name, f_wrapped)\\n\\n    def _set_prec(ctx, n):\\n        ctx._prec[0] = max(1, int(n))\\n        ctx._dps = prec_to_dps(n)\\n\\n    def _set_dps(ctx, n):\\n        ctx._prec[0] = dps_to_prec(n)\\n        ctx._dps = max(1, int(n))\\n\\n    prec = property(lambda ctx: ctx._prec[0], _set_prec)\\n    dps = property(lambda ctx: ctx._dps, _set_dps)\\n\\n    def make_mpf(ctx, v):\\n        a = new(ctx.mpf)\\n        a._mpi_ = v\\n        return a\\n\\n    def make_mpc(ctx, v):\\n        a = new(ctx.mpc)\\n        a._mpci_ = v\\n        return a\\n\\n    def _mpq(ctx, pq):\\n        p, q = pq\\n        a = libmp.from_rational(p, q, ctx.prec, round_floor)\\n        b = libmp.from_rational(p, q, ctx.prec, round_ceiling)\\n        return ctx.make_mpf((a, b))\\n\\n    def convert(ctx, x):\\n        if isinstance(x, (ctx.mpf, ctx.mpc)):\\n            return x\\n        if isinstance(x, ctx._constant):\\n            return +x\\n        if isinstance(x, complex) or hasattr(x, \\\"_mpc_\\\"):\\n            re = ctx.convert(x.real)\\n            im = ctx.convert(x.imag)\\n            return ctx.mpc(re,im)\\n        if isinstance(x, basestring):\\n            v = mpi_from_str(x, ctx.prec)\\n            return ctx.make_mpf(v)\\n        if hasattr(x, \\\"_mpi_\\\"):\\n            a, b = x._mpi_\\n        else:\\n            try:\\n                a, b = x\\n            except (TypeError, ValueError):\\n                a = b = x\\n            if hasattr(a, \\\"_mpi_\\\"):\\n                a = a._mpi_[0]\\n            else:\\n                a = convert_mpf_(a, ctx.prec, round_floor)\\n            if hasattr(b, \\\"_mpi_\\\"):\\n                b = b._mpi_[1]\\n            else:\\n                b = convert_mpf_(b, ctx.prec, round_ceiling)\\n        if a == fnan or b == fnan:\\n            a = fninf\\n            b = finf\\n        assert mpf_le(a, b), \\\"endpoints must be properly ordered\\\"\\n        return ctx.make_mpf((a, b))\\n\\n    def nstr(ctx, x, n=5, **kwargs):\\n        x = ctx.convert(x)\\n        if hasattr(x, \\\"_mpi_\\\"):\\n            return libmp.mpi_to_str(x._mpi_, n, **kwargs)\\n        if hasattr(x, \\\"_mpci_\\\"):\\n            re = libmp.mpi_to_str(x._mpci_[0], n, **kwargs)\\n            im = libmp.mpi_to_str(x._mpci_[1], n, **kwargs)\\n            return \\\"(%s + %s*j)\\\" % (re, im)\\n\\n    def mag(ctx, x):\\n        x = ctx.convert(x)\\n        if isinstance(x, ctx.mpc):\\n            return max(ctx.mag(x.real), ctx.mag(x.imag)) + 1\\n        a, b = libmp.mpi_abs(x._mpi_)\\n        sign, man, exp, bc = b\\n        if man:\\n            return exp+bc\\n        if b == fzero:\\n            return ctx.ninf\\n        if b == fnan:\\n            return ctx.nan\\n        return ctx.inf\\n\\n    def isnan(ctx, x):\\n        return False\\n\\n    def isinf(ctx, x):\\n        return x == ctx.inf\\n\\n    def isint(ctx, x):\\n        x = ctx.convert(x)\\n        a, b = x._mpi_\\n        if a == b:\\n            sign, man, exp, bc = a\\n            if man:\\n                return exp >= 0\\n            return a == fzero\\n        return None\\n\\n    def ldexp(ctx, x, n):\\n        a, b = ctx.convert(x)._mpi_\\n        a = libmp.mpf_shift(a, n)\\n        b = libmp.mpf_shift(b, n)\\n        return ctx.make_mpf((a,b))\\n\\n    def absmin(ctx, x):\\n        return abs(ctx.convert(x)).a\\n\\n    def absmax(ctx, x):\\n        return abs(ctx.convert(x)).b\\n\\n    def atan2(ctx, y, x):\\n        y = ctx.convert(y)._mpi_\\n        x = ctx.convert(x)._mpi_\\n        return ctx.make_mpf(libmp.mpi_atan2(y,x,ctx.prec))\\n\\n    def _convert_param(ctx, x):\\n        if isinstance(x, libmp.int_types):\\n            return x, 'Z'\\n        if isinstance(x, tuple):\\n            p, q = x\\n            return (ctx.mpf(p) / ctx.mpf(q), 'R')\\n        x = ctx.convert(x)\\n        if isinstance(x, ctx.mpf):\\n            return x, 'R'\\n        if isinstance(x, ctx.mpc):\\n            return x, 'C'\\n        raise ValueError\\n\\n    def _is_real_type(ctx, z):\\n        return isinstance(z, ctx.mpf) or isinstance(z, int_types)\\n\\n    def _is_complex_type(ctx, z):\\n        return isinstance(z, ctx.mpc)\\n\\n    def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):\\n        coeffs = list(coeffs)\\n        num = range(p)\\n        den = range(p,p+q)\\n        #tol = ctx.eps\\n        s = t = ctx.one\\n        k = 0\\n        while 1:\\n            for i in num: t *= (coeffs[i]+k)\\n            for i in den: t /= (coeffs[i]+k)\\n            k += 1; t /= k; t *= z; s += t\\n            if t == 0:\\n                return s\\n            #if abs(t) < tol:\\n            #    return s\\n            if k > maxterms:\\n                raise ctx.NoConvergence\\n\\n\\n# Register with \\\"numbers\\\" ABC\\n#     We do not subclass, hence we do not use the @abstractmethod checks. While\\n#     this is less invasive it may turn out that we do not actually support\\n#     parts of the expected interfaces.  See\\n#     http://docs.python.org/2/library/numbers.html for list of abstract\\n#     methods.\\ntry:\\n    import numbers\\n    numbers.Complex.register(ivmpc)\\n    numbers.Real.register(ivmpf)\\nexcept ImportError:\\n    pass\\n\\n\\nfrom .ctx_base import StandardBaseContext\\n\\nimport math\\nimport cmath\\nfrom . import math2\\n\\nfrom . import function_docs\\n\\nfrom .libmp import mpf_bernoulli, to_float, int_types\\nfrom . import libmp\\n\\nclass FPContext(StandardBaseContext):\\n    \\\"\\\"\\\"\\n    Context for fast low-precision arithmetic (53-bit precision, giving at most\\n    about 15-digit accuracy), using Python's builtin float and complex.\\n    \\\"\\\"\\\"\\n\\n    def __init__(ctx):\\n        StandardBaseContext.__init__(ctx)\\n\\n        # Override SpecialFunctions implementation\\n        ctx.loggamma = math2.loggamma\\n        ctx._bernoulli_cache = {}\\n        ctx.pretty = False\\n\\n        ctx._init_aliases()\\n\\n    _mpq = lambda cls, x: float(x[0])/x[1]\\n\\n    NoConvergence = libmp.NoConvergence\\n\\n    def _get_prec(ctx): return 53\\n    def _set_prec(ctx, p): return\\n    def _get_dps(ctx): return 15\\n    def _set_dps(ctx, p): return\\n\\n    _fixed_precision = True\\n\\n    prec = property(_get_prec, _set_prec)\\n    dps = property(_get_dps, _set_dps)\\n\\n    zero = 0.0\\n    one = 1.0\\n    eps = math2.EPS\\n    inf = math2.INF\\n    ninf = math2.NINF\\n    nan = math2.NAN\\n    j = 1j\\n\\n    # Called by SpecialFunctions.__init__()\\n    @classmethod\\n    def _wrap_specfun(cls, name, f, wrap):\\n        if wrap:\\n            def f_wrapped(ctx, *args, **kwargs):\\n                convert = ctx.convert\\n                args = [convert(a) for a in args]\\n                return f(ctx, *args, **kwargs)\\n        else:\\n            f_wrapped = f\\n        f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__)\\n        setattr(cls, name, f_wrapped)\\n\\n    def bernoulli(ctx, n):\\n        cache = ctx._bernoulli_cache\\n        if n in cache:\\n            return cache[n]\\n        cache[n] = to_float(mpf_bernoulli(n, 53, 'n'), strict=True)\\n        return cache[n]\\n\\n    pi = math2.pi\\n    e = math2.e\\n    euler = math2.euler\\n    sqrt2 = 1.4142135623730950488\\n    sqrt5 = 2.2360679774997896964\\n    phi = 1.6180339887498948482\\n    ln2 = 0.69314718055994530942\\n    ln10 = 2.302585092994045684\\n    euler = 0.57721566490153286061\\n    catalan = 0.91596559417721901505\\n    khinchin = 2.6854520010653064453\\n    apery = 1.2020569031595942854\\n    glaisher = 1.2824271291006226369\\n\\n    absmin = absmax = abs\\n\\n    def is_special(ctx, x):\\n        return x - x != 0.0\\n\\n    def isnan(ctx, x):\\n        return x != x\\n\\n    def isinf(ctx, x):\\n        return abs(x) == math2.INF\\n\\n    def isnormal(ctx, x):\\n        if x:\\n            return x - x == 0.0\\n        return False\\n\\n    def isnpint(ctx, x):\\n        if type(x) is complex:\\n            if x.imag:\\n                return False\\n            x = x.real\\n        return x <= 0.0 and round(x) == x\\n\\n    mpf = float\\n    mpc = complex\\n\\n    def convert(ctx, x):\\n        try:\\n            return float(x)\\n        except:\\n            return complex(x)\\n\\n    power = staticmethod(math2.pow)\\n    sqrt = staticmethod(math2.sqrt)\\n    exp = staticmethod(math2.exp)\\n    ln = log = staticmethod(math2.log)\\n    cos = staticmethod(math2.cos)\\n    sin = staticmethod(math2.sin)\\n    tan = staticmethod(math2.tan)\\n    cos_sin = staticmethod(math2.cos_sin)\\n    acos = staticmethod(math2.acos)\\n    asin = staticmethod(math2.asin)\\n    atan = staticmethod(math2.atan)\\n    cosh = staticmethod(math2.cosh)\\n    sinh = staticmethod(math2.sinh)\\n    tanh = staticmethod(math2.tanh)\\n    gamma = staticmethod(math2.gamma)\\n    rgamma = staticmethod(math2.rgamma)\\n    fac = factorial = staticmethod(math2.factorial)\\n    floor = staticmethod(math2.floor)\\n    ceil = staticmethod(math2.ceil)\\n    cospi = staticmethod(math2.cospi)\\n    sinpi = staticmethod(math2.sinpi)\\n    cbrt = staticmethod(math2.cbrt)\\n    _nthroot = staticmethod(math2.nthroot)\\n    _ei = staticmethod(math2.ei)\\n    _e1 = staticmethod(math2.e1)\\n    _zeta = _zeta_int = staticmethod(math2.zeta)\\n\\n    # XXX: math2\\n    def arg(ctx, z):\\n        z = complex(z)\\n        return math.atan2(z.imag, z.real)\\n\\n    def expj(ctx, x):\\n        return ctx.exp(ctx.j*x)\\n\\n    def expjpi(ctx, x):\\n        return ctx.exp(ctx.j*ctx.pi*x)\\n\\n    ldexp = math.ldexp\\n    frexp = math.frexp\\n\\n    def mag(ctx, z):\\n        if z:\\n            return ctx.frexp(abs(z))[1]\\n        return ctx.ninf\\n\\n    def isint(ctx, z):\\n        if hasattr(z, \\\"imag\\\"):   # float/int don't have .real/.imag in py2.5\\n            if z.imag:\\n                return False\\n            z = z.real\\n        try:\\n            return z == int(z)\\n        except:\\n            return False\\n\\n    def nint_distance(ctx, z):\\n        if hasattr(z, \\\"imag\\\"):   # float/int don't have .real/.imag in py2.5\\n            n = round(z.real)\\n        else:\\n            n = round(z)\\n        if n == z:\\n            return n, ctx.ninf\\n        return n, ctx.mag(abs(z-n))\\n\\n    def _convert_param(ctx, z):\\n        if type(z) is tuple:\\n            p, q = z\\n            return ctx.mpf(p) / q, 'R'\\n        if hasattr(z, \\\"imag\\\"):    # float/int don't have .real/.imag in py2.5\\n            intz = int(z.real)\\n        else:\\n            intz = int(z)\\n        if z == intz:\\n            return intz, 'Z'\\n        return z, 'R'\\n\\n    def _is_real_type(ctx, z):\\n        return isinstance(z, float) or isinstance(z, int_types)\\n\\n    def _is_complex_type(ctx, z):\\n        return isinstance(z, complex)\\n\\n    def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):\\n        coeffs = list(coeffs)\\n        num = range(p)\\n        den = range(p,p+q)\\n        tol = ctx.eps\\n        s = t = 1.0\\n        k = 0\\n        while 1:\\n            for i in num: t *= (coeffs[i]+k)\\n            for i in den: t /= (coeffs[i]+k)\\n            k += 1; t /= k; t *= z; s += t\\n            if abs(t) < tol:\\n                return s\\n            if k > maxterms:\\n                raise ctx.NoConvergence\\n\\n    def atan2(ctx, x, y):\\n        return math.atan2(x, y)\\n\\n    def psi(ctx, m, z):\\n        m = int(m)\\n        if m == 0:\\n            return ctx.digamma(z)\\n        return (-1)**(m+1) * ctx.fac(m) * ctx.zeta(m+1, z)\\n\\n    digamma = staticmethod(math2.digamma)\\n\\n    def harmonic(ctx, x):\\n        x = ctx.convert(x)\\n        if x == 0 or x == 1:\\n            return x\\n        return ctx.digamma(x+1) + ctx.euler\\n\\n    nstr = str\\n\\n    def to_fixed(ctx, x, prec):\\n        return int(math.ldexp(x, prec))\\n\\n    def rand(ctx):\\n        import random\\n        return random.random()\\n\\n    _erf = staticmethod(math2.erf)\\n    _erfc = staticmethod(math2.erfc)\\n\\n    def sum_accurately(ctx, terms, check_step=1):\\n        s = ctx.zero\\n        k = 0\\n        for term in terms():\\n            s += term\\n            if (not k % check_step) and term:\\n                if abs(term) <= 1e-18*abs(s):\\n                    break\\n            k += 1\\n        return s\\n\\n\\nimport operator\\nimport sys\\nfrom .libmp import int_types, mpf_hash, bitcount, from_man_exp, HASH_MODULUS\\n\\nnew = object.__new__\\n\\ndef create_reduced(p, q, _cache={}):\\n    key = p, q\\n    if key in _cache:\\n        return _cache[key]\\n    x, y = p, q\\n    while y:\\n        x, y = y, x % y\\n    if x != 1:\\n        p //= x\\n        q //= x\\n    v = new(mpq)\\n    v._mpq_ = p, q\\n    # Speedup integers, half-integers and other small fractions\\n    if q <= 4 and abs(key[0]) < 100:\\n        _cache[key] = v\\n    return v\\n\\nclass mpq(object):\\n    \\\"\\\"\\\"\\n    Exact rational type, currently only intended for internal use.\\n    \\\"\\\"\\\"\\n\\n    __slots__ = [\\\"_mpq_\\\"]\\n\\n    def __new__(cls, p, q=1):\\n        if type(p) is tuple:\\n            p, q = p\\n        elif hasattr(p, '_mpq_'):\\n            p, q = p._mpq_\\n        return create_reduced(p, q)\\n\\n    def __repr__(s):\\n        return \\\"mpq(%s,%s)\\\" % s._mpq_\\n\\n    def __str__(s):\\n        return \\\"(%s/%s)\\\" % s._mpq_\\n\\n    def __int__(s):\\n        a, b = s._mpq_\\n        return a // b\\n\\n    def __nonzero__(s):\\n        return bool(s._mpq_[0])\\n\\n    __bool__ = __nonzero__\\n\\n    def __hash__(s):\\n        a, b = s._mpq_\\n        if sys.version_info >= (3, 2):\\n            inverse = pow(b, HASH_MODULUS-2, HASH_MODULUS)\\n            if not inverse:\\n                h = sys.hash_info.inf\\n            else:\\n                h = (abs(a) * inverse) % HASH_MODULUS\\n            if a < 0: h = -h\\n            if h == -1: h = -2\\n            return h\\n        else:\\n            if b == 1:\\n                return hash(a)\\n            # Power of two: mpf compatible hash\\n            if not (b & (b-1)):\\n                return mpf_hash(from_man_exp(a, 1-bitcount(b)))\\n            return hash((a,b))\\n\\n    def __eq__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            return s._mpq_ == t._mpq_\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            if b != 1:\\n                return False\\n            return a == t\\n        return NotImplemented\\n\\n    def __ne__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            return s._mpq_ != t._mpq_\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            if b != 1:\\n                return True\\n            return a != t\\n        return NotImplemented\\n\\n    def _cmp(s, t, op):\\n        ttype = type(t)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            return op(a, t*b)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return op(a*d, b*c)\\n        return NotImplementedError\\n\\n    def __lt__(s, t): return s._cmp(t, operator.lt)\\n    def __le__(s, t): return s._cmp(t, operator.le)\\n    def __gt__(s, t): return s._cmp(t, operator.gt)\\n    def __ge__(s, t): return s._cmp(t, operator.ge)\\n\\n    def __abs__(s):\\n        a, b = s._mpq_\\n        if a >= 0:\\n            return s\\n        v = new(mpq)\\n        v._mpq_ = -a, b\\n        return v\\n\\n    def __neg__(s):\\n        a, b = s._mpq_\\n        v = new(mpq)\\n        v._mpq_ = -a, b\\n        return v\\n\\n    def __pos__(s):\\n        return s\\n\\n    def __add__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(a*d+b*c, b*d)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            v = new(mpq)\\n            v._mpq_ = a+b*t, b\\n            return v\\n        return NotImplemented\\n\\n    __radd__ = __add__\\n\\n    def __sub__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(a*d-b*c, b*d)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            v = new(mpq)\\n            v._mpq_ = a-b*t, b\\n            return v\\n        return NotImplemented\\n\\n    def __rsub__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(b*c-a*d, b*d)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            v = new(mpq)\\n            v._mpq_ = b*t-a, b\\n            return v\\n        return NotImplemented\\n\\n    def __mul__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(a*c, b*d)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            return create_reduced(a*t, b)\\n        return NotImplemented\\n\\n    __rmul__ = __mul__\\n\\n    def __div__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(a*d, b*c)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            return create_reduced(a, b*t)\\n        return NotImplemented\\n\\n    def __rdiv__(s, t):\\n        ttype = type(t)\\n        if ttype is mpq:\\n            a, b = s._mpq_\\n            c, d = t._mpq_\\n            return create_reduced(b*c, a*d)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            return create_reduced(b*t, a)\\n        return NotImplemented\\n\\n    def __pow__(s, t):\\n        ttype = type(t)\\n        if ttype in int_types:\\n            a, b = s._mpq_\\n            if t:\\n                if t < 0:\\n                    a, b, t = b, a, -t\\n                v = new(mpq)\\n                v._mpq_ = a**t, b**t\\n                return v\\n            raise ZeroDivisionError\\n        return NotImplemented\\n\\n\\nmpq_1 = mpq((1,1))\\nmpq_0 = mpq((0,1))\\nmpq_1_2 = mpq((1,2))\\nmpq_3_2 = mpq((3,2))\\nmpq_1_4 = mpq((1,4))\\nmpq_1_16 = mpq((1,16))\\nmpq_3_16 = mpq((3,16))\\nmpq_5_2 = mpq((5,2))\\nmpq_3_4 = mpq((3,4))\\nmpq_7_4 = mpq((7,4))\\nmpq_5_4 = mpq((5,4))\\n\\n\\n# Register with \\\"numbers\\\" ABC\\n#     We do not subclass, hence we do not use the @abstractmethod checks. While\\n#     this is less invasive it may turn out that we do not actually support\\n#     parts of the expected interfaces.  See\\n#     http://docs.python.org/2/library/numbers.html for list of abstract\\n#     methods.\\ntry:\\n    import numbers\\n    numbers.Rational.register(mpq)\\nexcept ImportError:\\n    pass\\n\\n\\n\\\"\\\"\\\"\\nPlotting (requires matplotlib)\\n\\\"\\\"\\\"\\n\\nfrom colorsys import hsv_to_rgb, hls_to_rgb\\nfrom .libmp import NoConvergence\\nfrom .libmp.backend import xrange\\n\\nclass VisualizationMethods(object):\\n    plot_ignore = (ValueError, ArithmeticError, ZeroDivisionError, NoConvergence)\\n\\ndef plot(ctx, f, xlim=[-5,5], ylim=None, points=200, file=None, dpi=None,\\n    singularities=[], axes=None):\\n    r\\\"\\\"\\\"\\n    Shows a simple 2D plot of a function `f(x)` or list of functions\\n    `[f_0(x), f_1(x), \\\\ldots, f_n(x)]` over a given interval\\n    specified by *xlim*. Some examples::\\n\\n        plot(lambda x: exp(x)*li(x), [1, 4])\\n        plot([cos, sin], [-4, 4])\\n        plot([fresnels, fresnelc], [-4, 4])\\n        plot([sqrt, cbrt], [-4, 4])\\n        plot(lambda t: zeta(0.5+t*j), [-20, 20])\\n        plot([floor, ceil, abs, sign], [-5, 5])\\n\\n    Points where the function raises a numerical exception or\\n    returns an infinite value are removed from the graph.\\n    Singularities can also be excluded explicitly\\n    as follows (useful for removing erroneous vertical lines)::\\n\\n        plot(cot, ylim=[-5, 5])   # bad\\n        plot(cot, ylim=[-5, 5], singularities=[-pi, 0, pi])  # good\\n\\n    For parts where the function assumes complex values, the\\n    real part is plotted with dashes and the imaginary part\\n    is plotted with dots.\\n\\n    .. note :: This function requires matplotlib (pylab).\\n    \\\"\\\"\\\"\\n    if file:\\n        axes = None\\n    fig = None\\n    if not axes:\\n        import pylab\\n        fig = pylab.figure()\\n        axes = fig.add_subplot(111)\\n    if not isinstance(f, (tuple, list)):\\n        f = [f]\\n    a, b = xlim\\n    colors = ['b', 'r', 'g', 'm', 'k']\\n    for n, func in enumerate(f):\\n        x = ctx.arange(a, b, (b-a)/float(points))\\n        segments = []\\n        segment = []\\n        in_complex = False\\n        for i in xrange(len(x)):\\n            try:\\n                if i != 0:\\n                    for sing in singularities:\\n                        if x[i-1] <= sing and x[i] >= sing:\\n                            raise ValueError\\n                v = func(x[i])\\n                if ctx.isnan(v) or abs(v) > 1e300:\\n                    raise ValueError\\n                if hasattr(v, \\\"imag\\\") and v.imag:\\n                    re = float(v.real)\\n                    im = float(v.imag)\\n                    if not in_complex:\\n                        in_complex = True\\n                        segments.append(segment)\\n                        segment = []\\n                    segment.append((float(x[i]), re, im))\\n                else:\\n                    if in_complex:\\n                        in_complex = False\\n                        segments.append(segment)\\n                        segment = []\\n                    if hasattr(v, \\\"real\\\"):\\n                        v = v.real\\n                    segment.append((float(x[i]), v))\\n            except ctx.plot_ignore:\\n                if segment:\\n                    segments.append(segment)\\n                segment = []\\n        if segment:\\n            segments.append(segment)\\n        for segment in segments:\\n            x = [s[0] for s in segment]\\n            y = [s[1] for s in segment]\\n            if not x:\\n                continue\\n            c = colors[n % len(colors)]\\n            if len(segment[0]) == 3:\\n                z = [s[2] for s in segment]\\n                axes.plot(x, y, '--'+c, linewidth=3)\\n                axes.plot(x, z, ':'+c, linewidth=3)\\n            else:\\n                axes.plot(x, y, c, linewidth=3)\\n    axes.set_xlim([float(_) for _ in xlim])\\n    if ylim:\\n        axes.set_ylim([float(_) for _ in ylim])\\n    axes.set_xlabel('x')\\n    axes.set_ylabel('f(x)')\\n    axes.grid(True)\\n    if fig:\\n        if file:\\n            pylab.savefig(file, dpi=dpi)\\n        else:\\n            pylab.show()\\n\\ndef default_color_function(ctx, z):\\n    if ctx.isinf(z):\\n        return (1.0, 1.0, 1.0)\\n    if ctx.isnan(z):\\n        return (0.5, 0.5, 0.5)\\n    pi = 3.1415926535898\\n    a = (float(ctx.arg(z)) + ctx.pi) / (2*ctx.pi)\\n    a = (a + 0.5) % 1.0\\n    b = 1.0 - float(1/(1.0+abs(z)**0.3))\\n    return hls_to_rgb(a, b, 0.8)\\n\\nblue_orange_colors = [\\n  (-1.0,  (0.0, 0.0, 0.0)),\\n  (-0.95, (0.1, 0.2, 0.5)),   # dark blue\\n  (-0.5,  (0.0, 0.5, 1.0)),   # blueish\\n  (-0.05, (0.4, 0.8, 0.8)),   # cyanish\\n  ( 0.0,  (1.0, 1.0, 1.0)),\\n  ( 0.05, (1.0, 0.9, 0.3)),   # yellowish\\n  ( 0.5,  (0.9, 0.5, 0.0)),   # orangeish\\n  ( 0.95, (0.7, 0.1, 0.0)),   # redish\\n  ( 1.0,  (0.0, 0.0, 0.0)),\\n  ( 2.0,  (0.0, 0.0, 0.0)),\\n]\\n\\ndef phase_color_function(ctx, z):\\n    if ctx.isinf(z):\\n        return (1.0, 1.0, 1.0)\\n    if ctx.isnan(z):\\n        return (0.5, 0.5, 0.5)\\n    pi = 3.1415926535898\\n    w = float(ctx.arg(z)) / pi\\n    w = max(min(w, 1.0), -1.0)\\n    for i in range(1,len(blue_orange_colors)):\\n        if blue_orange_colors[i][0] > w:\\n            a, (ra, ga, ba) = blue_orange_colors[i-1]\\n            b, (rb, gb, bb) = blue_orange_colors[i]\\n            s = (w-a) / (b-a)\\n            return ra+(rb-ra)*s, ga+(gb-ga)*s, ba+(bb-ba)*s\\n\\ndef cplot(ctx, f, re=[-5,5], im=[-5,5], points=2000, color=None,\\n    verbose=False, file=None, dpi=None, axes=None):\\n    \\\"\\\"\\\"\\n    Plots the given complex-valued function *f* over a rectangular part\\n    of the complex plane specified by the pairs of intervals *re* and *im*.\\n    For example::\\n\\n        cplot(lambda z: z, [-2, 2], [-10, 10])\\n        cplot(exp)\\n        cplot(zeta, [0, 1], [0, 50])\\n\\n    By default, the complex argument (phase) is shown as color (hue) and\\n    the magnitude is show as brightness. You can also supply a\\n    custom color function (*color*). This function should take a\\n    complex number as input and return an RGB 3-tuple containing\\n    floats in the range 0.0-1.0.\\n\\n    Alternatively, you can select a builtin color function by passing\\n    a string as *color*:\\n\\n      * \\\"default\\\" - default color scheme\\n      * \\\"phase\\\" - a color scheme that only renders the phase of the function,\\n         with white for positive reals, black for negative reals, gold in the\\n         upper half plane, and blue in the lower half plane.\\n\\n    To obtain a sharp image, the number of points may need to be\\n    increased to 100,000 or thereabout. Since evaluating the\\n    function that many times is likely to be slow, the 'verbose'\\n    option is useful to display progress.\\n\\n    .. note :: This function requires matplotlib (pylab).\\n    \\\"\\\"\\\"\\n    if color is None or color == \\\"default\\\":\\n        color = ctx.default_color_function\\n    if color == \\\"phase\\\":\\n        color = ctx.phase_color_function\\n    import pylab\\n    if file:\\n        axes = None\\n    fig = None\\n    if not axes:\\n        fig = pylab.figure()\\n        axes = fig.add_subplot(111)\\n    rea, reb = re\\n    ima, imb = im\\n    dre = reb - rea\\n    dim = imb - ima\\n    M = int(ctx.sqrt(points*dre/dim)+1)\\n    N = int(ctx.sqrt(points*dim/dre)+1)\\n    x = pylab.linspace(rea, reb, M)\\n    y = pylab.linspace(ima, imb, N)\\n    # Note: we have to be careful to get the right rotation.\\n    # Test with these plots:\\n    #   cplot(lambda z: z if z.real < 0 else 0)\\n    #   cplot(lambda z: z if z.imag < 0 else 0)\\n    w = pylab.zeros((N, M, 3))\\n    for n in xrange(N):\\n        for m in xrange(M):\\n            z = ctx.mpc(x[m], y[n])\\n            try:\\n                v = color(f(z))\\n            except ctx.plot_ignore:\\n                v = (0.5, 0.5, 0.5)\\n            w[n,m] = v\\n        if verbose:\\n            print(str(n) + ' of ' + str(N))\\n    rea, reb, ima, imb = [float(_) for _ in [rea, reb, ima, imb]]\\n    axes.imshow(w, extent=(rea, reb, ima, imb), origin='lower')\\n    axes.set_xlabel('Re(z)')\\n    axes.set_ylabel('Im(z)')\\n    if fig:\\n        if file:\\n            pylab.savefig(file, dpi=dpi)\\n        else:\\n            pylab.show()\\n\\ndef splot(ctx, f, u=[-5,5], v=[-5,5], points=100, keep_aspect=True, \\\\\\n          wireframe=False, file=None, dpi=None, axes=None):\\n    \\\"\\\"\\\"\\n    Plots the surface defined by `f`.\\n\\n    If `f` returns a single component, then this plots the surface\\n    defined by `z = f(x,y)` over the rectangular domain with\\n    `x = u` and `y = v`.\\n\\n    If `f` returns three components, then this plots the parametric\\n    surface `x, y, z = f(u,v)` over the pairs of intervals `u` and `v`.\\n\\n    For example, to plot a simple function::\\n\\n        >>> from mpmath import *\\n        >>> f = lambda x, y: sin(x+y)*cos(y)\\n        >>> splot(f, [-pi,pi], [-pi,pi])    # doctest: +SKIP\\n\\n    Plotting a donut::\\n\\n        >>> r, R = 1, 2.5\\n        >>> f = lambda u, v: [r*cos(u), (R+r*sin(u))*cos(v), (R+r*sin(u))*sin(v)]\\n        >>> splot(f, [0, 2*pi], [0, 2*pi])    # doctest: +SKIP\\n\\n    .. note :: This function requires matplotlib (pylab) 0.98.5.3 or higher.\\n    \\\"\\\"\\\"\\n    import pylab\\n    import mpl_toolkits.mplot3d as mplot3d\\n    if file:\\n        axes = None\\n    fig = None\\n    if not axes:\\n        fig = pylab.figure()\\n        axes = mplot3d.axes3d.Axes3D(fig)\\n    ua, ub = u\\n    va, vb = v\\n    du = ub - ua\\n    dv = vb - va\\n    if not isinstance(points, (list, tuple)):\\n        points = [points, points]\\n    M, N = points\\n    u = pylab.linspace(ua, ub, M)\\n    v = pylab.linspace(va, vb, N)\\n    x, y, z = [pylab.zeros((M, N)) for i in xrange(3)]\\n    xab, yab, zab = [[0, 0] for i in xrange(3)]\\n    for n in xrange(N):\\n        for m in xrange(M):\\n            fdata = f(ctx.convert(u[m]), ctx.convert(v[n]))\\n            try:\\n                x[m,n], y[m,n], z[m,n] = fdata\\n            except TypeError:\\n                x[m,n], y[m,n], z[m,n] = u[m], v[n], fdata\\n            for c, cab in [(x[m,n], xab), (y[m,n], yab), (z[m,n], zab)]:\\n                if c < cab[0]:\\n                    cab[0] = c\\n                if c > cab[1]:\\n                    cab[1] = c\\n    if wireframe:\\n        axes.plot_wireframe(x, y, z, rstride=4, cstride=4)\\n    else:\\n        axes.plot_surface(x, y, z, rstride=4, cstride=4)\\n    axes.set_xlabel('x')\\n    axes.set_ylabel('y')\\n    axes.set_zlabel('z')\\n    if keep_aspect:\\n        dx, dy, dz = [cab[1] - cab[0] for cab in [xab, yab, zab]]\\n        maxd = max(dx, dy, dz)\\n        if dx < maxd:\\n            delta = maxd - dx\\n            axes.set_xlim3d(xab[0] - delta / 2.0, xab[1] + delta / 2.0)\\n        if dy < maxd:\\n            delta = maxd - dy\\n            axes.set_ylim3d(yab[0] - delta / 2.0, yab[1] + delta / 2.0)\\n        if dz < maxd:\\n            delta = maxd - dz\\n            axes.set_zlim3d(zab[0] - delta / 2.0, zab[1] + delta / 2.0)\\n    if fig:\\n        if file:\\n            pylab.savefig(file, dpi=dpi)\\n        else:\\n            pylab.show()\\n\\n\\nVisualizationMethods.plot = plot\\nVisualizationMethods.default_color_function = default_color_function\\nVisualizationMethods.phase_color_function = phase_color_function\\nVisualizationMethods.cplot = cplot\\nVisualizationMethods.splot = splot\\n\\n\\n\\\"\\\"\\\"\\nThis module defines the mpf, mpc classes, and standard functions for\\noperating with them.\\n\\\"\\\"\\\"\\n__docformat__ = 'plaintext'\\n\\nimport functools\\n\\nimport re\\n\\nfrom .ctx_base import StandardBaseContext\\n\\nfrom .libmp.backend import basestring, BACKEND\\n\\nfrom . import libmp\\n\\nfrom .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,\\n    round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,\\n    ComplexResult, to_pickable, from_pickable, normalize,\\n    from_int, from_float, from_str, to_int, to_float, to_str,\\n    from_rational, from_man_exp,\\n    fone, fzero, finf, fninf, fnan,\\n    mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,\\n    mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,\\n    mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,\\n    mpf_hash, mpf_rand,\\n    mpf_sum,\\n    bitcount, to_fixed,\\n    mpc_to_str,\\n    mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,\\n    mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,\\n    mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,\\n    mpc_mpf_div,\\n    mpf_pow,\\n    mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,\\n    mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,\\n    mpf_glaisher, mpf_twinprime, mpf_mertens,\\n    int_types)\\n\\nfrom . import function_docs\\nfrom . import rational\\n\\nnew = object.__new__\\n\\nget_complex = re.compile(r'^\\\\(?(?P<re>[\\\\+\\\\-]?\\\\d*(\\\\.\\\\d*)?(e[\\\\+\\\\-]?\\\\d+)?)??'\\n                         r'(?P<im>[\\\\+\\\\-]?\\\\d*(\\\\.\\\\d*)?(e[\\\\+\\\\-]?\\\\d+)?j)?\\\\)?$')\\n\\nif BACKEND == 'sage':\\n    from sage.libs.mpmath.ext_main import Context as BaseMPContext\\n    # pickle hack\\n    import sage.libs.mpmath.ext_main as _mpf_module\\nelse:\\n    from .ctx_mp_python import PythonMPContext as BaseMPContext\\n    from . import ctx_mp_python as _mpf_module\\n\\nfrom .ctx_mp_python import _mpf, _mpc, mpnumeric\\n\\nclass MPContext(BaseMPContext, StandardBaseContext):\\n    \\\"\\\"\\\"\\n    Context for multiprecision arithmetic with a global precision.\\n    \\\"\\\"\\\"\\n\\n    def __init__(ctx):\\n        BaseMPContext.__init__(ctx)\\n        ctx.trap_complex = False\\n        ctx.pretty = False\\n        ctx.types = [ctx.mpf, ctx.mpc, ctx.constant]\\n        ctx._mpq = rational.mpq\\n        ctx.default()\\n        StandardBaseContext.__init__(ctx)\\n\\n        ctx.mpq = rational.mpq\\n        ctx.init_builtins()\\n\\n        ctx.hyp_summators = {}\\n\\n        ctx._init_aliases()\\n\\n        # XXX: automate\\n        try:\\n            ctx.bernoulli.im_func.func_doc = function_docs.bernoulli\\n            ctx.primepi.im_func.func_doc = function_docs.primepi\\n            ctx.psi.im_func.func_doc = function_docs.psi\\n            ctx.atan2.im_func.func_doc = function_docs.atan2\\n        except AttributeError:\\n            # python 3\\n            ctx.bernoulli.__func__.func_doc = function_docs.bernoulli\\n            ctx.primepi.__func__.func_doc = function_docs.primepi\\n            ctx.psi.__func__.func_doc = function_docs.psi\\n            ctx.atan2.__func__.func_doc = function_docs.atan2\\n\\n        ctx.digamma.func_doc = function_docs.digamma\\n        ctx.cospi.func_doc = function_docs.cospi\\n        ctx.sinpi.func_doc = function_docs.sinpi\\n\\n    def init_builtins(ctx):\\n\\n        mpf = ctx.mpf\\n        mpc = ctx.mpc\\n\\n        # Exact constants\\n        ctx.one = ctx.make_mpf(fone)\\n        ctx.zero = ctx.make_mpf(fzero)\\n        ctx.j = ctx.make_mpc((fzero,fone))\\n        ctx.inf = ctx.make_mpf(finf)\\n        ctx.ninf = ctx.make_mpf(fninf)\\n        ctx.nan = ctx.make_mpf(fnan)\\n\\n        eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1),\\n            \\\"epsilon of working precision\\\", \\\"eps\\\")\\n        ctx.eps = eps\\n\\n        # Approximate constants\\n        ctx.pi = ctx.constant(mpf_pi, \\\"pi\\\", \\\"pi\\\")\\n        ctx.ln2 = ctx.constant(mpf_ln2, \\\"ln(2)\\\", \\\"ln2\\\")\\n        ctx.ln10 = ctx.constant(mpf_ln10, \\\"ln(10)\\\", \\\"ln10\\\")\\n        ctx.phi = ctx.constant(mpf_phi, \\\"Golden ratio phi\\\", \\\"phi\\\")\\n        ctx.e = ctx.constant(mpf_e, \\\"e = exp(1)\\\", \\\"e\\\")\\n        ctx.euler = ctx.constant(mpf_euler, \\\"Euler's constant\\\", \\\"euler\\\")\\n        ctx.catalan = ctx.constant(mpf_catalan, \\\"Catalan's constant\\\", \\\"catalan\\\")\\n        ctx.khinchin = ctx.constant(mpf_khinchin, \\\"Khinchin's constant\\\", \\\"khinchin\\\")\\n        ctx.glaisher = ctx.constant(mpf_glaisher, \\\"Glaisher's constant\\\", \\\"glaisher\\\")\\n        ctx.apery = ctx.constant(mpf_apery, \\\"Apery's constant\\\", \\\"apery\\\")\\n        ctx.degree = ctx.constant(mpf_degree, \\\"1 deg = pi / 180\\\", \\\"degree\\\")\\n        ctx.twinprime = ctx.constant(mpf_twinprime, \\\"Twin prime constant\\\", \\\"twinprime\\\")\\n        ctx.mertens = ctx.constant(mpf_mertens, \\\"Mertens' constant\\\", \\\"mertens\\\")\\n\\n        # Standard functions\\n        ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt)\\n        ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt)\\n        ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log)\\n        ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)\\n        ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp)\\n        ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj)\\n        ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi)\\n        ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin)\\n        ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos)\\n        ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan)\\n        ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh)\\n        ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh)\\n        ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh)\\n        ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin)\\n        ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos)\\n        ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)\\n        ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh)\\n        ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh)\\n        ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh)\\n        ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi)\\n        ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi)\\n        ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor)\\n        ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil)\\n        ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint)\\n        ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac)\\n        ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci)\\n\\n        ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma)\\n        ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma)\\n        ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma)\\n        ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial)\\n\\n        ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0)\\n        ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic)\\n        ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei)\\n        ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1)\\n        ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci)\\n        ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si)\\n        ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk)\\n        ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe)\\n        ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1)\\n        ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None)\\n        ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None)\\n        ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta)\\n        ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta)\\n\\n        # Faster versions\\n        ctx.sqrt = getattr(ctx, \\\"_sage_sqrt\\\", ctx.sqrt)\\n        ctx.exp = getattr(ctx, \\\"_sage_exp\\\", ctx.exp)\\n        ctx.ln = getattr(ctx, \\\"_sage_ln\\\", ctx.ln)\\n        ctx.cos = getattr(ctx, \\\"_sage_cos\\\", ctx.cos)\\n        ctx.sin = getattr(ctx, \\\"_sage_sin\\\", ctx.sin)\\n\\n    def to_fixed(ctx, x, prec):\\n        return x.to_fixed(prec)\\n\\n    def hypot(ctx, x, y):\\n        r\\\"\\\"\\\"\\n        Computes the Euclidean norm of the vector `(x, y)`, equal\\n        to `\\\\sqrt{x^2 + y^2}`. Both `x` and `y` must be real.\\\"\\\"\\\"\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding))\\n\\n    def _gamma_upper_int(ctx, n, z):\\n        n = int(ctx._re(n))\\n        if n == 0:\\n            return ctx.e1(z)\\n        if not hasattr(z, '_mpf_'):\\n            raise NotImplementedError\\n        prec, rounding = ctx._prec_rounding\\n        real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True)\\n        if imag is None:\\n            return ctx.make_mpf(real)\\n        else:\\n            return ctx.make_mpc((real, imag))\\n\\n    def _expint_int(ctx, n, z):\\n        n = int(n)\\n        if n == 1:\\n            return ctx.e1(z)\\n        if not hasattr(z, '_mpf_'):\\n            raise NotImplementedError\\n        prec, rounding = ctx._prec_rounding\\n        real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding)\\n        if imag is None:\\n            return ctx.make_mpf(real)\\n        else:\\n            return ctx.make_mpc((real, imag))\\n\\n    def _nthroot(ctx, x, n):\\n        if hasattr(x, '_mpf_'):\\n            try:\\n                return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding))\\n            except ComplexResult:\\n                if ctx.trap_complex:\\n                    raise\\n                x = (x._mpf_, libmp.fzero)\\n        else:\\n            x = x._mpc_\\n        return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding))\\n\\n    def _besselj(ctx, n, z):\\n        prec, rounding = ctx._prec_rounding\\n        if hasattr(z, '_mpf_'):\\n            return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding))\\n        elif hasattr(z, '_mpc_'):\\n            return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding))\\n\\n    def _agm(ctx, a, b=1):\\n        prec, rounding = ctx._prec_rounding\\n        if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'):\\n            try:\\n                v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding)\\n                return ctx.make_mpf(v)\\n            except ComplexResult:\\n                pass\\n        if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero)\\n        else: a = a._mpc_\\n        if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero)\\n        else: b = b._mpc_\\n        return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding))\\n\\n    def bernoulli(ctx, n):\\n        return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding))\\n\\n    def _zeta_int(ctx, n):\\n        return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding))\\n\\n    def atan2(ctx, y, x):\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding))\\n\\n    def psi(ctx, m, z):\\n        z = ctx.convert(z)\\n        m = int(m)\\n        if ctx._is_real_type(z):\\n            return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding))\\n        else:\\n            return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding))\\n\\n    def cos_sin(ctx, x, **kwargs):\\n        if type(x) not in ctx.types:\\n            x = ctx.convert(x)\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        if hasattr(x, '_mpf_'):\\n            c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding)\\n            return ctx.make_mpf(c), ctx.make_mpf(s)\\n        elif hasattr(x, '_mpc_'):\\n            c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding)\\n            return ctx.make_mpc(c), ctx.make_mpc(s)\\n        else:\\n            return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)\\n\\n    def cospi_sinpi(ctx, x, **kwargs):\\n        if type(x) not in ctx.types:\\n            x = ctx.convert(x)\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        if hasattr(x, '_mpf_'):\\n            c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding)\\n            return ctx.make_mpf(c), ctx.make_mpf(s)\\n        elif hasattr(x, '_mpc_'):\\n            c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding)\\n            return ctx.make_mpc(c), ctx.make_mpc(s)\\n        else:\\n            return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)\\n\\n    def clone(ctx):\\n        \\\"\\\"\\\"\\n        Create a copy of the context, with the same working precision.\\n        \\\"\\\"\\\"\\n        a = ctx.__class__()\\n        a.prec = ctx.prec\\n        return a\\n\\n    # Several helper methods\\n    # TODO: add more of these, make consistent, write docstrings, ...\\n\\n    def _is_real_type(ctx, x):\\n        if hasattr(x, '_mpc_') or type(x) is complex:\\n            return False\\n        return True\\n\\n    def _is_complex_type(ctx, x):\\n        if hasattr(x, '_mpc_') or type(x) is complex:\\n            return True\\n        return False\\n\\n    def isnan(ctx, x):\\n        \\\"\\\"\\\"\\n        Return *True* if *x* is a NaN (not-a-number), or for a complex\\n        number, whether either the real or complex part is NaN;\\n        otherwise return *False*::\\n\\n            >>> from mpmath import *\\n            >>> isnan(3.14)\\n            False\\n            >>> isnan(nan)\\n            True\\n            >>> isnan(mpc(3.14,2.72))\\n            False\\n            >>> isnan(mpc(3.14,nan))\\n            True\\n\\n        \\\"\\\"\\\"\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            return x._mpf_ == fnan\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            return fnan in x._mpc_\\n        if isinstance(x, int_types) or isinstance(x, rational.mpq):\\n            return False\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):\\n            return ctx.isnan(x)\\n        raise TypeError(\\\"isnan() needs a number as input\\\")\\n\\n    def isfinite(ctx, x):\\n        \\\"\\\"\\\"\\n        Return *True* if *x* is a finite number, i.e. neither\\n        an infinity or a NaN.\\n\\n            >>> from mpmath import *\\n            >>> isfinite(inf)\\n            False\\n            >>> isfinite(-inf)\\n            False\\n            >>> isfinite(3)\\n            True\\n            >>> isfinite(nan)\\n            False\\n            >>> isfinite(3+4j)\\n            True\\n            >>> isfinite(mpc(3,inf))\\n            False\\n            >>> isfinite(mpc(nan,3))\\n            False\\n\\n        \\\"\\\"\\\"\\n        if ctx.isinf(x) or ctx.isnan(x):\\n            return False\\n        return True\\n\\n    def isnpint(ctx, x):\\n        \\\"\\\"\\\"\\n        Determine if *x* is a nonpositive integer.\\n        \\\"\\\"\\\"\\n        if not x:\\n            return True\\n        if hasattr(x, '_mpf_'):\\n            sign, man, exp, bc = x._mpf_\\n            return sign and exp >= 0\\n        if hasattr(x, '_mpc_'):\\n            return not x.imag and ctx.isnpint(x.real)\\n        if type(x) in int_types:\\n            return x <= 0\\n        if isinstance(x, ctx.mpq):\\n            p, q = x._mpq_\\n            if not p:\\n                return True\\n            return q == 1 and p <= 0\\n        return ctx.isnpint(ctx.convert(x))\\n\\n    def __str__(ctx):\\n        lines = [\\\"Mpmath settings:\\\",\\n            (\\\"  mp.prec = %s\\\" % ctx.prec).ljust(30) + \\\"[default: 53]\\\",\\n            (\\\"  mp.dps = %s\\\" % ctx.dps).ljust(30) + \\\"[default: 15]\\\",\\n            (\\\"  mp.trap_complex = %s\\\" % ctx.trap_complex).ljust(30) + \\\"[default: False]\\\",\\n        ]\\n        return \\\"\\\\n\\\".join(lines)\\n\\n    @property\\n    def _repr_digits(ctx):\\n        return repr_dps(ctx._prec)\\n\\n    @property\\n    def _str_digits(ctx):\\n        return ctx._dps\\n\\n    def extraprec(ctx, n, normalize_output=False):\\n        \\\"\\\"\\\"\\n        The block\\n\\n            with extraprec(n):\\n                <code>\\n\\n        increases the precision n bits, executes <code>, and then\\n        restores the precision.\\n\\n        extraprec(n)(f) returns a decorated version of the function f\\n        that increases the working precision by n bits before execution,\\n        and restores the parent precision afterwards. With\\n        normalize_output=True, it rounds the return value to the parent\\n        precision.\\n        \\\"\\\"\\\"\\n        return PrecisionManager(ctx, lambda p: p + n, None, normalize_output)\\n\\n    def extradps(ctx, n, normalize_output=False):\\n        \\\"\\\"\\\"\\n        This function is analogous to extraprec (see documentation)\\n        but changes the decimal precision instead of the number of bits.\\n        \\\"\\\"\\\"\\n        return PrecisionManager(ctx, None, lambda d: d + n, normalize_output)\\n\\n    def workprec(ctx, n, normalize_output=False):\\n        \\\"\\\"\\\"\\n        The block\\n\\n            with workprec(n):\\n                <code>\\n\\n        sets the precision to n bits, executes <code>, and then restores\\n        the precision.\\n\\n        workprec(n)(f) returns a decorated version of the function f\\n        that sets the precision to n bits before execution,\\n        and restores the precision afterwards. With normalize_output=True,\\n        it rounds the return value to the parent precision.\\n        \\\"\\\"\\\"\\n        return PrecisionManager(ctx, lambda p: n, None, normalize_output)\\n\\n    def workdps(ctx, n, normalize_output=False):\\n        \\\"\\\"\\\"\\n        This function is analogous to workprec (see documentation)\\n        but changes the decimal precision instead of the number of bits.\\n        \\\"\\\"\\\"\\n        return PrecisionManager(ctx, None, lambda d: n, normalize_output)\\n\\n    def autoprec(ctx, f, maxprec=None, catch=(), verbose=False):\\n        r\\\"\\\"\\\"\\n        Return a wrapped copy of *f* that repeatedly evaluates *f*\\n        with increasing precision until the result converges to the\\n        full precision used at the point of the call.\\n\\n        This heuristically protects against rounding errors, at the cost of\\n        roughly a 2x slowdown compared to manually setting the optimal\\n        precision. This method can, however, easily be fooled if the results\\n        from *f* depend \\\"discontinuously\\\" on the precision, for instance\\n        if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec`\\n        should be used judiciously.\\n\\n        **Examples**\\n\\n        Many functions are sensitive to perturbations of the input arguments.\\n        If the arguments are decimal numbers, they may have to be converted\\n        to binary at a much higher precision. If the amount of required\\n        extra precision is unknown, :func:`~mpmath.autoprec` is convenient::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15\\n            >>> mp.pretty = True\\n            >>> besselj(5, 125 * 10**28)    # Exact input\\n            -8.03284785591801e-17\\n            >>> besselj(5, '1.25e30')   # Bad\\n            7.12954868316652e-16\\n            >>> autoprec(besselj)(5, '1.25e30')   # Good\\n            -8.03284785591801e-17\\n\\n        The following fails to converge because `\\\\sin(\\\\pi) = 0` whereas all\\n        finite-precision approximations of `\\\\pi` give nonzero values::\\n\\n            >>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL\\n            Traceback (most recent call last):\\n              ...\\n            NoConvergence: autoprec: prec increased to 2910 without convergence\\n\\n        As the following example shows, :func:`~mpmath.autoprec` can protect against\\n        cancellation, but is fooled by too severe cancellation::\\n\\n            >>> x = 1e-10\\n            >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)\\n            1.00000008274037e-10\\n            1.00000000005e-10\\n            1.00000000005e-10\\n            >>> x = 1e-50\\n            >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)\\n            0.0\\n            1.0e-50\\n            0.0\\n\\n        With *catch*, an exception or list of exceptions to intercept\\n        may be specified. The raised exception is interpreted\\n        as signaling insufficient precision. This permits, for example,\\n        evaluating a function where a too low precision results in a\\n        division by zero::\\n\\n            >>> f = lambda x: 1/(exp(x)-1)\\n            >>> f(1e-30)\\n            Traceback (most recent call last):\\n              ...\\n            ZeroDivisionError\\n            >>> autoprec(f, catch=ZeroDivisionError)(1e-30)\\n            1.0e+30\\n\\n\\n        \\\"\\\"\\\"\\n        def f_autoprec_wrapped(*args, **kwargs):\\n            prec = ctx.prec\\n            if maxprec is None:\\n                maxprec2 = ctx._default_hyper_maxprec(prec)\\n            else:\\n                maxprec2 = maxprec\\n            try:\\n                ctx.prec = prec + 10\\n                try:\\n                    v1 = f(*args, **kwargs)\\n                except catch:\\n                    v1 = ctx.nan\\n                prec2 = prec + 20\\n                while 1:\\n                    ctx.prec = prec2\\n                    try:\\n                        v2 = f(*args, **kwargs)\\n                    except catch:\\n                        v2 = ctx.nan\\n                    if v1 == v2:\\n                        break\\n                    err = ctx.mag(v2-v1) - ctx.mag(v2)\\n                    if err < (-prec):\\n                        break\\n                    if verbose:\\n                        print(\\\"autoprec: target=%s, prec=%s, accuracy=%s\\\" \\\\\\n                            % (prec, prec2, -err))\\n                    v1 = v2\\n                    if prec2 >= maxprec2:\\n                        raise ctx.NoConvergence(\\\\\\n                        \\\"autoprec: prec increased to %i without convergence\\\"\\\\\\n                        % prec2)\\n                    prec2 += int(prec2*2)\\n                    prec2 = min(prec2, maxprec2)\\n            finally:\\n                ctx.prec = prec\\n            return +v2\\n        return f_autoprec_wrapped\\n\\n    def nstr(ctx, x, n=6, **kwargs):\\n        \\\"\\\"\\\"\\n        Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n*\\n        significant digits. The small default value for *n* is chosen to\\n        make this function useful for printing collections of numbers\\n        (lists, matrices, etc).\\n\\n        If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively\\n        to each element. For unrecognized classes, :func:`~mpmath.nstr`\\n        simply returns ``str(x)``.\\n\\n        The companion function :func:`~mpmath.nprint` prints the result\\n        instead of returning it.\\n\\n        The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed*\\n        and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`.\\n\\n        The number will be printed in fixed-point format if the position\\n        of the leading digit is strictly between min_fixed\\n        (default = min(-dps/3,-5)) and max_fixed (default = dps).\\n\\n        To force fixed-point format always, set min_fixed = -inf,\\n        max_fixed = +inf. To force floating-point format, set\\n        min_fixed >= max_fixed.\\n\\n            >>> from mpmath import *\\n            >>> nstr([+pi, ldexp(1,-500)])\\n            '[3.14159, 3.05494e-151]'\\n            >>> nprint([+pi, ldexp(1,-500)])\\n            [3.14159, 3.05494e-151]\\n            >>> nstr(mpf(\\\"5e-10\\\"), 5)\\n            '5.0e-10'\\n            >>> nstr(mpf(\\\"5e-10\\\"), 5, strip_zeros=False)\\n            '5.0000e-10'\\n            >>> nstr(mpf(\\\"5e-10\\\"), 5, strip_zeros=False, min_fixed=-11)\\n            '0.00000000050000'\\n            >>> nstr(mpf(0), 5, show_zero_exponent=True)\\n            '0.0e+0'\\n\\n        \\\"\\\"\\\"\\n        if isinstance(x, list):\\n            return \\\"[%s]\\\" % (\\\", \\\".join(ctx.nstr(c, n, **kwargs) for c in x))\\n        if isinstance(x, tuple):\\n            return \\\"(%s)\\\" % (\\\", \\\".join(ctx.nstr(c, n, **kwargs) for c in x))\\n        if hasattr(x, '_mpf_'):\\n            return to_str(x._mpf_, n, **kwargs)\\n        if hasattr(x, '_mpc_'):\\n            return \\\"(\\\" + mpc_to_str(x._mpc_, n, **kwargs)  + \\\")\\\"\\n        if isinstance(x, basestring):\\n            return repr(x)\\n        if isinstance(x, ctx.matrix):\\n            return x.__nstr__(n, **kwargs)\\n        return str(x)\\n\\n    def _convert_fallback(ctx, x, strings):\\n        if strings and isinstance(x, basestring):\\n            if 'j' in x.lower():\\n                x = x.lower().replace(' ', '')\\n                match = get_complex.match(x)\\n                re = match.group('re')\\n                if not re:\\n                    re = 0\\n                im = match.group('im').rstrip('j')\\n                return ctx.mpc(ctx.convert(re), ctx.convert(im))\\n        if hasattr(x, \\\"_mpi_\\\"):\\n            a, b = x._mpi_\\n            if a == b:\\n                return ctx.make_mpf(a)\\n            else:\\n                raise ValueError(\\\"can only create mpf from zero-width interval\\\")\\n        raise TypeError(\\\"cannot create mpf from \\\" + repr(x))\\n\\n    def mpmathify(ctx, *args, **kwargs):\\n        return ctx.convert(*args, **kwargs)\\n\\n    def _parse_prec(ctx, kwargs):\\n        if kwargs:\\n            if kwargs.get('exact'):\\n                return 0, 'f'\\n            prec, rounding = ctx._prec_rounding\\n            if 'rounding' in kwargs:\\n                rounding = kwargs['rounding']\\n            if 'prec' in kwargs:\\n                prec = kwargs['prec']\\n                if prec == ctx.inf:\\n                    return 0, 'f'\\n                else:\\n                    prec = int(prec)\\n            elif 'dps' in kwargs:\\n                dps = kwargs['dps']\\n                if dps == ctx.inf:\\n                    return 0, 'f'\\n                prec = dps_to_prec(dps)\\n            return prec, rounding\\n        return ctx._prec_rounding\\n\\n    _exact_overflow_msg = \\\"the exact result does not fit in memory\\\"\\n\\n    _hypsum_msg = \\\"\\\"\\\"hypsum() failed to converge to the requested %i bits of accuracy\\nusing a working precision of %i bits. Try with a higher maxprec,\\nmaxterms, or set zeroprec.\\\"\\\"\\\"\\n\\n    def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs):\\n        if hasattr(z, \\\"_mpf_\\\"):\\n            key = p, q, flags, 'R'\\n            v = z._mpf_\\n        elif hasattr(z, \\\"_mpc_\\\"):\\n            key = p, q, flags, 'C'\\n            v = z._mpc_\\n        if key not in ctx.hyp_summators:\\n            ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1]\\n        summator = ctx.hyp_summators[key]\\n        prec = ctx.prec\\n        maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec))\\n        extraprec = 50\\n        epsshift = 25\\n        # Jumps in magnitude occur when parameters are close to negative\\n        # integers. We must ensure that these terms are included in\\n        # the sum and added accurately\\n        magnitude_check = {}\\n        max_total_jump = 0\\n        for i, c in enumerate(coeffs):\\n            if flags[i] == 'Z':\\n                if i >= p and c <= 0:\\n                    ok = False\\n                    for ii, cc in enumerate(coeffs[:p]):\\n                        # Note: c <= cc or c < cc, depending on convention\\n                        if flags[ii] == 'Z' and cc <= 0 and c <= cc:\\n                            ok = True\\n                    if not ok:\\n                        raise ZeroDivisionError(\\\"pole in hypergeometric series\\\")\\n                continue\\n            n, d = ctx.nint_distance(c)\\n            n = -int(n)\\n            d = -d\\n            if i >= p and n >= 0 and d > 4:\\n                if n in magnitude_check:\\n                    magnitude_check[n] += d\\n                else:\\n                    magnitude_check[n] = d\\n                extraprec = max(extraprec, d - prec + 60)\\n            max_total_jump += abs(d)\\n        while 1:\\n            if extraprec > maxprec:\\n                raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec))\\n            wp = prec + extraprec\\n            if magnitude_check:\\n                mag_dict = dict((n,None) for n in magnitude_check)\\n            else:\\n                mag_dict = {}\\n            zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \\\\\\n                epsshift, mag_dict, **kwargs)\\n            cancel = -magnitude\\n            jumps_resolved = True\\n            if extraprec < max_total_jump:\\n                for n in mag_dict.values():\\n                    if (n is None) or (n < prec):\\n                        jumps_resolved = False\\n                        break\\n            accurate = (cancel < extraprec-25-5 or not accurate_small)\\n            if jumps_resolved:\\n                if accurate:\\n                    break\\n                # zero?\\n                zeroprec = kwargs.get('zeroprec')\\n                if zeroprec is not None:\\n                    if cancel > zeroprec:\\n                        if have_complex:\\n                            return ctx.mpc(0)\\n                        else:\\n                            return ctx.zero\\n\\n            # Some near-singularities were not included, so increase\\n            # precision and repeat until they are\\n            extraprec *= 2\\n            # Possible workaround for bad roundoff in fixed-point arithmetic\\n            epsshift += 5\\n            extraprec += 5\\n\\n        if type(zv) is tuple:\\n            if have_complex:\\n                return ctx.make_mpc(zv)\\n            else:\\n                return ctx.make_mpf(zv)\\n        else:\\n            return zv\\n\\n    def ldexp(ctx, x, n):\\n        r\\\"\\\"\\\"\\n        Computes `x 2^n` efficiently. No rounding is performed.\\n        The argument `x` must be a real floating-point number (or\\n        possible to convert into one) and `n` must be a Python ``int``.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> ldexp(1, 10)\\n            mpf('1024.0')\\n            >>> ldexp(1, -3)\\n            mpf('0.125')\\n\\n        \\\"\\\"\\\"\\n        x = ctx.convert(x)\\n        return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n))\\n\\n    def frexp(ctx, x):\\n        r\\\"\\\"\\\"\\n        Given a real number `x`, returns `(y, n)` with `y \\\\in [0.5, 1)`,\\n        `n` a Python integer, and such that `x = y 2^n`. No rounding is\\n        performed.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> frexp(7.5)\\n            (mpf('0.9375'), 3)\\n\\n        \\\"\\\"\\\"\\n        x = ctx.convert(x)\\n        y, n = libmp.mpf_frexp(x._mpf_)\\n        return ctx.make_mpf(y), n\\n\\n    def fneg(ctx, x, **kwargs):\\n        \\\"\\\"\\\"\\n        Negates the number *x*, giving a floating-point result, optionally\\n        using a custom precision and rounding mode.\\n\\n        See the documentation of :func:`~mpmath.fadd` for a detailed description\\n        of how to specify precision and rounding.\\n\\n        **Examples**\\n\\n        An mpmath number is returned::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fneg(2.5)\\n            mpf('-2.5')\\n            >>> fneg(-5+2j)\\n            mpc(real='5.0', imag='-2.0')\\n\\n        Precise control over rounding is possible::\\n\\n            >>> x = fadd(2, 1e-100, exact=True)\\n            >>> fneg(x)\\n            mpf('-2.0')\\n            >>> fneg(x, rounding='f')\\n            mpf('-2.0000000000000004')\\n\\n        Negating with and without roundoff::\\n\\n            >>> n = 200000000000000000000001\\n            >>> print(int(-mpf(n)))\\n            -200000000000000016777216\\n            >>> print(int(fneg(n)))\\n            -200000000000000016777216\\n            >>> print(int(fneg(n, prec=log(n,2)+1)))\\n            -200000000000000000000001\\n            >>> print(int(fneg(n, dps=log(n,10)+1)))\\n            -200000000000000000000001\\n            >>> print(int(fneg(n, prec=inf)))\\n            -200000000000000000000001\\n            >>> print(int(fneg(n, dps=inf)))\\n            -200000000000000000000001\\n            >>> print(int(fneg(n, exact=True)))\\n            -200000000000000000000001\\n\\n        \\\"\\\"\\\"\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_'):\\n            return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding))\\n        if hasattr(x, '_mpc_'):\\n            return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding))\\n        raise ValueError(\\\"Arguments need to be mpf or mpc compatible numbers\\\")\\n\\n    def fadd(ctx, x, y, **kwargs):\\n        \\\"\\\"\\\"\\n        Adds the numbers *x* and *y*, giving a floating-point result,\\n        optionally using a custom precision and rounding mode.\\n\\n        The default precision is the working precision of the context.\\n        You can specify a custom precision in bits by passing the *prec* keyword\\n        argument, or by providing an equivalent decimal precision with the *dps*\\n        keyword argument. If the precision is set to ``+inf``, or if the flag\\n        *exact=True* is passed, an exact addition with no rounding is performed.\\n\\n        When the precision is finite, the optional *rounding* keyword argument\\n        specifies the direction of rounding. Valid options are ``'n'`` for\\n        nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'``\\n        for down, ``'u'`` for up.\\n\\n        **Examples**\\n\\n        Using :func:`~mpmath.fadd` with precision and rounding control::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fadd(2, 1e-20)\\n            mpf('2.0')\\n            >>> fadd(2, 1e-20, rounding='u')\\n            mpf('2.0000000000000004')\\n            >>> nprint(fadd(2, 1e-20, prec=100), 25)\\n            2.00000000000000000001\\n            >>> nprint(fadd(2, 1e-20, dps=15), 25)\\n            2.0\\n            >>> nprint(fadd(2, 1e-20, dps=25), 25)\\n            2.00000000000000000001\\n            >>> nprint(fadd(2, 1e-20, exact=True), 25)\\n            2.00000000000000000001\\n\\n        Exact addition avoids cancellation errors, enforcing familiar laws\\n        of numbers such as `x+y-x = y`, which don't hold in floating-point\\n        arithmetic with finite precision::\\n\\n            >>> x, y = mpf(2), mpf('1e-1000')\\n            >>> print(x + y - x)\\n            0.0\\n            >>> print(fadd(x, y, prec=inf) - x)\\n            1.0e-1000\\n            >>> print(fadd(x, y, exact=True) - x)\\n            1.0e-1000\\n\\n        Exact addition can be inefficient and may be impossible to perform\\n        with large magnitude differences::\\n\\n            >>> fadd(1, '1e-100000000000000000000', prec=inf)\\n            Traceback (most recent call last):\\n              ...\\n            OverflowError: the exact result does not fit in memory\\n\\n        \\\"\\\"\\\"\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        try:\\n            if hasattr(x, '_mpf_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding))\\n            if hasattr(x, '_mpc_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding))\\n        except (ValueError, OverflowError):\\n            raise OverflowError(ctx._exact_overflow_msg)\\n        raise ValueError(\\\"Arguments need to be mpf or mpc compatible numbers\\\")\\n\\n    def fsub(ctx, x, y, **kwargs):\\n        \\\"\\\"\\\"\\n        Subtracts the numbers *x* and *y*, giving a floating-point result,\\n        optionally using a custom precision and rounding mode.\\n\\n        See the documentation of :func:`~mpmath.fadd` for a detailed description\\n        of how to specify precision and rounding.\\n\\n        **Examples**\\n\\n        Using :func:`~mpmath.fsub` with precision and rounding control::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fsub(2, 1e-20)\\n            mpf('2.0')\\n            >>> fsub(2, 1e-20, rounding='d')\\n            mpf('1.9999999999999998')\\n            >>> nprint(fsub(2, 1e-20, prec=100), 25)\\n            1.99999999999999999999\\n            >>> nprint(fsub(2, 1e-20, dps=15), 25)\\n            2.0\\n            >>> nprint(fsub(2, 1e-20, dps=25), 25)\\n            1.99999999999999999999\\n            >>> nprint(fsub(2, 1e-20, exact=True), 25)\\n            1.99999999999999999999\\n\\n        Exact subtraction avoids cancellation errors, enforcing familiar laws\\n        of numbers such as `x-y+y = x`, which don't hold in floating-point\\n        arithmetic with finite precision::\\n\\n            >>> x, y = mpf(2), mpf('1e1000')\\n            >>> print(x - y + y)\\n            0.0\\n            >>> print(fsub(x, y, prec=inf) + y)\\n            2.0\\n            >>> print(fsub(x, y, exact=True) + y)\\n            2.0\\n\\n        Exact addition can be inefficient and may be impossible to perform\\n        with large magnitude differences::\\n\\n            >>> fsub(1, '1e-100000000000000000000', prec=inf)\\n            Traceback (most recent call last):\\n              ...\\n            OverflowError: the exact result does not fit in memory\\n\\n        \\\"\\\"\\\"\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        try:\\n            if hasattr(x, '_mpf_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding))\\n            if hasattr(x, '_mpc_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding))\\n        except (ValueError, OverflowError):\\n            raise OverflowError(ctx._exact_overflow_msg)\\n        raise ValueError(\\\"Arguments need to be mpf or mpc compatible numbers\\\")\\n\\n    def fmul(ctx, x, y, **kwargs):\\n        \\\"\\\"\\\"\\n        Multiplies the numbers *x* and *y*, giving a floating-point result,\\n        optionally using a custom precision and rounding mode.\\n\\n        See the documentation of :func:`~mpmath.fadd` for a detailed description\\n        of how to specify precision and rounding.\\n\\n        **Examples**\\n\\n        The result is an mpmath number::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fmul(2, 5.0)\\n            mpf('10.0')\\n            >>> fmul(0.5j, 0.5)\\n            mpc(real='0.0', imag='0.25')\\n\\n        Avoiding roundoff::\\n\\n            >>> x, y = 10**10+1, 10**15+1\\n            >>> print(x*y)\\n            10000000001000010000000001\\n            >>> print(mpf(x) * mpf(y))\\n            1.0000000001e+25\\n            >>> print(int(mpf(x) * mpf(y)))\\n            10000000001000011026399232\\n            >>> print(int(fmul(x, y)))\\n            10000000001000011026399232\\n            >>> print(int(fmul(x, y, dps=25)))\\n            10000000001000010000000001\\n            >>> print(int(fmul(x, y, exact=True)))\\n            10000000001000010000000001\\n\\n        Exact multiplication with complex numbers can be inefficient and may\\n        be impossible to perform with large magnitude differences between\\n        real and imaginary parts::\\n\\n            >>> x = 1+2j\\n            >>> y = mpc(2, '1e-100000000000000000000')\\n            >>> fmul(x, y)\\n            mpc(real='2.0', imag='4.0')\\n            >>> fmul(x, y, rounding='u')\\n            mpc(real='2.0', imag='4.0000000000000009')\\n            >>> fmul(x, y, exact=True)\\n            Traceback (most recent call last):\\n              ...\\n            OverflowError: the exact result does not fit in memory\\n\\n        \\\"\\\"\\\"\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        try:\\n            if hasattr(x, '_mpf_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding))\\n            if hasattr(x, '_mpc_'):\\n                if hasattr(y, '_mpf_'):\\n                    return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding))\\n                if hasattr(y, '_mpc_'):\\n                    return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding))\\n        except (ValueError, OverflowError):\\n            raise OverflowError(ctx._exact_overflow_msg)\\n        raise ValueError(\\\"Arguments need to be mpf or mpc compatible numbers\\\")\\n\\n    def fdiv(ctx, x, y, **kwargs):\\n        \\\"\\\"\\\"\\n        Divides the numbers *x* and *y*, giving a floating-point result,\\n        optionally using a custom precision and rounding mode.\\n\\n        See the documentation of :func:`~mpmath.fadd` for a detailed description\\n        of how to specify precision and rounding.\\n\\n        **Examples**\\n\\n        The result is an mpmath number::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fdiv(3, 2)\\n            mpf('1.5')\\n            >>> fdiv(2, 3)\\n            mpf('0.66666666666666663')\\n            >>> fdiv(2+4j, 0.5)\\n            mpc(real='4.0', imag='8.0')\\n\\n        The rounding direction and precision can be controlled::\\n\\n            >>> fdiv(2, 3, dps=3)    # Should be accurate to at least 3 digits\\n            mpf('0.6666259765625')\\n            >>> fdiv(2, 3, rounding='d')\\n            mpf('0.66666666666666663')\\n            >>> fdiv(2, 3, prec=60)\\n            mpf('0.66666666666666667')\\n            >>> fdiv(2, 3, rounding='u')\\n            mpf('0.66666666666666674')\\n\\n        Checking the error of a division by performing it at higher precision::\\n\\n            >>> fdiv(2, 3) - fdiv(2, 3, prec=100)\\n            mpf('-3.7007434154172148e-17')\\n\\n        Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not\\n        allowed since the quotient of two floating-point numbers generally\\n        does not have an exact floating-point representation. (In the\\n        future this might be changed to allow the case where the division\\n        is actually exact.)\\n\\n            >>> fdiv(2, 3, exact=True)\\n            Traceback (most recent call last):\\n              ...\\n            ValueError: division is not an exact operation\\n\\n        \\\"\\\"\\\"\\n        prec, rounding = ctx._parse_prec(kwargs)\\n        if not prec:\\n            raise ValueError(\\\"division is not an exact operation\\\")\\n        x = ctx.convert(x)\\n        y = ctx.convert(y)\\n        if hasattr(x, '_mpf_'):\\n            if hasattr(y, '_mpf_'):\\n                return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding))\\n            if hasattr(y, '_mpc_'):\\n                return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding))\\n        if hasattr(x, '_mpc_'):\\n            if hasattr(y, '_mpf_'):\\n                return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding))\\n            if hasattr(y, '_mpc_'):\\n                return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding))\\n        raise ValueError(\\\"Arguments need to be mpf or mpc compatible numbers\\\")\\n\\n    def nint_distance(ctx, x):\\n        r\\\"\\\"\\\"\\n        Return `(n,d)` where `n` is the nearest integer to `x` and `d` is\\n        an estimate of `\\\\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision\\n        (measured in bits) lost to cancellation when computing `x-n`.\\n\\n            >>> from mpmath import *\\n            >>> n, d = nint_distance(5)\\n            >>> print(n); print(d)\\n            5\\n            -inf\\n            >>> n, d = nint_distance(mpf(5))\\n            >>> print(n); print(d)\\n            5\\n            -inf\\n            >>> n, d = nint_distance(mpf(5.00000001))\\n            >>> print(n); print(d)\\n            5\\n            -26\\n            >>> n, d = nint_distance(mpf(4.99999999))\\n            >>> print(n); print(d)\\n            5\\n            -26\\n            >>> n, d = nint_distance(mpc(5,10))\\n            >>> print(n); print(d)\\n            5\\n            4\\n            >>> n, d = nint_distance(mpc(5,0.000001))\\n            >>> print(n); print(d)\\n            5\\n            -19\\n\\n        \\\"\\\"\\\"\\n        typx = type(x)\\n        if typx in int_types:\\n            return int(x), ctx.ninf\\n        elif typx is rational.mpq:\\n            p, q = x._mpq_\\n            n, r = divmod(p, q)\\n            if 2*r >= q:\\n                n += 1\\n            elif not r:\\n                return n, ctx.ninf\\n            # log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q)\\n            d = bitcount(abs(p-n*q)) - bitcount(q)\\n            return n, d\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            re = x._mpf_\\n            im_dist = ctx.ninf\\n        elif hasattr(x, \\\"_mpc_\\\"):\\n            re, im = x._mpc_\\n            isign, iman, iexp, ibc = im\\n            if iman:\\n                im_dist = iexp + ibc\\n            elif im == fzero:\\n                im_dist = ctx.ninf\\n            else:\\n                raise ValueError(\\\"requires a finite number\\\")\\n        else:\\n            x = ctx.convert(x)\\n            if hasattr(x, \\\"_mpf_\\\") or hasattr(x, \\\"_mpc_\\\"):\\n                return ctx.nint_distance(x)\\n            else:\\n                raise TypeError(\\\"requires an mpf/mpc\\\")\\n        sign, man, exp, bc = re\\n        mag = exp+bc\\n        # |x| < 0.5\\n        if mag < 0:\\n            n = 0\\n            re_dist = mag\\n        elif man:\\n            # exact integer\\n            if exp >= 0:\\n                n = man << exp\\n                re_dist = ctx.ninf\\n            # exact half-integer\\n            elif exp == -1:\\n                n = (man>>1)+1\\n                re_dist = 0\\n            else:\\n                d = (-exp-1)\\n                t = man >> d\\n                if t & 1:\\n                    t += 1\\n                    man = (t<<d) - man\\n                else:\\n                    man -= (t<<d)\\n                n = t>>1   # int(t)>>1\\n                re_dist = exp+bitcount(man)\\n            if sign:\\n                n = -n\\n        elif re == fzero:\\n            re_dist = ctx.ninf\\n            n = 0\\n        else:\\n            raise ValueError(\\\"requires a finite number\\\")\\n        return n, max(re_dist, im_dist)\\n\\n    def fprod(ctx, factors):\\n        r\\\"\\\"\\\"\\n        Calculates a product containing a finite number of factors (for\\n        infinite products, see :func:`~mpmath.nprod`). The factors will be\\n        converted to mpmath numbers.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fprod([1, 2, 0.5, 7])\\n            mpf('7.0')\\n\\n        \\\"\\\"\\\"\\n        orig = ctx.prec\\n        try:\\n            v = ctx.one\\n            for p in factors:\\n                v *= p\\n        finally:\\n            ctx.prec = orig\\n        return +v\\n\\n    def rand(ctx):\\n        \\\"\\\"\\\"\\n        Returns an ``mpf`` with value chosen randomly from `[0, 1)`.\\n        The number of randomly generated bits in the mantissa is equal\\n        to the working precision.\\n        \\\"\\\"\\\"\\n        return ctx.make_mpf(mpf_rand(ctx._prec))\\n\\n    def fraction(ctx, p, q):\\n        \\\"\\\"\\\"\\n        Given Python integers `(p, q)`, returns a lazy ``mpf`` representing\\n        the fraction `p/q`. The value is updated with the precision.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15\\n            >>> a = fraction(1,100)\\n            >>> b = mpf(1)/100\\n            >>> print(a); print(b)\\n            0.01\\n            0.01\\n            >>> mp.dps = 30\\n            >>> print(a); print(b)      # a will be accurate\\n            0.01\\n            0.0100000000000000002081668171172\\n            >>> mp.dps = 15\\n        \\\"\\\"\\\"\\n        return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd),\\n            '%s/%s' % (p, q))\\n\\n    def absmin(ctx, x):\\n        return abs(ctx.convert(x))\\n\\n    def absmax(ctx, x):\\n        return abs(ctx.convert(x))\\n\\n    def _as_points(ctx, x):\\n        # XXX: remove this?\\n        if hasattr(x, '_mpi_'):\\n            a, b = x._mpi_\\n            return [ctx.make_mpf(a), ctx.make_mpf(b)]\\n        return x\\n\\n    '''\\n    def _zetasum(ctx, s, a, b):\\n        \\\"\\\"\\\"\\n        Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small\\n        integers.\\n        \\\"\\\"\\\"\\n        a = int(a)\\n        b = int(b)\\n        s = ctx.convert(s)\\n        prec, rounding = ctx._prec_rounding\\n        if hasattr(s, '_mpf_'):\\n            v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec))\\n        elif hasattr(s, '_mpc_'):\\n            v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec))\\n        return v\\n    '''\\n\\n    def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False):\\n        if not (ctx.isint(a) and hasattr(s, \\\"_mpc_\\\")):\\n            raise NotImplementedError\\n        a = int(a)\\n        prec = ctx._prec\\n        xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec)\\n        xs = [ctx.make_mpc(x) for x in xs]\\n        ys = [ctx.make_mpc(y) for y in ys]\\n        return xs, ys\\n\\nclass PrecisionManager:\\n    def __init__(self, ctx, precfun, dpsfun, normalize_output=False):\\n        self.ctx = ctx\\n        self.precfun = precfun\\n        self.dpsfun = dpsfun\\n        self.normalize_output = normalize_output\\n    def __call__(self, f):\\n        @functools.wraps(f)\\n        def g(*args, **kwargs):\\n            orig = self.ctx.prec\\n            try:\\n                if self.precfun:\\n                    self.ctx.prec = self.precfun(self.ctx.prec)\\n                else:\\n                    self.ctx.dps = self.dpsfun(self.ctx.dps)\\n                if self.normalize_output:\\n                    v = f(*args, **kwargs)\\n                    if type(v) is tuple:\\n                        return tuple([+a for a in v])\\n                    return +v\\n                else:\\n                    return f(*args, **kwargs)\\n            finally:\\n                self.ctx.prec = orig\\n        return g\\n    def __enter__(self):\\n        self.origp = self.ctx.prec\\n        if self.precfun:\\n            self.ctx.prec = self.precfun(self.ctx.prec)\\n        else:\\n            self.ctx.dps = self.dpsfun(self.ctx.dps)\\n    def __exit__(self, exc_type, exc_val, exc_tb):\\n        self.ctx.prec = self.origp\\n        return False\\n\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\n\\\"\\\"\\\"\\nExtended docstrings for functions.py\\n\\\"\\\"\\\"\\n\\n\\npi = r\\\"\\\"\\\"\\n`\\\\pi`, roughly equal to 3.141592654, represents the area of the unit\\ncircle, the half-period of trigonometric functions, and many other\\nthings in mathematics.\\n\\nMpmath can evaluate `\\\\pi` to arbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +pi\\n    3.1415926535897932384626433832795028841971693993751\\n\\nThis shows digits 99991-100000 of `\\\\pi` (the last digit is actually\\na 4 when the decimal expansion is truncated, but here the nearest\\nrounding is used)::\\n\\n    >>> mp.dps = 100000\\n    >>> str(pi)[-10:]\\n    '5549362465'\\n\\n**Possible issues**\\n\\n:data:`pi` always rounds to the nearest floating-point\\nnumber when used. This means that exact mathematical identities\\ninvolving `\\\\pi` will generally not be preserved in floating-point\\narithmetic. In particular, multiples of :data:`pi` (except for\\nthe trivial case ``0*pi``) are *not* the exact roots of\\n:func:`~mpmath.sin`, but differ roughly by the current epsilon::\\n\\n    >>> mp.dps = 15\\n    >>> sin(pi)\\n    1.22464679914735e-16\\n\\nOne solution is to use the :func:`~mpmath.sinpi` function instead::\\n\\n    >>> sinpi(1)\\n    0.0\\n\\nSee the documentation of trigonometric functions for additional\\ndetails.\\n\\n**References**\\n\\n* [BorweinBorwein]_\\n\\n\\\"\\\"\\\"\\n\\ndegree = r\\\"\\\"\\\"\\nRepresents one degree of angle, `1^{\\\\circ} = \\\\pi/180`, or\\nabout 0.01745329. This constant may be evaluated to arbitrary\\nprecision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +degree\\n    0.017453292519943295769236907684886127134428718885417\\n\\nThe :data:`degree` object is convenient for conversion\\nto radians::\\n\\n    >>> sin(30 * degree)\\n    0.5\\n    >>> asin(0.5) / degree\\n    30.0\\n\\\"\\\"\\\"\\n\\ne = r\\\"\\\"\\\"\\nThe transcendental number `e` = 2.718281828... is the base of the\\nnatural logarithm (:func:`~mpmath.ln`) and of the exponential function\\n(:func:`~mpmath.exp`).\\n\\nMpmath can be evaluate `e` to arbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +e\\n    2.7182818284590452353602874713526624977572470937\\n\\nThis shows digits 99991-100000 of `e` (the last digit is actually\\na 5 when the decimal expansion is truncated, but here the nearest\\nrounding is used)::\\n\\n    >>> mp.dps = 100000\\n    >>> str(e)[-10:]\\n    '2100427166'\\n\\n**Possible issues**\\n\\n:data:`e` always rounds to the nearest floating-point number\\nwhen used, and mathematical identities involving `e` may not\\nhold in floating-point arithmetic. For example, ``ln(e)``\\nmight not evaluate exactly to 1.\\n\\nIn particular, don't use ``e**x`` to compute the exponential\\nfunction. Use ``exp(x)`` instead; this is both faster and more\\naccurate.\\n\\\"\\\"\\\"\\n\\nphi = r\\\"\\\"\\\"\\nRepresents the golden ratio `\\\\phi = (1+\\\\sqrt 5)/2`,\\napproximately equal to 1.6180339887. To high precision,\\nits value is::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +phi\\n    1.6180339887498948482045868343656381177203091798058\\n\\nFormulas for the golden ratio include the following::\\n\\n    >>> (1+sqrt(5))/2\\n    1.6180339887498948482045868343656381177203091798058\\n    >>> findroot(lambda x: x**2-x-1, 1)\\n    1.6180339887498948482045868343656381177203091798058\\n    >>> limit(lambda n: fib(n+1)/fib(n), inf)\\n    1.6180339887498948482045868343656381177203091798058\\n\\\"\\\"\\\"\\n\\neuler = r\\\"\\\"\\\"\\nEuler's constant or the Euler-Mascheroni constant `\\\\gamma`\\n= 0.57721566... is a number of central importance to\\nnumber theory and special functions. It is defined as the limit\\n\\n.. math ::\\n\\n    \\\\gamma = \\\\lim_{n\\\\to\\\\infty} H_n - \\\\log n\\n\\nwhere `H_n = 1 + \\\\frac{1}{2} + \\\\ldots + \\\\frac{1}{n}` is a harmonic\\nnumber (see :func:`~mpmath.harmonic`).\\n\\nEvaluation of `\\\\gamma` is supported at arbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +euler\\n    0.57721566490153286060651209008240243104215933593992\\n\\nWe can also compute `\\\\gamma` directly from the definition,\\nalthough this is less efficient::\\n\\n    >>> limit(lambda n: harmonic(n)-log(n), inf)\\n    0.57721566490153286060651209008240243104215933593992\\n\\nThis shows digits 9991-10000 of `\\\\gamma` (the last digit is actually\\na 5 when the decimal expansion is truncated, but here the nearest\\nrounding is used)::\\n\\n    >>> mp.dps = 10000\\n    >>> str(euler)[-10:]\\n    '4679858166'\\n\\nIntegrals, series, and representations for `\\\\gamma` in terms of\\nspecial functions include the following (there are many others)::\\n\\n    >>> mp.dps = 25\\n    >>> -quad(lambda x: exp(-x)*log(x), [0,inf])\\n    0.5772156649015328606065121\\n    >>> quad(lambda x,y: (x-1)/(1-x*y)/log(x*y), [0,1], [0,1])\\n    0.5772156649015328606065121\\n    >>> nsum(lambda k: 1/k-log(1+1/k), [1,inf])\\n    0.5772156649015328606065121\\n    >>> nsum(lambda k: (-1)**k*zeta(k)/k, [2,inf])\\n    0.5772156649015328606065121\\n    >>> -diff(gamma, 1)\\n    0.5772156649015328606065121\\n    >>> limit(lambda x: 1/x-gamma(x), 0)\\n    0.5772156649015328606065121\\n    >>> limit(lambda x: zeta(x)-1/(x-1), 1)\\n    0.5772156649015328606065121\\n    >>> (log(2*pi*nprod(lambda n:\\n    ...     exp(-2+2/n)*(1+2/n)**n, [1,inf]))-3)/2\\n    0.5772156649015328606065121\\n\\nFor generalizations of the identities `\\\\gamma = -\\\\Gamma'(1)`\\nand `\\\\gamma = \\\\lim_{x\\\\to1} \\\\zeta(x)-1/(x-1)`, see\\n:func:`~mpmath.psi` and :func:`~mpmath.stieltjes` respectively.\\n\\n**References**\\n\\n* [BorweinBailey]_\\n\\n\\\"\\\"\\\"\\n\\ncatalan = r\\\"\\\"\\\"\\nCatalan's constant `K` = 0.91596559... is given by the infinite\\nseries\\n\\n.. math ::\\n\\n    K = \\\\sum_{k=0}^{\\\\infty} \\\\frac{(-1)^k}{(2k+1)^2}.\\n\\nMpmath can evaluate it to arbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +catalan\\n    0.91596559417721901505460351493238411077414937428167\\n\\nOne can also compute `K` directly from the definition, although\\nthis is significantly less efficient::\\n\\n    >>> nsum(lambda k: (-1)**k/(2*k+1)**2, [0, inf])\\n    0.91596559417721901505460351493238411077414937428167\\n\\nThis shows digits 9991-10000 of `K` (the last digit is actually\\na 3 when the decimal expansion is truncated, but here the nearest\\nrounding is used)::\\n\\n    >>> mp.dps = 10000\\n    >>> str(catalan)[-10:]\\n    '9537871504'\\n\\nCatalan's constant has numerous integral representations::\\n\\n    >>> mp.dps = 50\\n    >>> quad(lambda x: -log(x)/(1+x**2), [0, 1])\\n    0.91596559417721901505460351493238411077414937428167\\n    >>> quad(lambda x: atan(x)/x, [0, 1])\\n    0.91596559417721901505460351493238411077414937428167\\n    >>> quad(lambda x: ellipk(x**2)/2, [0, 1])\\n    0.91596559417721901505460351493238411077414937428167\\n    >>> quad(lambda x,y: 1/(1+(x*y)**2), [0, 1], [0, 1])\\n    0.91596559417721901505460351493238411077414937428167\\n\\nAs well as series representations::\\n\\n    >>> pi*log(sqrt(3)+2)/8 + 3*nsum(lambda n:\\n    ...  (fac(n)/(2*n+1))**2/fac(2*n), [0, inf])/8\\n    0.91596559417721901505460351493238411077414937428167\\n    >>> 1-nsum(lambda n: n*zeta(2*n+1)/16**n, [1,inf])\\n    0.91596559417721901505460351493238411077414937428167\\n\\\"\\\"\\\"\\n\\nkhinchin = r\\\"\\\"\\\"\\nKhinchin's constant `K` = 2.68542... is a number that\\nappears in the theory of continued fractions. Mpmath can evaluate\\nit to arbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +khinchin\\n    2.6854520010653064453097148354817956938203822939945\\n\\nAn integral representation is::\\n\\n    >>> I = quad(lambda x: log((1-x**2)/sincpi(x))/x/(1+x), [0, 1])\\n    >>> 2*exp(1/log(2)*I)\\n    2.6854520010653064453097148354817956938203822939945\\n\\nThe computation of ``khinchin`` is based on an efficient\\nimplementation of the following series::\\n\\n    >>> f = lambda n: (zeta(2*n)-1)/n*sum((-1)**(k+1)/mpf(k)\\n    ...     for k in range(1,2*int(n)))\\n    >>> exp(nsum(f, [1,inf])/log(2))\\n    2.6854520010653064453097148354817956938203822939945\\n\\\"\\\"\\\"\\n\\nglaisher = r\\\"\\\"\\\"\\nGlaisher's constant `A`, also known as the Glaisher-Kinkelin\\nconstant, is a number approximately equal to 1.282427129 that\\nsometimes appears in formulas related to gamma and zeta functions.\\nIt is also related to the Barnes G-function (see :func:`~mpmath.barnesg`).\\n\\nThe constant is defined  as `A = \\\\exp(1/12-\\\\zeta'(-1))` where\\n`\\\\zeta'(s)` denotes the derivative of the Riemann zeta function\\n(see :func:`~mpmath.zeta`).\\n\\nMpmath can evaluate Glaisher's constant to arbitrary precision:\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +glaisher\\n    1.282427129100622636875342568869791727767688927325\\n\\nWe can verify that the value computed by :data:`glaisher` is\\ncorrect using mpmath's facilities for numerical\\ndifferentiation and arbitrary evaluation of the zeta function:\\n\\n    >>> exp(mpf(1)/12 - diff(zeta, -1))\\n    1.282427129100622636875342568869791727767688927325\\n\\nHere is an example of an integral that can be evaluated in\\nterms of Glaisher's constant:\\n\\n    >>> mp.dps = 15\\n    >>> quad(lambda x: log(gamma(x)), [1, 1.5])\\n    -0.0428537406502909\\n    >>> -0.5 - 7*log(2)/24 + log(pi)/4 + 3*log(glaisher)/2\\n    -0.042853740650291\\n\\nMpmath computes Glaisher's constant by applying Euler-Maclaurin\\nsummation to a slowly convergent series. The implementation is\\nreasonably efficient up to about 10,000 digits. See the source\\ncode for additional details.\\n\\nReferences:\\nhttp://mathworld.wolfram.com/Glaisher-KinkelinConstant.html\\n\\\"\\\"\\\"\\n\\napery = r\\\"\\\"\\\"\\nRepresents Apery's constant, which is the irrational number\\napproximately equal to 1.2020569 given by\\n\\n.. math ::\\n\\n    \\\\zeta(3) = \\\\sum_{k=1}^\\\\infty\\\\frac{1}{k^3}.\\n\\nThe calculation is based on an efficient hypergeometric\\nseries. To 50 decimal places, the value is given by::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +apery\\n    1.2020569031595942853997381615114499907649862923405\\n\\nOther ways to evaluate Apery's constant using mpmath\\ninclude::\\n\\n    >>> zeta(3)\\n    1.2020569031595942853997381615114499907649862923405\\n    >>> -psi(2,1)/2\\n    1.2020569031595942853997381615114499907649862923405\\n    >>> 8*nsum(lambda k: 1/(2*k+1)**3, [0,inf])/7\\n    1.2020569031595942853997381615114499907649862923405\\n    >>> f = lambda k: 2/k**3/(exp(2*pi*k)-1)\\n    >>> 7*pi**3/180 - nsum(f, [1,inf])\\n    1.2020569031595942853997381615114499907649862923405\\n\\nThis shows digits 9991-10000 of Apery's constant::\\n\\n    >>> mp.dps = 10000\\n    >>> str(apery)[-10:]\\n    '3189504235'\\n\\\"\\\"\\\"\\n\\nmertens = r\\\"\\\"\\\"\\nRepresents the Mertens or Meissel-Mertens constant, which is the\\nprime number analog of Euler's constant:\\n\\n.. math ::\\n\\n    B_1 = \\\\lim_{N\\\\to\\\\infty}\\n        \\\\left(\\\\sum_{p_k \\\\le N} \\\\frac{1}{p_k} - \\\\log \\\\log N \\\\right)\\n\\nHere `p_k` denotes the `k`-th prime number. Other names for this\\nconstant include the Hadamard-de la Vallee-Poussin constant or\\nthe prime reciprocal constant.\\n\\nThe following gives the Mertens constant to 50 digits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +mertens\\n    0.2614972128476427837554268386086958590515666482612\\n\\nReferences:\\nhttp://mathworld.wolfram.com/MertensConstant.html\\n\\\"\\\"\\\"\\n\\ntwinprime = r\\\"\\\"\\\"\\nRepresents the twin prime constant, which is the factor `C_2`\\nfeaturing in the Hardy-Littlewood conjecture for the growth of the\\ntwin prime counting function,\\n\\n.. math ::\\n\\n    \\\\pi_2(n) \\\\sim 2 C_2 \\\\frac{n}{\\\\log^2 n}.\\n\\nIt is given by the product over primes\\n\\n.. math ::\\n\\n    C_2 = \\\\prod_{p\\\\ge3} \\\\frac{p(p-2)}{(p-1)^2} \\\\approx 0.66016\\n\\nComputing `C_2` to 50 digits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> +twinprime\\n    0.66016181584686957392781211001455577843262336028473\\n\\nReferences:\\nhttp://mathworld.wolfram.com/TwinPrimesConstant.html\\n\\\"\\\"\\\"\\n\\nln = r\\\"\\\"\\\"\\nComputes the natural logarithm of `x`, `\\\\ln x`.\\nSee :func:`~mpmath.log` for additional documentation.\\\"\\\"\\\"\\n\\nsqrt = r\\\"\\\"\\\"\\n``sqrt(x)`` gives the principal square root of `x`, `\\\\sqrt x`.\\nFor positive real numbers, the principal root is simply the\\npositive square root. For arbitrary complex numbers, the principal\\nsquare root is defined to satisfy `\\\\sqrt x = \\\\exp(\\\\log(x)/2)`.\\nThe function thus has a branch cut along the negative half real axis.\\n\\nFor all mpmath numbers ``x``, calling ``sqrt(x)`` is equivalent to\\nperforming ``x**0.5``.\\n\\n**Examples**\\n\\nBasic examples and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> sqrt(10)\\n    3.16227766016838\\n    >>> sqrt(100)\\n    10.0\\n    >>> sqrt(-4)\\n    (0.0 + 2.0j)\\n    >>> sqrt(1+1j)\\n    (1.09868411346781 + 0.455089860562227j)\\n    >>> sqrt(inf)\\n    +inf\\n\\nSquare root evaluation is fast at huge precision::\\n\\n    >>> mp.dps = 50000\\n    >>> a = sqrt(3)\\n    >>> str(a)[-10:]\\n    '9329332815'\\n\\n:func:`mpmath.iv.sqrt` supports interval arguments::\\n\\n    >>> iv.dps = 15; iv.pretty = True\\n    >>> iv.sqrt([16,100])\\n    [4.0, 10.0]\\n    >>> iv.sqrt(2)\\n    [1.4142135623730949234, 1.4142135623730951455]\\n    >>> iv.sqrt(2) ** 2\\n    [1.9999999999999995559, 2.0000000000000004441]\\n\\n\\\"\\\"\\\"\\n\\ncbrt = r\\\"\\\"\\\"\\n``cbrt(x)`` computes the cube root of `x`, `x^{1/3}`. This\\nfunction is faster and more accurate than raising to a floating-point\\nfraction::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> 125**(mpf(1)/3)\\n    mpf('4.9999999999999991')\\n    >>> cbrt(125)\\n    mpf('5.0')\\n\\nEvery nonzero complex number has three cube roots. This function\\nreturns the cube root defined by `\\\\exp(\\\\log(x)/3)` where the\\nprincipal branch of the natural logarithm is used. Note that this\\ndoes not give a real cube root for negative real numbers::\\n\\n    >>> mp.pretty = True\\n    >>> cbrt(-1)\\n    (0.5 + 0.866025403784439j)\\n\\\"\\\"\\\"\\n\\nexp = r\\\"\\\"\\\"\\nComputes the exponential function,\\n\\n.. math ::\\n\\n    \\\\exp(x) = e^x = \\\\sum_{k=0}^{\\\\infty} \\\\frac{x^k}{k!}.\\n\\nFor complex numbers, the exponential function also satisfies\\n\\n.. math ::\\n\\n    \\\\exp(x+yi) = e^x (\\\\cos y + i \\\\sin y).\\n\\n**Basic examples**\\n\\nSome values of the exponential function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> exp(0)\\n    1.0\\n    >>> exp(1)\\n    2.718281828459045235360287\\n    >>> exp(-1)\\n    0.3678794411714423215955238\\n    >>> exp(inf)\\n    +inf\\n    >>> exp(-inf)\\n    0.0\\n\\nArguments can be arbitrarily large::\\n\\n    >>> exp(10000)\\n    8.806818225662921587261496e+4342\\n    >>> exp(-10000)\\n    1.135483865314736098540939e-4343\\n\\nEvaluation is supported for interval arguments via\\n:func:`mpmath.iv.exp`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.exp([-inf,0])\\n    [0.0, 1.0]\\n    >>> iv.exp([0,1])\\n    [1.0, 2.71828182845904523536028749558]\\n\\nThe exponential function can be evaluated efficiently to arbitrary\\nprecision::\\n\\n    >>> mp.dps = 10000\\n    >>> exp(pi)  #doctest: +ELLIPSIS\\n    23.140692632779269005729...8984304016040616\\n\\n**Functional properties**\\n\\nNumerical verification of Euler's identity for the complex\\nexponential function::\\n\\n    >>> mp.dps = 15\\n    >>> exp(j*pi)+1\\n    (0.0 + 1.22464679914735e-16j)\\n    >>> chop(exp(j*pi)+1)\\n    0.0\\n\\nThis recovers the coefficients (reciprocal factorials) in the\\nMaclaurin series expansion of exp::\\n\\n    >>> nprint(taylor(exp, 0, 5))\\n    [1.0, 1.0, 0.5, 0.166667, 0.0416667, 0.00833333]\\n\\nThe exponential function is its own derivative and antiderivative::\\n\\n    >>> exp(pi)\\n    23.1406926327793\\n    >>> diff(exp, pi)\\n    23.1406926327793\\n    >>> quad(exp, [-inf, pi])\\n    23.1406926327793\\n\\nThe exponential function can be evaluated using various methods,\\nincluding direct summation of the series, limits, and solving\\nthe defining differential equation::\\n\\n    >>> nsum(lambda k: pi**k/fac(k), [0,inf])\\n    23.1406926327793\\n    >>> limit(lambda k: (1+pi/k)**k, inf)\\n    23.1406926327793\\n    >>> odefun(lambda t, x: x, 0, 1)(pi)\\n    23.1406926327793\\n\\\"\\\"\\\"\\n\\ncosh = r\\\"\\\"\\\"\\nComputes the hyperbolic cosine of `x`,\\n`\\\\cosh(x) = (e^x + e^{-x})/2`. Values and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> cosh(0)\\n    1.0\\n    >>> cosh(1)\\n    1.543080634815243778477906\\n    >>> cosh(-inf), cosh(+inf)\\n    (+inf, +inf)\\n\\nThe hyperbolic cosine is an even, convex function with\\na global minimum at `x = 0`, having a Maclaurin series\\nthat starts::\\n\\n    >>> nprint(chop(taylor(cosh, 0, 5)))\\n    [1.0, 0.0, 0.5, 0.0, 0.0416667, 0.0]\\n\\nGeneralized to complex numbers, the hyperbolic cosine is\\nequivalent to a cosine with the argument rotated\\nin the imaginary direction, or `\\\\cosh x = \\\\cos ix`::\\n\\n    >>> cosh(2+3j)\\n    (-3.724545504915322565473971 + 0.5118225699873846088344638j)\\n    >>> cos(3-2j)\\n    (-3.724545504915322565473971 + 0.5118225699873846088344638j)\\n\\\"\\\"\\\"\\n\\nsinh = r\\\"\\\"\\\"\\nComputes the hyperbolic sine of `x`,\\n`\\\\sinh(x) = (e^x - e^{-x})/2`. Values and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> sinh(0)\\n    0.0\\n    >>> sinh(1)\\n    1.175201193643801456882382\\n    >>> sinh(-inf), sinh(+inf)\\n    (-inf, +inf)\\n\\nThe hyperbolic sine is an odd function, with a Maclaurin\\nseries that starts::\\n\\n    >>> nprint(chop(taylor(sinh, 0, 5)))\\n    [0.0, 1.0, 0.0, 0.166667, 0.0, 0.00833333]\\n\\nGeneralized to complex numbers, the hyperbolic sine is\\nessentially a sine with a rotation `i` applied to\\nthe argument; more precisely, `\\\\sinh x = -i \\\\sin ix`::\\n\\n    >>> sinh(2+3j)\\n    (-3.590564589985779952012565 + 0.5309210862485198052670401j)\\n    >>> j*sin(3-2j)\\n    (-3.590564589985779952012565 + 0.5309210862485198052670401j)\\n\\\"\\\"\\\"\\n\\ntanh = r\\\"\\\"\\\"\\nComputes the hyperbolic tangent of `x`,\\n`\\\\tanh(x) = \\\\sinh(x)/\\\\cosh(x)`. Values and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> tanh(0)\\n    0.0\\n    >>> tanh(1)\\n    0.7615941559557648881194583\\n    >>> tanh(-inf), tanh(inf)\\n    (-1.0, 1.0)\\n\\nThe hyperbolic tangent is an odd, sigmoidal function, similar\\nto the inverse tangent and error function. Its Maclaurin\\nseries is::\\n\\n    >>> nprint(chop(taylor(tanh, 0, 5)))\\n    [0.0, 1.0, 0.0, -0.333333, 0.0, 0.133333]\\n\\nGeneralized to complex numbers, the hyperbolic tangent is\\nessentially a tangent with a rotation `i` applied to\\nthe argument; more precisely, `\\\\tanh x = -i \\\\tan ix`::\\n\\n    >>> tanh(2+3j)\\n    (0.9653858790221331242784803 - 0.009884375038322493720314034j)\\n    >>> j*tan(3-2j)\\n    (0.9653858790221331242784803 - 0.009884375038322493720314034j)\\n\\\"\\\"\\\"\\n\\ncos = r\\\"\\\"\\\"\\nComputes the cosine of `x`, `\\\\cos(x)`.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> cos(pi/3)\\n    0.5\\n    >>> cos(100000001)\\n    -0.9802850113244713353133243\\n    >>> cos(2+3j)\\n    (-4.189625690968807230132555 - 9.109227893755336597979197j)\\n    >>> cos(inf)\\n    nan\\n    >>> nprint(chop(taylor(cos, 0, 6)))\\n    [1.0, 0.0, -0.5, 0.0, 0.0416667, 0.0, -0.00138889]\\n\\nIntervals are supported via :func:`mpmath.iv.cos`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.cos([0,1])\\n    [0.540302305868139717400936602301, 1.0]\\n    >>> iv.cos([0,2])\\n    [-0.41614683654714238699756823214, 1.0]\\n\\\"\\\"\\\"\\n\\nsin = r\\\"\\\"\\\"\\nComputes the sine of `x`, `\\\\sin(x)`.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> sin(pi/3)\\n    0.8660254037844386467637232\\n    >>> sin(100000001)\\n    0.1975887055794968911438743\\n    >>> sin(2+3j)\\n    (9.1544991469114295734673 - 4.168906959966564350754813j)\\n    >>> sin(inf)\\n    nan\\n    >>> nprint(chop(taylor(sin, 0, 6)))\\n    [0.0, 1.0, 0.0, -0.166667, 0.0, 0.00833333, 0.0]\\n\\nIntervals are supported via :func:`mpmath.iv.sin`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.sin([0,1])\\n    [0.0, 0.841470984807896506652502331201]\\n    >>> iv.sin([0,2])\\n    [0.0, 1.0]\\n\\\"\\\"\\\"\\n\\ntan = r\\\"\\\"\\\"\\nComputes the tangent of `x`, `\\\\tan(x) = \\\\frac{\\\\sin(x)}{\\\\cos(x)}`.\\nThe tangent function is singular at `x = (n+1/2)\\\\pi`, but\\n``tan(x)`` always returns a finite result since `(n+1/2)\\\\pi`\\ncannot be represented exactly using floating-point arithmetic.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> tan(pi/3)\\n    1.732050807568877293527446\\n    >>> tan(100000001)\\n    -0.2015625081449864533091058\\n    >>> tan(2+3j)\\n    (-0.003764025641504248292751221 + 1.003238627353609801446359j)\\n    >>> tan(inf)\\n    nan\\n    >>> nprint(chop(taylor(tan, 0, 6)))\\n    [0.0, 1.0, 0.0, 0.333333, 0.0, 0.133333, 0.0]\\n\\nIntervals are supported via :func:`mpmath.iv.tan`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.tan([0,1])\\n    [0.0, 1.55740772465490223050697482944]\\n    >>> iv.tan([0,2])  # Interval includes a singularity\\n    [-inf, +inf]\\n\\\"\\\"\\\"\\n\\nsec = r\\\"\\\"\\\"\\nComputes the secant of `x`, `\\\\mathrm{sec}(x) = \\\\frac{1}{\\\\cos(x)}`.\\nThe secant function is singular at `x = (n+1/2)\\\\pi`, but\\n``sec(x)`` always returns a finite result since `(n+1/2)\\\\pi`\\ncannot be represented exactly using floating-point arithmetic.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> sec(pi/3)\\n    2.0\\n    >>> sec(10000001)\\n    -1.184723164360392819100265\\n    >>> sec(2+3j)\\n    (-0.04167496441114427004834991 + 0.0906111371962375965296612j)\\n    >>> sec(inf)\\n    nan\\n    >>> nprint(chop(taylor(sec, 0, 6)))\\n    [1.0, 0.0, 0.5, 0.0, 0.208333, 0.0, 0.0847222]\\n\\nIntervals are supported via :func:`mpmath.iv.sec`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.sec([0,1])\\n    [1.0, 1.85081571768092561791175326276]\\n    >>> iv.sec([0,2])  # Interval includes a singularity\\n    [-inf, +inf]\\n\\\"\\\"\\\"\\n\\ncsc = r\\\"\\\"\\\"\\nComputes the cosecant of `x`, `\\\\mathrm{csc}(x) = \\\\frac{1}{\\\\sin(x)}`.\\nThis cosecant function is singular at `x = n \\\\pi`, but with the\\nexception of the point `x = 0`, ``csc(x)`` returns a finite result\\nsince `n \\\\pi` cannot be represented exactly using floating-point\\narithmetic.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> csc(pi/3)\\n    1.154700538379251529018298\\n    >>> csc(10000001)\\n    -1.864910497503629858938891\\n    >>> csc(2+3j)\\n    (0.09047320975320743980579048 + 0.04120098628857412646300981j)\\n    >>> csc(inf)\\n    nan\\n\\nIntervals are supported via :func:`mpmath.iv.csc`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.csc([0,1])  # Interval includes a singularity\\n    [1.18839510577812121626159943988, +inf]\\n    >>> iv.csc([0,2])\\n    [1.0, +inf]\\n\\\"\\\"\\\"\\n\\ncot = r\\\"\\\"\\\"\\nComputes the cotangent of `x`,\\n`\\\\mathrm{cot}(x) = \\\\frac{1}{\\\\tan(x)} = \\\\frac{\\\\cos(x)}{\\\\sin(x)}`.\\nThis cotangent function is singular at `x = n \\\\pi`, but with the\\nexception of the point `x = 0`, ``cot(x)`` returns a finite result\\nsince `n \\\\pi` cannot be represented exactly using floating-point\\narithmetic.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> cot(pi/3)\\n    0.5773502691896257645091488\\n    >>> cot(10000001)\\n    1.574131876209625656003562\\n    >>> cot(2+3j)\\n    (-0.003739710376336956660117409 - 0.9967577965693583104609688j)\\n    >>> cot(inf)\\n    nan\\n\\nIntervals are supported via :func:`mpmath.iv.cot`::\\n\\n    >>> iv.dps = 25; iv.pretty = True\\n    >>> iv.cot([0,1])  # Interval includes a singularity\\n    [0.642092615934330703006419974862, +inf]\\n    >>> iv.cot([1,2])\\n    [-inf, +inf]\\n\\\"\\\"\\\"\\n\\nacos = r\\\"\\\"\\\"\\nComputes the inverse cosine or arccosine of `x`, `\\\\cos^{-1}(x)`.\\nSince `-1 \\\\le \\\\cos(x) \\\\le 1` for real `x`, the inverse\\ncosine is real-valued only for `-1 \\\\le x \\\\le 1`. On this interval,\\n:func:`~mpmath.acos` is defined to be a monotonically decreasing\\nfunction assuming values between `+\\\\pi` and `0`.\\n\\nBasic values are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> acos(-1)\\n    3.141592653589793238462643\\n    >>> acos(0)\\n    1.570796326794896619231322\\n    >>> acos(1)\\n    0.0\\n    >>> nprint(chop(taylor(acos, 0, 6)))\\n    [1.5708, -1.0, 0.0, -0.166667, 0.0, -0.075, 0.0]\\n\\n:func:`~mpmath.acos` is defined so as to be a proper inverse function of\\n`\\\\cos(\\\\theta)` for `0 \\\\le \\\\theta < \\\\pi`.\\nWe have `\\\\cos(\\\\cos^{-1}(x)) = x` for all `x`, but\\n`\\\\cos^{-1}(\\\\cos(x)) = x` only for `0 \\\\le \\\\Re[x] < \\\\pi`::\\n\\n    >>> for x in [1, 10, -1, 2+3j, 10+3j]:\\n    ...     print(\\\"%s %s\\\" % (cos(acos(x)), acos(cos(x))))\\n    ...\\n    1.0 1.0\\n    (10.0 + 0.0j) 2.566370614359172953850574\\n    -1.0 1.0\\n    (2.0 + 3.0j) (2.0 + 3.0j)\\n    (10.0 + 3.0j) (2.566370614359172953850574 - 3.0j)\\n\\nThe inverse cosine has two branch points: `x = \\\\pm 1`. :func:`~mpmath.acos`\\nplaces the branch cuts along the line segments `(-\\\\infty, -1)` and\\n`(+1, +\\\\infty)`. In general,\\n\\n.. math ::\\n\\n    \\\\cos^{-1}(x) = \\\\frac{\\\\pi}{2} + i \\\\log\\\\left(ix + \\\\sqrt{1-x^2} \\\\right)\\n\\nwhere the principal-branch log and square root are implied.\\n\\\"\\\"\\\"\\n\\nasin = r\\\"\\\"\\\"\\nComputes the inverse sine or arcsine of `x`, `\\\\sin^{-1}(x)`.\\nSince `-1 \\\\le \\\\sin(x) \\\\le 1` for real `x`, the inverse\\nsine is real-valued only for `-1 \\\\le x \\\\le 1`.\\nOn this interval, it is defined to be a monotonically increasing\\nfunction assuming values between `-\\\\pi/2` and `\\\\pi/2`.\\n\\nBasic values are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> asin(-1)\\n    -1.570796326794896619231322\\n    >>> asin(0)\\n    0.0\\n    >>> asin(1)\\n    1.570796326794896619231322\\n    >>> nprint(chop(taylor(asin, 0, 6)))\\n    [0.0, 1.0, 0.0, 0.166667, 0.0, 0.075, 0.0]\\n\\n:func:`~mpmath.asin` is defined so as to be a proper inverse function of\\n`\\\\sin(\\\\theta)` for `-\\\\pi/2 < \\\\theta < \\\\pi/2`.\\nWe have `\\\\sin(\\\\sin^{-1}(x)) = x` for all `x`, but\\n`\\\\sin^{-1}(\\\\sin(x)) = x` only for `-\\\\pi/2 < \\\\Re[x] < \\\\pi/2`::\\n\\n    >>> for x in [1, 10, -1, 1+3j, -2+3j]:\\n    ...     print(\\\"%s %s\\\" % (chop(sin(asin(x))), asin(sin(x))))\\n    ...\\n    1.0 1.0\\n    10.0 -0.5752220392306202846120698\\n    -1.0 -1.0\\n    (1.0 + 3.0j) (1.0 + 3.0j)\\n    (-2.0 + 3.0j) (-1.141592653589793238462643 - 3.0j)\\n\\nThe inverse sine has two branch points: `x = \\\\pm 1`. :func:`~mpmath.asin`\\nplaces the branch cuts along the line segments `(-\\\\infty, -1)` and\\n`(+1, +\\\\infty)`. In general,\\n\\n.. math ::\\n\\n    \\\\sin^{-1}(x) = -i \\\\log\\\\left(ix + \\\\sqrt{1-x^2} \\\\right)\\n\\nwhere the principal-branch log and square root are implied.\\n\\\"\\\"\\\"\\n\\natan = r\\\"\\\"\\\"\\nComputes the inverse tangent or arctangent of `x`, `\\\\tan^{-1}(x)`.\\nThis is a real-valued function for all real `x`, with range\\n`(-\\\\pi/2, \\\\pi/2)`.\\n\\nBasic values are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> atan(-inf)\\n    -1.570796326794896619231322\\n    >>> atan(-1)\\n    -0.7853981633974483096156609\\n    >>> atan(0)\\n    0.0\\n    >>> atan(1)\\n    0.7853981633974483096156609\\n    >>> atan(inf)\\n    1.570796326794896619231322\\n    >>> nprint(chop(taylor(atan, 0, 6)))\\n    [0.0, 1.0, 0.0, -0.333333, 0.0, 0.2, 0.0]\\n\\nThe inverse tangent is often used to compute angles. However,\\nthe atan2 function is often better for this as it preserves sign\\n(see :func:`~mpmath.atan2`).\\n\\n:func:`~mpmath.atan` is defined so as to be a proper inverse function of\\n`\\\\tan(\\\\theta)` for `-\\\\pi/2 < \\\\theta < \\\\pi/2`.\\nWe have `\\\\tan(\\\\tan^{-1}(x)) = x` for all `x`, but\\n`\\\\tan^{-1}(\\\\tan(x)) = x` only for `-\\\\pi/2 < \\\\Re[x] < \\\\pi/2`::\\n\\n    >>> mp.dps = 25\\n    >>> for x in [1, 10, -1, 1+3j, -2+3j]:\\n    ...     print(\\\"%s %s\\\" % (tan(atan(x)), atan(tan(x))))\\n    ...\\n    1.0 1.0\\n    10.0 0.5752220392306202846120698\\n    -1.0 -1.0\\n    (1.0 + 3.0j) (1.000000000000000000000001 + 3.0j)\\n    (-2.0 + 3.0j) (1.141592653589793238462644 + 3.0j)\\n\\nThe inverse tangent has two branch points: `x = \\\\pm i`. :func:`~mpmath.atan`\\nplaces the branch cuts along the line segments `(-i \\\\infty, -i)` and\\n`(+i, +i \\\\infty)`. In general,\\n\\n.. math ::\\n\\n    \\\\tan^{-1}(x) = \\\\frac{i}{2}\\\\left(\\\\log(1-ix)-\\\\log(1+ix)\\\\right)\\n\\nwhere the principal-branch log is implied.\\n\\\"\\\"\\\"\\n\\nacot = r\\\"\\\"\\\"Computes the inverse cotangent of `x`,\\n`\\\\mathrm{cot}^{-1}(x) = \\\\tan^{-1}(1/x)`.\\\"\\\"\\\"\\n\\nasec = r\\\"\\\"\\\"Computes the inverse secant of `x`,\\n`\\\\mathrm{sec}^{-1}(x) = \\\\cos^{-1}(1/x)`.\\\"\\\"\\\"\\n\\nacsc = r\\\"\\\"\\\"Computes the inverse cosecant of `x`,\\n`\\\\mathrm{csc}^{-1}(x) = \\\\sin^{-1}(1/x)`.\\\"\\\"\\\"\\n\\ncoth = r\\\"\\\"\\\"Computes the hyperbolic cotangent of `x`,\\n`\\\\mathrm{coth}(x) = \\\\frac{\\\\cosh(x)}{\\\\sinh(x)}`.\\n\\\"\\\"\\\"\\n\\nsech = r\\\"\\\"\\\"Computes the hyperbolic secant of `x`,\\n`\\\\mathrm{sech}(x) = \\\\frac{1}{\\\\cosh(x)}`.\\n\\\"\\\"\\\"\\n\\ncsch = r\\\"\\\"\\\"Computes the hyperbolic cosecant of `x`,\\n`\\\\mathrm{csch}(x) = \\\\frac{1}{\\\\sinh(x)}`.\\n\\\"\\\"\\\"\\n\\nacosh = r\\\"\\\"\\\"Computes the inverse hyperbolic cosine of `x`,\\n`\\\\mathrm{cosh}^{-1}(x) = \\\\log(x+\\\\sqrt{x+1}\\\\sqrt{x-1})`.\\n\\\"\\\"\\\"\\n\\nasinh = r\\\"\\\"\\\"Computes the inverse hyperbolic sine of `x`,\\n`\\\\mathrm{sinh}^{-1}(x) = \\\\log(x+\\\\sqrt{1+x^2})`.\\n\\\"\\\"\\\"\\n\\natanh = r\\\"\\\"\\\"Computes the inverse hyperbolic tangent of `x`,\\n`\\\\mathrm{tanh}^{-1}(x) = \\\\frac{1}{2}\\\\left(\\\\log(1+x)-\\\\log(1-x)\\\\right)`.\\n\\\"\\\"\\\"\\n\\nacoth = r\\\"\\\"\\\"Computes the inverse hyperbolic cotangent of `x`,\\n`\\\\mathrm{coth}^{-1}(x) = \\\\tanh^{-1}(1/x)`.\\\"\\\"\\\"\\n\\nasech = r\\\"\\\"\\\"Computes the inverse hyperbolic secant of `x`,\\n`\\\\mathrm{sech}^{-1}(x) = \\\\cosh^{-1}(1/x)`.\\\"\\\"\\\"\\n\\nacsch = r\\\"\\\"\\\"Computes the inverse hyperbolic cosecant of `x`,\\n`\\\\mathrm{csch}^{-1}(x) = \\\\sinh^{-1}(1/x)`.\\\"\\\"\\\"\\n\\n\\n\\nsinpi = r\\\"\\\"\\\"\\nComputes `\\\\sin(\\\\pi x)`, more accurately than the expression\\n``sin(pi*x)``::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> sinpi(10**10), sin(pi*(10**10))\\n    (0.0, -2.23936276195592e-6)\\n    >>> sinpi(10**10+0.5), sin(pi*(10**10+0.5))\\n    (1.0, 0.999999999998721)\\n\\\"\\\"\\\"\\n\\ncospi = r\\\"\\\"\\\"\\nComputes `\\\\cos(\\\\pi x)`, more accurately than the expression\\n``cos(pi*x)``::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> cospi(10**10), cos(pi*(10**10))\\n    (1.0, 0.999999999997493)\\n    >>> cospi(10**10+0.5), cos(pi*(10**10+0.5))\\n    (0.0, 1.59960492420134e-6)\\n\\\"\\\"\\\"\\n\\nsinc = r\\\"\\\"\\\"\\n``sinc(x)`` computes the unnormalized sinc function, defined as\\n\\n.. math ::\\n\\n    \\\\mathrm{sinc}(x) = \\\\begin{cases}\\n        \\\\sin(x)/x, & \\\\mbox{if } x \\\\ne 0 \\\\\\\\\\n        1,         & \\\\mbox{if } x = 0.\\n    \\\\end{cases}\\n\\nSee :func:`~mpmath.sincpi` for the normalized sinc function.\\n\\nSimple values and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> sinc(0)\\n    1.0\\n    >>> sinc(1)\\n    0.841470984807897\\n    >>> sinc(inf)\\n    0.0\\n\\nThe integral of the sinc function is the sine integral Si::\\n\\n    >>> quad(sinc, [0, 1])\\n    0.946083070367183\\n    >>> si(1)\\n    0.946083070367183\\n\\\"\\\"\\\"\\n\\nsincpi = r\\\"\\\"\\\"\\n``sincpi(x)`` computes the normalized sinc function, defined as\\n\\n.. math ::\\n\\n    \\\\mathrm{sinc}_{\\\\pi}(x) = \\\\begin{cases}\\n        \\\\sin(\\\\pi x)/(\\\\pi x), & \\\\mbox{if } x \\\\ne 0 \\\\\\\\\\n        1,                   & \\\\mbox{if } x = 0.\\n    \\\\end{cases}\\n\\nEquivalently, we have\\n`\\\\mathrm{sinc}_{\\\\pi}(x) = \\\\mathrm{sinc}(\\\\pi x)`.\\n\\nThe normalization entails that the function integrates\\nto unity over the entire real line::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> quadosc(sincpi, [-inf, inf], period=2.0)\\n    1.0\\n\\nLike, :func:`~mpmath.sinpi`, :func:`~mpmath.sincpi` is evaluated accurately\\nat its roots::\\n\\n    >>> sincpi(10)\\n    0.0\\n\\\"\\\"\\\"\\n\\nexpj = r\\\"\\\"\\\"\\nConvenience function for computing `e^{ix}`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> expj(0)\\n    (1.0 + 0.0j)\\n    >>> expj(-1)\\n    (0.5403023058681397174009366 - 0.8414709848078965066525023j)\\n    >>> expj(j)\\n    (0.3678794411714423215955238 + 0.0j)\\n    >>> expj(1+j)\\n    (0.1987661103464129406288032 + 0.3095598756531121984439128j)\\n\\\"\\\"\\\"\\n\\nexpjpi = r\\\"\\\"\\\"\\nConvenience function for computing `e^{i \\\\pi x}`.\\nEvaluation is accurate near zeros (see also :func:`~mpmath.cospi`,\\n:func:`~mpmath.sinpi`)::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> expjpi(0)\\n    (1.0 + 0.0j)\\n    >>> expjpi(1)\\n    (-1.0 + 0.0j)\\n    >>> expjpi(0.5)\\n    (0.0 + 1.0j)\\n    >>> expjpi(-1)\\n    (-1.0 + 0.0j)\\n    >>> expjpi(j)\\n    (0.04321391826377224977441774 + 0.0j)\\n    >>> expjpi(1+j)\\n    (-0.04321391826377224977441774 + 0.0j)\\n\\\"\\\"\\\"\\n\\nfloor = r\\\"\\\"\\\"\\nComputes the floor of `x`, `\\\\lfloor x \\\\rfloor`, defined as\\nthe largest integer less than or equal to `x`::\\n\\n    >>> from mpmath import *\\n    >>> mp.pretty = False\\n    >>> floor(3.5)\\n    mpf('3.0')\\n\\n.. note ::\\n\\n    :func:`~mpmath.floor`, :func:`~mpmath.ceil` and :func:`~mpmath.nint` return a\\n    floating-point number, not a Python ``int``. If `\\\\lfloor x \\\\rfloor` is\\n    too large to be represented exactly at the present working precision,\\n    the result will be rounded, not necessarily in the direction\\n    implied by the mathematical definition of the function.\\n\\nTo avoid rounding, use *prec=0*::\\n\\n    >>> mp.dps = 15\\n    >>> print(int(floor(10**30+1)))\\n    1000000000000000019884624838656\\n    >>> print(int(floor(10**30+1, prec=0)))\\n    1000000000000000000000000000001\\n\\nThe floor function is defined for complex numbers and\\nacts on the real and imaginary parts separately::\\n\\n    >>> floor(3.25+4.75j)\\n    mpc(real='3.0', imag='4.0')\\n\\\"\\\"\\\"\\n\\nceil = r\\\"\\\"\\\"\\nComputes the ceiling of `x`, `\\\\lceil x \\\\rceil`, defined as\\nthe smallest integer greater than or equal to `x`::\\n\\n    >>> from mpmath import *\\n    >>> mp.pretty = False\\n    >>> ceil(3.5)\\n    mpf('4.0')\\n\\nThe ceiling function is defined for complex numbers and\\nacts on the real and imaginary parts separately::\\n\\n    >>> ceil(3.25+4.75j)\\n    mpc(real='4.0', imag='5.0')\\n\\nSee notes about rounding for :func:`~mpmath.floor`.\\n\\\"\\\"\\\"\\n\\nnint = r\\\"\\\"\\\"\\nEvaluates the nearest integer function, `\\\\mathrm{nint}(x)`.\\nThis gives the nearest integer to `x`; on a tie, it\\ngives the nearest even integer::\\n\\n    >>> from mpmath import *\\n    >>> mp.pretty = False\\n    >>> nint(3.2)\\n    mpf('3.0')\\n    >>> nint(3.8)\\n    mpf('4.0')\\n    >>> nint(3.5)\\n    mpf('4.0')\\n    >>> nint(4.5)\\n    mpf('4.0')\\n\\nThe nearest integer function is defined for complex numbers and\\nacts on the real and imaginary parts separately::\\n\\n    >>> nint(3.25+4.75j)\\n    mpc(real='3.0', imag='5.0')\\n\\nSee notes about rounding for :func:`~mpmath.floor`.\\n\\\"\\\"\\\"\\n\\nfrac = r\\\"\\\"\\\"\\nGives the fractional part of `x`, defined as\\n`\\\\mathrm{frac}(x) = x - \\\\lfloor x \\\\rfloor` (see :func:`~mpmath.floor`).\\nIn effect, this computes `x` modulo 1, or `x+n` where\\n`n \\\\in \\\\mathbb{Z}` is such that `x+n \\\\in [0,1)`::\\n\\n    >>> from mpmath import *\\n    >>> mp.pretty = False\\n    >>> frac(1.25)\\n    mpf('0.25')\\n    >>> frac(3)\\n    mpf('0.0')\\n    >>> frac(-1.25)\\n    mpf('0.75')\\n\\nFor a complex number, the fractional part function applies to\\nthe real and imaginary parts separately::\\n\\n    >>> frac(2.25+3.75j)\\n    mpc(real='0.25', imag='0.75')\\n\\nPlotted, the fractional part function gives a sawtooth\\nwave. The Fourier series coefficients have a simple\\nform::\\n\\n    >>> mp.dps = 15\\n    >>> nprint(fourier(lambda x: frac(x)-0.5, [0,1], 4))\\n    ([0.0, 0.0, 0.0, 0.0, 0.0], [0.0, -0.31831, -0.159155, -0.106103, -0.0795775])\\n    >>> nprint([-1/(pi*k) for k in range(1,5)])\\n    [-0.31831, -0.159155, -0.106103, -0.0795775]\\n\\n.. note::\\n\\n    The fractional part is sometimes defined as a symmetric\\n    function, i.e. returning `-\\\\mathrm{frac}(-x)` if `x < 0`.\\n    This convention is used, for instance, by Mathematica's\\n    ``FractionalPart``.\\n\\n\\\"\\\"\\\"\\n\\nsign = r\\\"\\\"\\\"\\nReturns the sign of `x`, defined as `\\\\mathrm{sign}(x) = x / |x|`\\n(with the special case `\\\\mathrm{sign}(0) = 0`)::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> sign(10)\\n    mpf('1.0')\\n    >>> sign(-10)\\n    mpf('-1.0')\\n    >>> sign(0)\\n    mpf('0.0')\\n\\nNote that the sign function is also defined for complex numbers,\\nfor which it gives the projection onto the unit circle::\\n\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> sign(1+j)\\n    (0.707106781186547 + 0.707106781186547j)\\n\\n\\\"\\\"\\\"\\n\\narg = r\\\"\\\"\\\"\\nComputes the complex argument (phase) of `x`, defined as the\\nsigned angle between the positive real axis and `x` in the\\ncomplex plane::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> arg(3)\\n    0.0\\n    >>> arg(3+3j)\\n    0.785398163397448\\n    >>> arg(3j)\\n    1.5707963267949\\n    >>> arg(-3)\\n    3.14159265358979\\n    >>> arg(-3j)\\n    -1.5707963267949\\n\\nThe angle is defined to satisfy `-\\\\pi < \\\\arg(x) \\\\le \\\\pi` and\\nwith the sign convention that a nonnegative imaginary part\\nresults in a nonnegative argument.\\n\\nThe value returned by :func:`~mpmath.arg` is an ``mpf`` instance.\\n\\\"\\\"\\\"\\n\\nfabs = r\\\"\\\"\\\"\\nReturns the absolute value of `x`, `|x|`. Unlike :func:`abs`,\\n:func:`~mpmath.fabs` converts non-mpmath numbers (such as ``int``)\\ninto mpmath numbers::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> fabs(3)\\n    mpf('3.0')\\n    >>> fabs(-3)\\n    mpf('3.0')\\n    >>> fabs(3+4j)\\n    mpf('5.0')\\n\\\"\\\"\\\"\\n\\nre = r\\\"\\\"\\\"\\nReturns the real part of `x`, `\\\\Re(x)`. :func:`~mpmath.re`\\nconverts a non-mpmath number to an mpmath number::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> re(3)\\n    mpf('3.0')\\n    >>> re(-1+4j)\\n    mpf('-1.0')\\n\\\"\\\"\\\"\\n\\nim = r\\\"\\\"\\\"\\nReturns the imaginary part of `x`, `\\\\Im(x)`. :func:`~mpmath.im`\\nconverts a non-mpmath number to an mpmath number::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> im(3)\\n    mpf('0.0')\\n    >>> im(-1+4j)\\n    mpf('4.0')\\n\\\"\\\"\\\"\\n\\nconj = r\\\"\\\"\\\"\\nReturns the complex conjugate of `x`, `\\\\overline{x}`. Unlike\\n``x.conjugate()``, :func:`~mpmath.im` converts `x` to a mpmath number::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> conj(3)\\n    mpf('3.0')\\n    >>> conj(-1+4j)\\n    mpc(real='-1.0', imag='-4.0')\\n\\\"\\\"\\\"\\n\\npolar = r\\\"\\\"\\\"\\nReturns the polar representation of the complex number `z`\\nas a pair `(r, \\\\phi)` such that `z = r e^{i \\\\phi}`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> polar(-2)\\n    (2.0, 3.14159265358979)\\n    >>> polar(3-4j)\\n    (5.0, -0.927295218001612)\\n\\\"\\\"\\\"\\n\\nrect = r\\\"\\\"\\\"\\nReturns the complex number represented by polar\\ncoordinates `(r, \\\\phi)`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> chop(rect(2, pi))\\n    -2.0\\n    >>> rect(sqrt(2), -pi/4)\\n    (1.0 - 1.0j)\\n\\\"\\\"\\\"\\n\\nexpm1 = r\\\"\\\"\\\"\\nComputes `e^x - 1`, accurately for small `x`.\\n\\nUnlike the expression ``exp(x) - 1``, ``expm1(x)`` does not suffer from\\npotentially catastrophic cancellation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> exp(1e-10)-1; print(expm1(1e-10))\\n    1.00000008274037e-10\\n    1.00000000005e-10\\n    >>> exp(1e-20)-1; print(expm1(1e-20))\\n    0.0\\n    1.0e-20\\n    >>> 1/(exp(1e-20)-1)\\n    Traceback (most recent call last):\\n      ...\\n    ZeroDivisionError\\n    >>> 1/expm1(1e-20)\\n    1.0e+20\\n\\nEvaluation works for extremely tiny values::\\n\\n    >>> expm1(0)\\n    0.0\\n    >>> expm1('1e-10000000')\\n    1.0e-10000000\\n\\n\\\"\\\"\\\"\\n\\nlog1p = r\\\"\\\"\\\"\\nComputes `\\\\log(1+x)`, accurately for small `x`.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> log(1+1e-10); print(mp.log1p(1e-10))\\n    1.00000008269037e-10\\n    9.9999999995e-11\\n    >>> mp.log1p(1e-100j)\\n    (5.0e-201 + 1.0e-100j)\\n    >>> mp.log1p(0)\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\n\\npowm1 = r\\\"\\\"\\\"\\nComputes `x^y - 1`, accurately when `x^y` is very close to 1.\\n\\nThis avoids potentially catastrophic cancellation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> power(0.99999995, 1e-10) - 1\\n    0.0\\n    >>> powm1(0.99999995, 1e-10)\\n    -5.00000012791934e-18\\n\\nPowers exactly equal to 1, and only those powers, yield 0 exactly::\\n\\n    >>> powm1(-j, 4)\\n    (0.0 + 0.0j)\\n    >>> powm1(3, 0)\\n    0.0\\n    >>> powm1(fadd(-1, 1e-100, exact=True), 4)\\n    -4.0e-100\\n\\nEvaluation works for extremely tiny `y`::\\n\\n    >>> powm1(2, '1e-100000')\\n    6.93147180559945e-100001\\n    >>> powm1(j, '1e-1000')\\n    (-1.23370055013617e-2000 + 1.5707963267949e-1000j)\\n\\n\\\"\\\"\\\"\\n\\nroot = r\\\"\\\"\\\"\\n``root(z, n, k=0)`` computes an `n`-th root of `z`, i.e. returns a number\\n`r` that (up to possible approximation error) satisfies `r^n = z`.\\n(``nthroot`` is available as an alias for ``root``.)\\n\\nEvery complex number `z \\\\ne 0` has `n` distinct `n`-th roots, which are\\nequidistant points on a circle with radius `|z|^{1/n}`, centered around the\\norigin. A specific root may be selected using the optional index\\n`k`. The roots are indexed counterclockwise, starting with `k = 0` for the root\\nclosest to the positive real half-axis.\\n\\nThe `k = 0` root is the so-called principal `n`-th root, often denoted by\\n`\\\\sqrt[n]{z}` or `z^{1/n}`, and also given by `\\\\exp(\\\\log(z) / n)`. If `z` is\\na positive real number, the principal root is just the unique positive\\n`n`-th root of `z`. Under some circumstances, non-principal real roots exist:\\nfor positive real `z`, `n` even, there is a negative root given by `k = n/2`;\\nfor negative real `z`, `n` odd, there is a negative root given by `k = (n-1)/2`.\\n\\nTo obtain all roots with a simple expression, use\\n``[root(z,n,k) for k in range(n)]``.\\n\\nAn important special case, ``root(1, n, k)`` returns the `k`-th `n`-th root of\\nunity, `\\\\zeta_k = e^{2 \\\\pi i k / n}`. Alternatively, :func:`~mpmath.unitroots`\\nprovides a slightly more convenient way to obtain the roots of unity,\\nincluding the option to compute only the primitive roots of unity.\\n\\nBoth `k` and `n` should be integers; `k` outside of ``range(n)`` will be\\nreduced modulo `n`. If `n` is negative, `x^{-1/n} = 1/x^{1/n}` (or\\nthe equivalent reciprocal for a non-principal root with `k \\\\ne 0`) is computed.\\n\\n:func:`~mpmath.root` is implemented to use Newton's method for small\\n`n`. At high precision, this makes `x^{1/n}` not much more\\nexpensive than the regular exponentiation, `x^n`. For very large\\n`n`, :func:`~mpmath.nthroot` falls back to use the exponential function.\\n\\n**Examples**\\n\\n:func:`~mpmath.nthroot`/:func:`~mpmath.root` is faster and more accurate than raising to a\\nfloating-point fraction::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = False\\n    >>> 16807 ** (mpf(1)/5)\\n    mpf('7.0000000000000009')\\n    >>> root(16807, 5)\\n    mpf('7.0')\\n    >>> nthroot(16807, 5)    # Alias\\n    mpf('7.0')\\n\\nA high-precision root::\\n\\n    >>> mp.dps = 50; mp.pretty = True\\n    >>> nthroot(10, 5)\\n    1.584893192461113485202101373391507013269442133825\\n    >>> nthroot(10, 5) ** 5\\n    10.0\\n\\nComputing principal and non-principal square and cube roots::\\n\\n    >>> mp.dps = 15\\n    >>> root(10, 2)\\n    3.16227766016838\\n    >>> root(10, 2, 1)\\n    -3.16227766016838\\n    >>> root(-10, 3)\\n    (1.07721734501594 + 1.86579517236206j)\\n    >>> root(-10, 3, 1)\\n    -2.15443469003188\\n    >>> root(-10, 3, 2)\\n    (1.07721734501594 - 1.86579517236206j)\\n\\nAll the 7th roots of a complex number::\\n\\n    >>> for r in [root(3+4j, 7, k) for k in range(7)]:\\n    ...     print(\\\"%s %s\\\" % (r, r**7))\\n    ...\\n    (1.24747270589553 + 0.166227124177353j) (3.0 + 4.0j)\\n    (0.647824911301003 + 1.07895435170559j) (3.0 + 4.0j)\\n    (-0.439648254723098 + 1.17920694574172j) (3.0 + 4.0j)\\n    (-1.19605731775069 + 0.391492658196305j) (3.0 + 4.0j)\\n    (-1.05181082538903 - 0.691023585965793j) (3.0 + 4.0j)\\n    (-0.115529328478668 - 1.25318497558335j) (3.0 + 4.0j)\\n    (0.907748109144957 - 0.871672518271819j) (3.0 + 4.0j)\\n\\nCube roots of unity::\\n\\n    >>> for k in range(3): print(root(1, 3, k))\\n    ...\\n    1.0\\n    (-0.5 + 0.866025403784439j)\\n    (-0.5 - 0.866025403784439j)\\n\\nSome exact high order roots::\\n\\n    >>> root(75**210, 105)\\n    5625.0\\n    >>> root(1, 128, 96)\\n    (0.0 - 1.0j)\\n    >>> root(4**128, 128, 96)\\n    (0.0 - 4.0j)\\n\\n\\\"\\\"\\\"\\n\\nunitroots = r\\\"\\\"\\\"\\n``unitroots(n)`` returns `\\\\zeta_0, \\\\zeta_1, \\\\ldots, \\\\zeta_{n-1}`,\\nall the distinct `n`-th roots of unity, as a list. If the option\\n*primitive=True* is passed, only the primitive roots are returned.\\n\\nEvery `n`-th root of unity satisfies `(\\\\zeta_k)^n = 1`. There are `n` distinct\\nroots for each `n` (`\\\\zeta_k` and `\\\\zeta_j` are the same when\\n`k = j \\\\pmod n`), which form a regular polygon with vertices on the unit\\ncircle. They are ordered counterclockwise with increasing `k`, starting\\nwith `\\\\zeta_0 = 1`.\\n\\n**Examples**\\n\\nThe roots of unity up to `n = 4`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> nprint(unitroots(1))\\n    [1.0]\\n    >>> nprint(unitroots(2))\\n    [1.0, -1.0]\\n    >>> nprint(unitroots(3))\\n    [1.0, (-0.5 + 0.866025j), (-0.5 - 0.866025j)]\\n    >>> nprint(unitroots(4))\\n    [1.0, (0.0 + 1.0j), -1.0, (0.0 - 1.0j)]\\n\\nRoots of unity form a geometric series that sums to 0::\\n\\n    >>> mp.dps = 50\\n    >>> chop(fsum(unitroots(25)))\\n    0.0\\n\\nPrimitive roots up to `n = 4`::\\n\\n    >>> mp.dps = 15\\n    >>> nprint(unitroots(1, primitive=True))\\n    [1.0]\\n    >>> nprint(unitroots(2, primitive=True))\\n    [-1.0]\\n    >>> nprint(unitroots(3, primitive=True))\\n    [(-0.5 + 0.866025j), (-0.5 - 0.866025j)]\\n    >>> nprint(unitroots(4, primitive=True))\\n    [(0.0 + 1.0j), (0.0 - 1.0j)]\\n\\nThere are only four primitive 12th roots::\\n\\n    >>> nprint(unitroots(12, primitive=True))\\n    [(0.866025 + 0.5j), (-0.866025 + 0.5j), (-0.866025 - 0.5j), (0.866025 - 0.5j)]\\n\\nThe `n`-th roots of unity form a group, the cyclic group of order `n`.\\nAny primitive root `r` is a generator for this group, meaning that\\n`r^0, r^1, \\\\ldots, r^{n-1}` gives the whole set of unit roots (in\\nsome permuted order)::\\n\\n    >>> for r in unitroots(6): print(r)\\n    ...\\n    1.0\\n    (0.5 + 0.866025403784439j)\\n    (-0.5 + 0.866025403784439j)\\n    -1.0\\n    (-0.5 - 0.866025403784439j)\\n    (0.5 - 0.866025403784439j)\\n    >>> r = unitroots(6, primitive=True)[1]\\n    >>> for k in range(6): print(chop(r**k))\\n    ...\\n    1.0\\n    (0.5 - 0.866025403784439j)\\n    (-0.5 - 0.866025403784439j)\\n    -1.0\\n    (-0.5 + 0.866025403784438j)\\n    (0.5 + 0.866025403784438j)\\n\\nThe number of primitive roots equals the Euler totient function `\\\\phi(n)`::\\n\\n    >>> [len(unitroots(n, primitive=True)) for n in range(1,20)]\\n    [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6, 18]\\n\\n\\\"\\\"\\\"\\n\\n\\nlog = r\\\"\\\"\\\"\\nComputes the base-`b` logarithm of `x`, `\\\\log_b(x)`. If `b` is\\nunspecified, :func:`~mpmath.log` computes the natural (base `e`) logarithm\\nand is equivalent to :func:`~mpmath.ln`. In general, the base `b` logarithm\\nis defined in terms of the natural logarithm as\\n`\\\\log_b(x) = \\\\ln(x)/\\\\ln(b)`.\\n\\nBy convention, we take `\\\\log(0) = -\\\\infty`.\\n\\nThe natural logarithm is real if `x > 0` and complex if `x < 0` or if\\n`x` is complex. The principal branch of the complex logarithm is\\nused, meaning that `\\\\Im(\\\\ln(x)) = -\\\\pi < \\\\arg(x) \\\\le \\\\pi`.\\n\\n**Examples**\\n\\nSome basic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> log(1)\\n    0.0\\n    >>> log(2)\\n    0.693147180559945\\n    >>> log(1000,10)\\n    3.0\\n    >>> log(4, 16)\\n    0.5\\n    >>> log(j)\\n    (0.0 + 1.5707963267949j)\\n    >>> log(-1)\\n    (0.0 + 3.14159265358979j)\\n    >>> log(0)\\n    -inf\\n    >>> log(inf)\\n    +inf\\n\\nThe natural logarithm is the antiderivative of `1/x`::\\n\\n    >>> quad(lambda x: 1/x, [1, 5])\\n    1.6094379124341\\n    >>> log(5)\\n    1.6094379124341\\n    >>> diff(log, 10)\\n    0.1\\n\\nThe Taylor series expansion of the natural logarithm around\\n`x = 1` has coefficients `(-1)^{n+1}/n`::\\n\\n    >>> nprint(taylor(log, 1, 7))\\n    [0.0, 1.0, -0.5, 0.333333, -0.25, 0.2, -0.166667, 0.142857]\\n\\n:func:`~mpmath.log` supports arbitrary precision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> log(pi)\\n    1.1447298858494001741434273513530587116472948129153\\n    >>> log(pi, pi**3)\\n    0.33333333333333333333333333333333333333333333333333\\n    >>> mp.dps = 25\\n    >>> log(3+4j)\\n    (1.609437912434100374600759 + 0.9272952180016122324285125j)\\n\\\"\\\"\\\"\\n\\nlog10 = r\\\"\\\"\\\"\\nComputes the base-10 logarithm of `x`, `\\\\log_{10}(x)`. ``log10(x)``\\nis equivalent to ``log(x, 10)``.\\n\\\"\\\"\\\"\\n\\nfmod = r\\\"\\\"\\\"\\nConverts `x` and `y` to mpmath numbers and returns `x \\\\mod y`.\\nFor mpmath numbers, this is equivalent to ``x % y``.\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> fmod(100, pi)\\n    2.61062773871641\\n\\nYou can use :func:`~mpmath.fmod` to compute fractional parts of numbers::\\n\\n    >>> fmod(10.25, 1)\\n    0.25\\n\\n\\\"\\\"\\\"\\n\\nradians = r\\\"\\\"\\\"\\nConverts the degree angle `x` to radians::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> radians(60)\\n    1.0471975511966\\n\\\"\\\"\\\"\\n\\ndegrees = r\\\"\\\"\\\"\\nConverts the radian angle `x` to a degree angle::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> degrees(pi/3)\\n    60.0\\n\\\"\\\"\\\"\\n\\natan2 = r\\\"\\\"\\\"\\nComputes the two-argument arctangent, `\\\\mathrm{atan2}(y, x)`,\\ngiving the signed angle between the positive `x`-axis and the\\npoint `(x, y)` in the 2D plane. This function is defined for\\nreal `x` and `y` only.\\n\\nThe two-argument arctangent essentially computes\\n`\\\\mathrm{atan}(y/x)`, but accounts for the signs of both\\n`x` and `y` to give the angle for the correct quadrant. The\\nfollowing examples illustrate the difference::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> atan2(1,1), atan(1/1.)\\n    (0.785398163397448, 0.785398163397448)\\n    >>> atan2(1,-1), atan(1/-1.)\\n    (2.35619449019234, -0.785398163397448)\\n    >>> atan2(-1,1), atan(-1/1.)\\n    (-0.785398163397448, -0.785398163397448)\\n    >>> atan2(-1,-1), atan(-1/-1.)\\n    (-2.35619449019234, 0.785398163397448)\\n\\nThe angle convention is the same as that used for the complex\\nargument; see :func:`~mpmath.arg`.\\n\\\"\\\"\\\"\\n\\nfibonacci = r\\\"\\\"\\\"\\n``fibonacci(n)`` computes the `n`-th Fibonacci number, `F(n)`. The\\nFibonacci numbers are defined by the recurrence `F(n) = F(n-1) + F(n-2)`\\nwith the initial values `F(0) = 0`, `F(1) = 1`. :func:`~mpmath.fibonacci`\\nextends this definition to arbitrary real and complex arguments\\nusing the formula\\n\\n.. math ::\\n\\n  F(z) = \\\\frac{\\\\phi^z - \\\\cos(\\\\pi z) \\\\phi^{-z}}{\\\\sqrt 5}\\n\\nwhere `\\\\phi` is the golden ratio. :func:`~mpmath.fibonacci` also uses this\\ncontinuous formula to compute `F(n)` for extremely large `n`, where\\ncalculating the exact integer would be wasteful.\\n\\nFor convenience, :func:`~mpmath.fib` is available as an alias for\\n:func:`~mpmath.fibonacci`.\\n\\n**Basic examples**\\n\\nSome small Fibonacci numbers are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for i in range(10):\\n    ...     print(fibonacci(i))\\n    ...\\n    0.0\\n    1.0\\n    1.0\\n    2.0\\n    3.0\\n    5.0\\n    8.0\\n    13.0\\n    21.0\\n    34.0\\n    >>> fibonacci(50)\\n    12586269025.0\\n\\nThe recurrence for `F(n)` extends backwards to negative `n`::\\n\\n    >>> for i in range(10):\\n    ...     print(fibonacci(-i))\\n    ...\\n    0.0\\n    1.0\\n    -1.0\\n    2.0\\n    -3.0\\n    5.0\\n    -8.0\\n    13.0\\n    -21.0\\n    34.0\\n\\nLarge Fibonacci numbers will be computed approximately unless\\nthe precision is set high enough::\\n\\n    >>> fib(200)\\n    2.8057117299251e+41\\n    >>> mp.dps = 45\\n    >>> fib(200)\\n    280571172992510140037611932413038677189525.0\\n\\n:func:`~mpmath.fibonacci` can compute approximate Fibonacci numbers\\nof stupendous size::\\n\\n    >>> mp.dps = 15\\n    >>> fibonacci(10**25)\\n    3.49052338550226e+2089876402499787337692720\\n\\n**Real and complex arguments**\\n\\nThe extended Fibonacci function is an analytic function. The\\nproperty `F(z) = F(z-1) + F(z-2)` holds for arbitrary `z`::\\n\\n    >>> mp.dps = 15\\n    >>> fib(pi)\\n    2.1170270579161\\n    >>> fib(pi-1) + fib(pi-2)\\n    2.1170270579161\\n    >>> fib(3+4j)\\n    (-5248.51130728372 - 14195.962288353j)\\n    >>> fib(2+4j) + fib(1+4j)\\n    (-5248.51130728372 - 14195.962288353j)\\n\\nThe Fibonacci function has infinitely many roots on the\\nnegative half-real axis. The first root is at 0, the second is\\nclose to -0.18, and then there are infinitely many roots that\\nasymptotically approach `-n+1/2`::\\n\\n    >>> findroot(fib, -0.2)\\n    -0.183802359692956\\n    >>> findroot(fib, -2)\\n    -1.57077646820395\\n    >>> findroot(fib, -17)\\n    -16.4999999596115\\n    >>> findroot(fib, -24)\\n    -23.5000000000479\\n\\n**Mathematical relationships**\\n\\nFor large `n`, `F(n+1)/F(n)` approaches the golden ratio::\\n\\n    >>> mp.dps = 50\\n    >>> fibonacci(101)/fibonacci(100)\\n    1.6180339887498948482045868343656381177203127439638\\n    >>> +phi\\n    1.6180339887498948482045868343656381177203091798058\\n\\nThe sum of reciprocal Fibonacci numbers converges to an irrational\\nnumber for which no closed form expression is known::\\n\\n    >>> mp.dps = 15\\n    >>> nsum(lambda n: 1/fib(n), [1, inf])\\n    3.35988566624318\\n\\nAmazingly, however, the sum of odd-index reciprocal Fibonacci\\nnumbers can be expressed in terms of a Jacobi theta function::\\n\\n    >>> nsum(lambda n: 1/fib(2*n+1), [0, inf])\\n    1.82451515740692\\n    >>> sqrt(5)*jtheta(2,0,(3-sqrt(5))/2)**2/4\\n    1.82451515740692\\n\\nSome related sums can be done in closed form::\\n\\n    >>> nsum(lambda k: 1/(1+fib(2*k+1)), [0, inf])\\n    1.11803398874989\\n    >>> phi - 0.5\\n    1.11803398874989\\n    >>> f = lambda k:(-1)**(k+1) / sum(fib(n)**2 for n in range(1,int(k+1)))\\n    >>> nsum(f, [1, inf])\\n    0.618033988749895\\n    >>> phi-1\\n    0.618033988749895\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/FibonacciNumber.html\\n\\\"\\\"\\\"\\n\\naltzeta = r\\\"\\\"\\\"\\nGives the Dirichlet eta function, `\\\\eta(s)`, also known as the\\nalternating zeta function. This function is defined in analogy\\nwith the Riemann zeta function as providing the sum of the\\nalternating series\\n\\n.. math ::\\n\\n    \\\\eta(s) = \\\\sum_{k=0}^{\\\\infty} \\\\frac{(-1)^k}{k^s}\\n        = 1-\\\\frac{1}{2^s}+\\\\frac{1}{3^s}-\\\\frac{1}{4^s}+\\\\ldots\\n\\nThe eta function, unlike the Riemann zeta function, is an entire\\nfunction, having a finite value for all complex `s`. The special case\\n`\\\\eta(1) = \\\\log(2)` gives the value of the alternating harmonic series.\\n\\nThe alternating zeta function may expressed using the Riemann zeta function\\nas `\\\\eta(s) = (1 - 2^{1-s}) \\\\zeta(s)`. It can also be expressed\\nin terms of the Hurwitz zeta function, for example using\\n:func:`~mpmath.dirichlet` (see documentation for that function).\\n\\n**Examples**\\n\\nSome special values are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> altzeta(1)\\n    0.693147180559945\\n    >>> altzeta(0)\\n    0.5\\n    >>> altzeta(-1)\\n    0.25\\n    >>> altzeta(-2)\\n    0.0\\n\\nAn example of a sum that can be computed more accurately and\\nefficiently via :func:`~mpmath.altzeta` than via numerical summation::\\n\\n    >>> sum(-(-1)**n / mpf(n)**2.5 for n in range(1, 100))\\n    0.867204951503984\\n    >>> altzeta(2.5)\\n    0.867199889012184\\n\\nAt positive even integers, the Dirichlet eta function\\nevaluates to a rational multiple of a power of `\\\\pi`::\\n\\n    >>> altzeta(2)\\n    0.822467033424113\\n    >>> pi**2/12\\n    0.822467033424113\\n\\nLike the Riemann zeta function, `\\\\eta(s)`, approaches 1\\nas `s` approaches positive infinity, although it does\\nso from below rather than from above::\\n\\n    >>> altzeta(30)\\n    0.999999999068682\\n    >>> altzeta(inf)\\n    1.0\\n    >>> mp.pretty = False\\n    >>> altzeta(1000, rounding='d')\\n    mpf('0.99999999999999989')\\n    >>> altzeta(1000, rounding='u')\\n    mpf('1.0')\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/DirichletEtaFunction.html\\n\\n2. http://en.wikipedia.org/wiki/Dirichlet_eta_function\\n\\\"\\\"\\\"\\n\\nfactorial = r\\\"\\\"\\\"\\nComputes the factorial, `x!`. For integers `n \\\\ge 0`, we have\\n`n! = 1 \\\\cdot 2 \\\\cdots (n-1) \\\\cdot n` and more generally the factorial\\nis defined for real or complex `x` by `x! = \\\\Gamma(x+1)`.\\n\\n**Examples**\\n\\nBasic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for k in range(6):\\n    ...     print(\\\"%s %s\\\" % (k, fac(k)))\\n    ...\\n    0 1.0\\n    1 1.0\\n    2 2.0\\n    3 6.0\\n    4 24.0\\n    5 120.0\\n    >>> fac(inf)\\n    +inf\\n    >>> fac(0.5), sqrt(pi)/2\\n    (0.886226925452758, 0.886226925452758)\\n\\nFor large positive `x`, `x!` can be approximated by\\nStirling's formula::\\n\\n    >>> x = 10**10\\n    >>> fac(x)\\n    2.32579620567308e+95657055186\\n    >>> sqrt(2*pi*x)*(x/e)**x\\n    2.32579597597705e+95657055186\\n\\n:func:`~mpmath.fac` supports evaluation for astronomically large values::\\n\\n    >>> fac(10**30)\\n    6.22311232304258e+29565705518096748172348871081098\\n\\nReciprocal factorials appear in the Taylor series of the\\nexponential function (among many other contexts)::\\n\\n    >>> nsum(lambda k: 1/fac(k), [0, inf]), exp(1)\\n    (2.71828182845905, 2.71828182845905)\\n    >>> nsum(lambda k: pi**k/fac(k), [0, inf]), exp(pi)\\n    (23.1406926327793, 23.1406926327793)\\n\\n\\\"\\\"\\\"\\n\\ngamma = r\\\"\\\"\\\"\\nComputes the gamma function, `\\\\Gamma(x)`. The gamma function is a\\nshifted version of the ordinary factorial, satisfying\\n`\\\\Gamma(n) = (n-1)!` for integers `n > 0`. More generally, it\\nis defined by\\n\\n.. math ::\\n\\n    \\\\Gamma(x) = \\\\int_0^{\\\\infty} t^{x-1} e^{-t}\\\\, dt\\n\\nfor any real or complex `x` with `\\\\Re(x) > 0` and for `\\\\Re(x) < 0`\\nby analytic continuation.\\n\\n**Examples**\\n\\nBasic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for k in range(1, 6):\\n    ...     print(\\\"%s %s\\\" % (k, gamma(k)))\\n    ...\\n    1 1.0\\n    2 1.0\\n    3 2.0\\n    4 6.0\\n    5 24.0\\n    >>> gamma(inf)\\n    +inf\\n    >>> gamma(0)\\n    Traceback (most recent call last):\\n      ...\\n    ValueError: gamma function pole\\n\\nThe gamma function of a half-integer is a rational multiple of\\n`\\\\sqrt{\\\\pi}`::\\n\\n    >>> gamma(0.5), sqrt(pi)\\n    (1.77245385090552, 1.77245385090552)\\n    >>> gamma(1.5), sqrt(pi)/2\\n    (0.886226925452758, 0.886226925452758)\\n\\nWe can check the integral definition::\\n\\n    >>> gamma(3.5)\\n    3.32335097044784\\n    >>> quad(lambda t: t**2.5*exp(-t), [0,inf])\\n    3.32335097044784\\n\\n:func:`~mpmath.gamma` supports arbitrary-precision evaluation and\\ncomplex arguments::\\n\\n    >>> mp.dps = 50\\n    >>> gamma(sqrt(3))\\n    0.91510229697308632046045539308226554038315280564184\\n    >>> mp.dps = 25\\n    >>> gamma(2j)\\n    (0.009902440080927490985955066 - 0.07595200133501806872408048j)\\n\\nArguments can also be large. Note that the gamma function grows\\nvery quickly::\\n\\n    >>> mp.dps = 15\\n    >>> gamma(10**20)\\n    1.9328495143101e+1956570551809674817225\\n\\n**References**\\n\\n* [Spouge]_\\n\\n\\\"\\\"\\\"\\n\\npsi = r\\\"\\\"\\\"\\nGives the polygamma function of order `m` of `z`, `\\\\psi^{(m)}(z)`.\\nSpecial cases are known as the *digamma function* (`\\\\psi^{(0)}(z)`),\\nthe *trigamma function* (`\\\\psi^{(1)}(z)`), etc. The polygamma\\nfunctions are defined as the logarithmic derivatives of the gamma\\nfunction:\\n\\n.. math ::\\n\\n    \\\\psi^{(m)}(z) = \\\\left(\\\\frac{d}{dz}\\\\right)^{m+1} \\\\log \\\\Gamma(z)\\n\\nIn particular, `\\\\psi^{(0)}(z) = \\\\Gamma'(z)/\\\\Gamma(z)`. In the\\npresent implementation of :func:`~mpmath.psi`, the order `m` must be a\\nnonnegative integer, while the argument `z` may be an arbitrary\\ncomplex number (with exception for the polygamma function's poles\\nat `z = 0, -1, -2, \\\\ldots`).\\n\\n**Examples**\\n\\nFor various rational arguments, the polygamma function reduces to\\na combination of standard mathematical constants::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> psi(0, 1), -euler\\n    (-0.5772156649015328606065121, -0.5772156649015328606065121)\\n    >>> psi(1, '1/4'), pi**2+8*catalan\\n    (17.19732915450711073927132, 17.19732915450711073927132)\\n    >>> psi(2, '1/2'), -14*apery\\n    (-16.82879664423431999559633, -16.82879664423431999559633)\\n\\nThe polygamma functions are derivatives of each other::\\n\\n    >>> diff(lambda x: psi(3, x), pi), psi(4, pi)\\n    (-0.1105749312578862734526952, -0.1105749312578862734526952)\\n    >>> quad(lambda x: psi(4, x), [2, 3]), psi(3,3)-psi(3,2)\\n    (-0.375, -0.375)\\n\\nThe digamma function diverges logarithmically as `z \\\\to \\\\infty`,\\nwhile higher orders tend to zero::\\n\\n    >>> psi(0,inf), psi(1,inf), psi(2,inf)\\n    (+inf, 0.0, 0.0)\\n\\nEvaluation for a complex argument::\\n\\n    >>> psi(2, -1-2j)\\n    (0.03902435405364952654838445 + 0.1574325240413029954685366j)\\n\\nEvaluation is supported for large orders `m` and/or large\\narguments `z`::\\n\\n    >>> psi(3, 10**100)\\n    2.0e-300\\n    >>> psi(250, 10**30+10**20*j)\\n    (-1.293142504363642687204865e-7010 + 3.232856260909107391513108e-7018j)\\n\\n**Application to infinite series**\\n\\nAny infinite series where the summand is a rational function of\\nthe index `k` can be evaluated in closed form in terms of polygamma\\nfunctions of the roots and poles of the summand::\\n\\n    >>> a = sqrt(2)\\n    >>> b = sqrt(3)\\n    >>> nsum(lambda k: 1/((k+a)**2*(k+b)), [0, inf])\\n    0.4049668927517857061917531\\n    >>> (psi(0,a)-psi(0,b)-a*psi(1,a)+b*psi(1,a))/(a-b)**2\\n    0.4049668927517857061917531\\n\\nThis follows from the series representation (`m > 0`)\\n\\n.. math ::\\n\\n    \\\\psi^{(m)}(z) = (-1)^{m+1} m! \\\\sum_{k=0}^{\\\\infty}\\n        \\\\frac{1}{(z+k)^{m+1}}.\\n\\nSince the roots of a polynomial may be complex, it is sometimes\\nnecessary to use the complex polygamma function to evaluate\\nan entirely real-valued sum::\\n\\n    >>> nsum(lambda k: 1/(k**2-2*k+3), [0, inf])\\n    1.694361433907061256154665\\n    >>> nprint(polyroots([1,-2,3]))\\n    [(1.0 - 1.41421j), (1.0 + 1.41421j)]\\n    >>> r1 = 1-sqrt(2)*j\\n    >>> r2 = r1.conjugate()\\n    >>> (psi(0,-r2)-psi(0,-r1))/(r1-r2)\\n    (1.694361433907061256154665 + 0.0j)\\n\\n\\\"\\\"\\\"\\n\\ndigamma = r\\\"\\\"\\\"\\nShortcut for ``psi(0,z)``.\\n\\\"\\\"\\\"\\n\\nharmonic = r\\\"\\\"\\\"\\nIf `n` is an integer, ``harmonic(n)`` gives a floating-point\\napproximation of the `n`-th harmonic number `H(n)`, defined as\\n\\n.. math ::\\n\\n    H(n) = 1 + \\\\frac{1}{2} + \\\\frac{1}{3} + \\\\ldots + \\\\frac{1}{n}\\n\\nThe first few harmonic numbers are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(8):\\n    ...     print(\\\"%s %s\\\" % (n, harmonic(n)))\\n    ...\\n    0 0.0\\n    1 1.0\\n    2 1.5\\n    3 1.83333333333333\\n    4 2.08333333333333\\n    5 2.28333333333333\\n    6 2.45\\n    7 2.59285714285714\\n\\nThe infinite harmonic series `1 + 1/2 + 1/3 + \\\\ldots` diverges::\\n\\n    >>> harmonic(inf)\\n    +inf\\n\\n:func:`~mpmath.harmonic` is evaluated using the digamma function rather\\nthan by summing the harmonic series term by term. It can therefore\\nbe computed quickly for arbitrarily large `n`, and even for\\nnonintegral arguments::\\n\\n    >>> harmonic(10**100)\\n    230.835724964306\\n    >>> harmonic(0.5)\\n    0.613705638880109\\n    >>> harmonic(3+4j)\\n    (2.24757548223494 + 0.850502209186044j)\\n\\n:func:`~mpmath.harmonic` supports arbitrary precision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> harmonic(11)\\n    3.0198773448773448773448773448773448773448773448773\\n    >>> harmonic(pi)\\n    1.8727388590273302654363491032336134987519132374152\\n\\nThe harmonic series diverges, but at a glacial pace. It is possible\\nto calculate the exact number of terms required before the sum\\nexceeds a given amount, say 100::\\n\\n    >>> mp.dps = 50\\n    >>> v = 10**findroot(lambda x: harmonic(10**x) - 100, 10)\\n    >>> v\\n    15092688622113788323693563264538101449859496.864101\\n    >>> v = int(ceil(v))\\n    >>> print(v)\\n    15092688622113788323693563264538101449859497\\n    >>> harmonic(v-1)\\n    99.999999999999999999999999999999999999999999942747\\n    >>> harmonic(v)\\n    100.000000000000000000000000000000000000000000009\\n\\n\\\"\\\"\\\"\\n\\nbernoulli = r\\\"\\\"\\\"\\nComputes the nth Bernoulli number, `B_n`, for any integer `n \\\\ge 0`.\\n\\nThe Bernoulli numbers are rational numbers, but this function\\nreturns a floating-point approximation. To obtain an exact\\nfraction, use :func:`~mpmath.bernfrac` instead.\\n\\n**Examples**\\n\\nNumerical values of the first few Bernoulli numbers::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(15):\\n    ...     print(\\\"%s %s\\\" % (n, bernoulli(n)))\\n    ...\\n    0 1.0\\n    1 -0.5\\n    2 0.166666666666667\\n    3 0.0\\n    4 -0.0333333333333333\\n    5 0.0\\n    6 0.0238095238095238\\n    7 0.0\\n    8 -0.0333333333333333\\n    9 0.0\\n    10 0.0757575757575758\\n    11 0.0\\n    12 -0.253113553113553\\n    13 0.0\\n    14 1.16666666666667\\n\\nBernoulli numbers can be approximated with arbitrary precision::\\n\\n    >>> mp.dps = 50\\n    >>> bernoulli(100)\\n    -2.8382249570693706959264156336481764738284680928013e+78\\n\\nArbitrarily large `n` are supported::\\n\\n    >>> mp.dps = 15\\n    >>> bernoulli(10**20 + 2)\\n    3.09136296657021e+1876752564973863312327\\n\\nThe Bernoulli numbers are related to the Riemann zeta function\\nat integer arguments::\\n\\n    >>> -bernoulli(8) * (2*pi)**8 / (2*fac(8))\\n    1.00407735619794\\n    >>> zeta(8)\\n    1.00407735619794\\n\\n**Algorithm**\\n\\nFor small `n` (`n < 3000`) :func:`~mpmath.bernoulli` uses a recurrence\\nformula due to Ramanujan. All results in this range are cached,\\nso sequential computation of small Bernoulli numbers is\\nguaranteed to be fast.\\n\\nFor larger `n`, `B_n` is evaluated in terms of the Riemann zeta\\nfunction.\\n\\\"\\\"\\\"\\n\\nstieltjes = r\\\"\\\"\\\"\\nFor a nonnegative integer `n`, ``stieltjes(n)`` computes the\\n`n`-th Stieltjes constant `\\\\gamma_n`, defined as the\\n`n`-th coefficient in the Laurent series expansion of the\\nRiemann zeta function around the pole at `s = 1`. That is,\\nwe have:\\n\\n.. math ::\\n\\n  \\\\zeta(s) = \\\\frac{1}{s-1} \\\\sum_{n=0}^{\\\\infty}\\n      \\\\frac{(-1)^n}{n!} \\\\gamma_n (s-1)^n\\n\\nMore generally, ``stieltjes(n, a)`` gives the corresponding\\ncoefficient `\\\\gamma_n(a)` for the Hurwitz zeta function\\n`\\\\zeta(s,a)` (with `\\\\gamma_n = \\\\gamma_n(1)`).\\n\\n**Examples**\\n\\nThe zeroth Stieltjes constant is just Euler's constant `\\\\gamma`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> stieltjes(0)\\n    0.577215664901533\\n\\nSome more values are::\\n\\n    >>> stieltjes(1)\\n    -0.0728158454836767\\n    >>> stieltjes(10)\\n    0.000205332814909065\\n    >>> stieltjes(30)\\n    0.00355772885557316\\n    >>> stieltjes(1000)\\n    -1.57095384420474e+486\\n    >>> stieltjes(2000)\\n    2.680424678918e+1109\\n    >>> stieltjes(1, 2.5)\\n    -0.23747539175716\\n\\nAn alternative way to compute `\\\\gamma_1`::\\n\\n    >>> diff(extradps(15)(lambda x: 1/(x-1) - zeta(x)), 1)\\n    -0.0728158454836767\\n\\n:func:`~mpmath.stieltjes` supports arbitrary precision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> stieltjes(2)\\n    -0.0096903631928723184845303860352125293590658061013408\\n\\n**Algorithm**\\n\\n:func:`~mpmath.stieltjes` numerically evaluates the integral in\\nthe following representation due to Ainsworth, Howell and\\nCoffey [1], [2]:\\n\\n.. math ::\\n\\n  \\\\gamma_n(a) = \\\\frac{\\\\log^n a}{2a} - \\\\frac{\\\\log^{n+1}(a)}{n+1} +\\n      \\\\frac{2}{a} \\\\Re \\\\int_0^{\\\\infty}\\n      \\\\frac{(x/a-i)\\\\log^n(a-ix)}{(1+x^2/a^2)(e^{2\\\\pi x}-1)} dx.\\n\\nFor some reference values with `a = 1`, see e.g. [4].\\n\\n**References**\\n\\n1. O. R. Ainsworth & L. W. Howell, \\\"An integral representation of\\n   the generalized Euler-Mascheroni constants\\\", NASA Technical\\n   Paper 2456 (1985),\\n   http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19850014994_1985014994.pdf\\n\\n2. M. W. Coffey, \\\"The Stieltjes constants, their relation to the\\n   `\\\\eta_j` coefficients, and representation of the Hurwitz\\n   zeta function\\\", \\tarXiv:0706.0343v1 http://arxiv.org/abs/0706.0343\\n\\n3. http://mathworld.wolfram.com/StieltjesConstants.html\\n\\n4. http://pi.lacim.uqam.ca/piDATA/stieltjesgamma.txt\\n\\n\\\"\\\"\\\"\\n\\ngammaprod = r\\\"\\\"\\\"\\nGiven iterables `a` and `b`, ``gammaprod(a, b)`` computes the\\nproduct / quotient of gamma functions:\\n\\n.. math ::\\n\\n    \\\\frac{\\\\Gamma(a_0) \\\\Gamma(a_1) \\\\cdots \\\\Gamma(a_p)}\\n         {\\\\Gamma(b_0) \\\\Gamma(b_1) \\\\cdots \\\\Gamma(b_q)}\\n\\nUnlike direct calls to :func:`~mpmath.gamma`, :func:`~mpmath.gammaprod` considers\\nthe entire product as a limit and evaluates this limit properly if\\nany of the numerator or denominator arguments are nonpositive\\nintegers such that poles of the gamma function are encountered.\\nThat is, :func:`~mpmath.gammaprod` evaluates\\n\\n.. math ::\\n\\n    \\\\lim_{\\\\epsilon \\\\to 0}\\n    \\\\frac{\\\\Gamma(a_0+\\\\epsilon) \\\\Gamma(a_1+\\\\epsilon) \\\\cdots\\n        \\\\Gamma(a_p+\\\\epsilon)}\\n         {\\\\Gamma(b_0+\\\\epsilon) \\\\Gamma(b_1+\\\\epsilon) \\\\cdots\\n        \\\\Gamma(b_q+\\\\epsilon)}\\n\\nIn particular:\\n\\n* If there are equally many poles in the numerator and the\\n  denominator, the limit is a rational number times the remaining,\\n  regular part of the product.\\n\\n* If there are more poles in the numerator, :func:`~mpmath.gammaprod`\\n  returns ``+inf``.\\n\\n* If there are more poles in the denominator, :func:`~mpmath.gammaprod`\\n  returns 0.\\n\\n**Examples**\\n\\nThe reciprocal gamma function `1/\\\\Gamma(x)` evaluated at `x = 0`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15\\n    >>> gammaprod([], [0])\\n    0.0\\n\\nA limit::\\n\\n    >>> gammaprod([-4], [-3])\\n    -0.25\\n    >>> limit(lambda x: gamma(x-1)/gamma(x), -3, direction=1)\\n    -0.25\\n    >>> limit(lambda x: gamma(x-1)/gamma(x), -3, direction=-1)\\n    -0.25\\n\\n\\\"\\\"\\\"\\n\\nbeta = r\\\"\\\"\\\"\\nComputes the beta function,\\n`B(x,y) = \\\\Gamma(x) \\\\Gamma(y) / \\\\Gamma(x+y)`.\\nThe beta function is also commonly defined by the integral\\nrepresentation\\n\\n.. math ::\\n\\n    B(x,y) = \\\\int_0^1 t^{x-1} (1-t)^{y-1} \\\\, dt\\n\\n**Examples**\\n\\nFor integer and half-integer arguments where all three gamma\\nfunctions are finite, the beta function becomes either rational\\nnumber or a rational multiple of `\\\\pi`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> beta(5, 2)\\n    0.0333333333333333\\n    >>> beta(1.5, 2)\\n    0.266666666666667\\n    >>> 16*beta(2.5, 1.5)\\n    3.14159265358979\\n\\nWhere appropriate, :func:`~mpmath.beta` evaluates limits. A pole\\nof the beta function is taken to result in ``+inf``::\\n\\n    >>> beta(-0.5, 0.5)\\n    0.0\\n    >>> beta(-3, 3)\\n    -0.333333333333333\\n    >>> beta(-2, 3)\\n    +inf\\n    >>> beta(inf, 1)\\n    0.0\\n    >>> beta(inf, 0)\\n    nan\\n\\n:func:`~mpmath.beta` supports complex numbers and arbitrary precision\\nevaluation::\\n\\n    >>> beta(1, 2+j)\\n    (0.4 - 0.2j)\\n    >>> mp.dps = 25\\n    >>> beta(j,0.5)\\n    (1.079424249270925780135675 - 1.410032405664160838288752j)\\n    >>> mp.dps = 50\\n    >>> beta(pi, e)\\n    0.037890298781212201348153837138927165984170287886464\\n\\nVarious integrals can be computed by means of the\\nbeta function::\\n\\n    >>> mp.dps = 15\\n    >>> quad(lambda t: t**2.5*(1-t)**2, [0, 1])\\n    0.0230880230880231\\n    >>> beta(3.5, 3)\\n    0.0230880230880231\\n    >>> quad(lambda t: sin(t)**4 * sqrt(cos(t)), [0, pi/2])\\n    0.319504062596158\\n    >>> beta(2.5, 0.75)/2\\n    0.319504062596158\\n\\n\\\"\\\"\\\"\\n\\nbetainc = r\\\"\\\"\\\"\\n``betainc(a, b, x1=0, x2=1, regularized=False)`` gives the generalized\\nincomplete beta function,\\n\\n.. math ::\\n\\n    I_{x_1}^{x_2}(a,b) = \\\\int_{x_1}^{x_2} t^{a-1} (1-t)^{b-1} dt.\\n\\nWhen `x_1 = 0, x_2 = 1`, this reduces to the ordinary (complete)\\nbeta function `B(a,b)`; see :func:`~mpmath.beta`.\\n\\nWith the keyword argument ``regularized=True``, :func:`~mpmath.betainc`\\ncomputes the regularized incomplete beta function\\n`I_{x_1}^{x_2}(a,b) / B(a,b)`. This is the cumulative distribution of the\\nbeta distribution with parameters `a`, `b`.\\n\\n.. note :\\n\\n    Implementations of the incomplete beta function in some other\\n    software uses a different argument order. For example, Mathematica uses the\\n    reversed argument order ``Beta[x1,x2,a,b]``. For the equivalent of SciPy's\\n    three-argument incomplete beta integral (implicitly with `x1 = 0`), use\\n    ``betainc(a,b,0,x2,regularized=True)``.\\n\\n**Examples**\\n\\nVerifying that :func:`~mpmath.betainc` computes the integral in the\\ndefinition::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> x,y,a,b = 3, 4, 0, 6\\n    >>> betainc(x, y, a, b)\\n    -4010.4\\n    >>> quad(lambda t: t**(x-1) * (1-t)**(y-1), [a, b])\\n    -4010.4\\n\\nThe arguments may be arbitrary complex numbers::\\n\\n    >>> betainc(0.75, 1-4j, 0, 2+3j)\\n    (0.2241657956955709603655887 + 0.3619619242700451992411724j)\\n\\nWith regularization::\\n\\n    >>> betainc(1, 2, 0, 0.25, regularized=True)\\n    0.4375\\n    >>> betainc(pi, e, 0, 1, regularized=True)   # Complete\\n    1.0\\n\\nThe beta integral satisfies some simple argument transformation\\nsymmetries::\\n\\n    >>> mp.dps = 15\\n    >>> betainc(2,3,4,5), -betainc(2,3,5,4), betainc(3,2,1-5,1-4)\\n    (56.0833333333333, 56.0833333333333, 56.0833333333333)\\n\\nThe beta integral can often be evaluated analytically. For integer and\\nrational arguments, the incomplete beta function typically reduces to a\\nsimple algebraic-logarithmic expression::\\n\\n    >>> mp.dps = 25\\n    >>> identify(chop(betainc(0, 0, 3, 4)))\\n    '-(log((9/8)))'\\n    >>> identify(betainc(2, 3, 4, 5))\\n    '(673/12)'\\n    >>> identify(betainc(1.5, 1, 1, 2))\\n    '((-12+sqrt(1152))/18)'\\n\\n\\\"\\\"\\\"\\n\\nbinomial = r\\\"\\\"\\\"\\nComputes the binomial coefficient\\n\\n.. math ::\\n\\n    {n \\\\choose k} = \\\\frac{n!}{k!(n-k)!}.\\n\\nThe binomial coefficient gives the number of ways that `k` items\\ncan be chosen from a set of `n` items. More generally, the binomial\\ncoefficient is a well-defined function of arbitrary real or\\ncomplex `n` and `k`, via the gamma function.\\n\\n**Examples**\\n\\nGenerate Pascal's triangle::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(5):\\n    ...     nprint([binomial(n,k) for k in range(n+1)])\\n    ...\\n    [1.0]\\n    [1.0, 1.0]\\n    [1.0, 2.0, 1.0]\\n    [1.0, 3.0, 3.0, 1.0]\\n    [1.0, 4.0, 6.0, 4.0, 1.0]\\n\\nThere is 1 way to select 0 items from the empty set, and 0 ways to\\nselect 1 item from the empty set::\\n\\n    >>> binomial(0, 0)\\n    1.0\\n    >>> binomial(0, 1)\\n    0.0\\n\\n:func:`~mpmath.binomial` supports large arguments::\\n\\n    >>> binomial(10**20, 10**20-5)\\n    8.33333333333333e+97\\n    >>> binomial(10**20, 10**10)\\n    2.60784095465201e+104342944813\\n\\nNonintegral binomial coefficients find use in series\\nexpansions::\\n\\n    >>> nprint(taylor(lambda x: (1+x)**0.25, 0, 4))\\n    [1.0, 0.25, -0.09375, 0.0546875, -0.0375977]\\n    >>> nprint([binomial(0.25, k) for k in range(5)])\\n    [1.0, 0.25, -0.09375, 0.0546875, -0.0375977]\\n\\nAn integral representation::\\n\\n    >>> n, k = 5, 3\\n    >>> f = lambda t: exp(-j*k*t)*(1+exp(j*t))**n\\n    >>> chop(quad(f, [-pi,pi])/(2*pi))\\n    10.0\\n    >>> binomial(n,k)\\n    10.0\\n\\n\\\"\\\"\\\"\\n\\nrf = r\\\"\\\"\\\"\\nComputes the rising factorial or Pochhammer symbol,\\n\\n.. math ::\\n\\n    x^{(n)} = x (x+1) \\\\cdots (x+n-1) = \\\\frac{\\\\Gamma(x+n)}{\\\\Gamma(x)}\\n\\nwhere the rightmost expression is valid for nonintegral `n`.\\n\\n**Examples**\\n\\nFor integral `n`, the rising factorial is a polynomial::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(5):\\n    ...     nprint(taylor(lambda x: rf(x,n), 0, n))\\n    ...\\n    [1.0]\\n    [0.0, 1.0]\\n    [0.0, 1.0, 1.0]\\n    [0.0, 2.0, 3.0, 1.0]\\n    [0.0, 6.0, 11.0, 6.0, 1.0]\\n\\nEvaluation is supported for arbitrary arguments::\\n\\n    >>> rf(2+3j, 5.5)\\n    (-7202.03920483347 - 3777.58810701527j)\\n\\\"\\\"\\\"\\n\\nff = r\\\"\\\"\\\"\\nComputes the falling factorial,\\n\\n.. math ::\\n\\n    (x)_n = x (x-1) \\\\cdots (x-n+1) = \\\\frac{\\\\Gamma(x+1)}{\\\\Gamma(x-n+1)}\\n\\nwhere the rightmost expression is valid for nonintegral `n`.\\n\\n**Examples**\\n\\nFor integral `n`, the falling factorial is a polynomial::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(5):\\n    ...     nprint(taylor(lambda x: ff(x,n), 0, n))\\n    ...\\n    [1.0]\\n    [0.0, 1.0]\\n    [0.0, -1.0, 1.0]\\n    [0.0, 2.0, -3.0, 1.0]\\n    [0.0, -6.0, 11.0, -6.0, 1.0]\\n\\nEvaluation is supported for arbitrary arguments::\\n\\n    >>> ff(2+3j, 5.5)\\n    (-720.41085888203 + 316.101124983878j)\\n\\\"\\\"\\\"\\n\\nfac2 = r\\\"\\\"\\\"\\nComputes the double factorial `x!!`, defined for integers\\n`x > 0` by\\n\\n.. math ::\\n\\n    x!! = \\\\begin{cases}\\n        1 \\\\cdot 3 \\\\cdots (x-2) \\\\cdot x & x \\\\;\\\\mathrm{odd} \\\\\\\\\\n        2 \\\\cdot 4 \\\\cdots (x-2) \\\\cdot x & x \\\\;\\\\mathrm{even}\\n    \\\\end{cases}\\n\\nand more generally by [1]\\n\\n.. math ::\\n\\n    x!! = 2^{x/2} \\\\left(\\\\frac{\\\\pi}{2}\\\\right)^{(\\\\cos(\\\\pi x)-1)/4}\\n          \\\\Gamma\\\\left(\\\\frac{x}{2}+1\\\\right).\\n\\n**Examples**\\n\\nThe integer sequence of double factorials begins::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> nprint([fac2(n) for n in range(10)])\\n    [1.0, 1.0, 2.0, 3.0, 8.0, 15.0, 48.0, 105.0, 384.0, 945.0]\\n\\nFor large `x`, double factorials follow a Stirling-like asymptotic\\napproximation::\\n\\n    >>> x = mpf(10000)\\n    >>> fac2(x)\\n    5.97272691416282e+17830\\n    >>> sqrt(pi)*x**((x+1)/2)*exp(-x/2)\\n    5.97262736954392e+17830\\n\\nThe recurrence formula `x!! = x (x-2)!!` can be reversed to\\ndefine the double factorial of negative odd integers (but\\nnot negative even integers)::\\n\\n    >>> fac2(-1), fac2(-3), fac2(-5), fac2(-7)\\n    (1.0, -1.0, 0.333333333333333, -0.0666666666666667)\\n    >>> fac2(-2)\\n    Traceback (most recent call last):\\n      ...\\n    ValueError: gamma function pole\\n\\nWith the exception of the poles at negative even integers,\\n:func:`~mpmath.fac2` supports evaluation for arbitrary complex arguments.\\nThe recurrence formula is valid generally::\\n\\n    >>> fac2(pi+2j)\\n    (-1.3697207890154e-12 + 3.93665300979176e-12j)\\n    >>> (pi+2j)*fac2(pi-2+2j)\\n    (-1.3697207890154e-12 + 3.93665300979176e-12j)\\n\\nDouble factorials should not be confused with nested factorials,\\nwhich are immensely larger::\\n\\n    >>> fac(fac(20))\\n    5.13805976125208e+43675043585825292774\\n    >>> fac2(20)\\n    3715891200.0\\n\\nDouble factorials appear, among other things, in series expansions\\nof Gaussian functions and the error function. Infinite series\\ninclude::\\n\\n    >>> nsum(lambda k: 1/fac2(k), [0, inf])\\n    3.05940740534258\\n    >>> sqrt(e)*(1+sqrt(pi/2)*erf(sqrt(2)/2))\\n    3.05940740534258\\n    >>> nsum(lambda k: 2**k/fac2(2*k-1), [1, inf])\\n    4.06015693855741\\n    >>> e * erf(1) * sqrt(pi)\\n    4.06015693855741\\n\\nA beautiful Ramanujan sum::\\n\\n    >>> nsum(lambda k: (-1)**k*(fac2(2*k-1)/fac2(2*k))**3, [0,inf])\\n    0.90917279454693\\n    >>> (gamma('9/8')/gamma('5/4')/gamma('7/8'))**2\\n    0.90917279454693\\n\\n**References**\\n\\n1. http://functions.wolfram.com/GammaBetaErf/Factorial2/27/01/0002/\\n\\n2. http://mathworld.wolfram.com/DoubleFactorial.html\\n\\n\\\"\\\"\\\"\\n\\nhyper = r\\\"\\\"\\\"\\nEvaluates the generalized hypergeometric function\\n\\n.. math ::\\n\\n    \\\\,_pF_q(a_1,\\\\ldots,a_p; b_1,\\\\ldots,b_q; z) =\\n    \\\\sum_{n=0}^\\\\infty \\\\frac{(a_1)_n (a_2)_n \\\\ldots (a_p)_n}\\n       {(b_1)_n(b_2)_n\\\\ldots(b_q)_n} \\\\frac{z^n}{n!}\\n\\nwhere `(x)_n` denotes the rising factorial (see :func:`~mpmath.rf`).\\n\\nThe parameters lists ``a_s`` and ``b_s`` may contain integers,\\nreal numbers, complex numbers, as well as exact fractions given in\\nthe form of tuples `(p, q)`. :func:`~mpmath.hyper` is optimized to handle\\nintegers and fractions more efficiently than arbitrary\\nfloating-point parameters (since rational parameters are by\\nfar the most common).\\n\\n**Examples**\\n\\nVerifying that :func:`~mpmath.hyper` gives the sum in the definition, by\\ncomparison with :func:`~mpmath.nsum`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> a,b,c,d = 2,3,4,5\\n    >>> x = 0.25\\n    >>> hyper([a,b],[c,d],x)\\n    1.078903941164934876086237\\n    >>> fn = lambda n: rf(a,n)*rf(b,n)/rf(c,n)/rf(d,n)*x**n/fac(n)\\n    >>> nsum(fn, [0, inf])\\n    1.078903941164934876086237\\n\\nThe parameters can be any combination of integers, fractions,\\nfloats and complex numbers::\\n\\n    >>> a, b, c, d, e = 1, (-1,2), pi, 3+4j, (2,3)\\n    >>> x = 0.2j\\n    >>> hyper([a,b],[c,d,e],x)\\n    (0.9923571616434024810831887 - 0.005753848733883879742993122j)\\n    >>> b, e = -0.5, mpf(2)/3\\n    >>> fn = lambda n: rf(a,n)*rf(b,n)/rf(c,n)/rf(d,n)/rf(e,n)*x**n/fac(n)\\n    >>> nsum(fn, [0, inf])\\n    (0.9923571616434024810831887 - 0.005753848733883879742993122j)\\n\\nThe `\\\\,_0F_0` and `\\\\,_1F_0` series are just elementary functions::\\n\\n    >>> a, z = sqrt(2), +pi\\n    >>> hyper([],[],z)\\n    23.14069263277926900572909\\n    >>> exp(z)\\n    23.14069263277926900572909\\n    >>> hyper([a],[],z)\\n    (-0.09069132879922920160334114 + 0.3283224323946162083579656j)\\n    >>> (1-z)**(-a)\\n    (-0.09069132879922920160334114 + 0.3283224323946162083579656j)\\n\\nIf any `a_k` coefficient is a nonpositive integer, the series terminates\\ninto a finite polynomial::\\n\\n    >>> hyper([1,1,1,-3],[2,5],1)\\n    0.7904761904761904761904762\\n    >>> identify(_)\\n    '(83/105)'\\n\\nIf any `b_k` is a nonpositive integer, the function is undefined (unless the\\nseries terminates before the division by zero occurs)::\\n\\n    >>> hyper([1,1,1,-3],[-2,5],1)\\n    Traceback (most recent call last):\\n      ...\\n    ZeroDivisionError: pole in hypergeometric series\\n    >>> hyper([1,1,1,-1],[-2,5],1)\\n    1.1\\n\\nExcept for polynomial cases, the radius of convergence `R` of the hypergeometric\\nseries is either `R = \\\\infty` (if `p \\\\le q`), `R = 1` (if `p = q+1`), or\\n`R = 0` (if `p > q+1`).\\n\\nThe analytic continuations of the functions with `p = q+1`, i.e. `\\\\,_2F_1`,\\n`\\\\,_3F_2`,  `\\\\,_4F_3`, etc, are all implemented and therefore these functions\\ncan be evaluated for `|z| \\\\ge 1`. The shortcuts :func:`~mpmath.hyp2f1`, :func:`~mpmath.hyp3f2`\\nare available to handle the most common cases (see their documentation),\\nbut functions of higher degree are also supported via :func:`~mpmath.hyper`::\\n\\n    >>> hyper([1,2,3,4], [5,6,7], 1)   # 4F3 at finite-valued branch point\\n    1.141783505526870731311423\\n    >>> hyper([4,5,6,7], [1,2,3], 1)   # 4F3 at pole\\n    +inf\\n    >>> hyper([1,2,3,4,5], [6,7,8,9], 10)    # 5F4\\n    (1.543998916527972259717257 - 0.5876309929580408028816365j)\\n    >>> hyper([1,2,3,4,5,6], [7,8,9,10,11], 1j)   # 6F5\\n    (0.9996565821853579063502466 + 0.0129721075905630604445669j)\\n\\nNear `z = 1` with noninteger parameters::\\n\\n    >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','41/8'], 1)\\n    2.219433352235586121250027\\n    >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','5/4'], 1)\\n    +inf\\n    >>> eps1 = extradps(6)(lambda: 1 - mpf('1e-6'))()\\n    >>> hyper(['1/3',1,'3/2',2], ['1/5','11/6','5/4'], eps1)\\n    2923978034.412973409330956\\n\\nPlease note that, as currently implemented, evaluation of `\\\\,_pF_{p-1}`\\nwith `p \\\\ge 3` may be slow or inaccurate when `|z-1|` is small,\\nfor some parameter values.\\n\\nEvaluation may be aborted if convergence appears to be too slow.\\nThe optional ``maxterms`` (limiting the number of series terms) and ``maxprec``\\n(limiting the internal precision) keyword arguments can be used\\nto control evaluation::\\n\\n    >>> hyper([1,2,3], [4,5,6], 10000)              # doctest: +IGNORE_EXCEPTION_DETAIL\\n    Traceback (most recent call last):\\n      ...\\n    NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms.\\n    >>> hyper([1,2,3], [4,5,6], 10000, maxterms=10**6)\\n    7.622806053177969474396918e+4310\\n\\nAdditional options include ``force_series`` (which forces direct use of\\na hypergeometric series even if another evaluation method might work better)\\nand ``asymp_tol`` which controls the target tolerance for using\\nasymptotic series.\\n\\nWhen `p > q+1`, ``hyper`` computes the (iterated) Borel sum of the divergent\\nseries. For `\\\\,_2F_0` the Borel sum has an analytic solution and can be\\ncomputed efficiently (see :func:`~mpmath.hyp2f0`). For higher degrees, the functions\\nis evaluated first by attempting to sum it directly as an asymptotic\\nseries (this only works for tiny `|z|`), and then by evaluating the Borel\\nregularized sum using numerical integration. Except for\\nspecial parameter combinations, this can be extremely slow.\\n\\n    >>> hyper([1,1], [], 0.5)          # regularization of 2F0\\n    (1.340965419580146562086448 + 0.8503366631752726568782447j)\\n    >>> hyper([1,1,1,1], [1], 0.5)     # regularization of 4F1\\n    (1.108287213689475145830699 + 0.5327107430640678181200491j)\\n\\nWith the following magnitude of argument, the asymptotic series for `\\\\,_3F_1`\\ngives only a few digits. Using Borel summation, ``hyper`` can produce\\na value with full accuracy::\\n\\n    >>> mp.dps = 15\\n    >>> hyper([2,0.5,4], [5.25], '0.08', force_series=True)             # doctest: +IGNORE_EXCEPTION_DETAIL\\n    Traceback (most recent call last):\\n      ...\\n    NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms.\\n    >>> hyper([2,0.5,4], [5.25], '0.08', asymp_tol=1e-4)\\n    1.0725535790737\\n    >>> hyper([2,0.5,4], [5.25], '0.08')\\n    (1.07269542893559 + 5.54668863216891e-5j)\\n    >>> hyper([2,0.5,4], [5.25], '-0.08', asymp_tol=1e-4)\\n    0.946344925484879\\n    >>> hyper([2,0.5,4], [5.25], '-0.08')\\n    0.946312503737771\\n    >>> mp.dps = 25\\n    >>> hyper([2,0.5,4], [5.25], '-0.08')\\n    0.9463125037377662296700858\\n\\nNote that with the positive `z` value, there is a complex part in the\\ncorrect result, which falls below the tolerance of the asymptotic series.\\n\\nBy default, a parameter that appears in both ``a_s`` and ``b_s`` will be removed\\nunless it is a nonpositive integer. This generally speeds up evaluation\\nby producing a hypergeometric function of lower order.\\nThis optimization can be disabled by passing ``eliminate=False``.\\n\\n    >>> hyper([1,2,3], [4,5,3], 10000)\\n    1.268943190440206905892212e+4321\\n    >>> hyper([1,2,3], [4,5,3], 10000, eliminate=False)             # doctest: +IGNORE_EXCEPTION_DETAIL\\n    Traceback (most recent call last):\\n      ...\\n    NoConvergence: Hypergeometric series converges too slowly. Try increasing maxterms.\\n    >>> hyper([1,2,3], [4,5,3], 10000, eliminate=False, maxterms=10**6)\\n    1.268943190440206905892212e+4321\\n\\nIf a nonpositive integer `-n` appears in both ``a_s`` and ``b_s``, this parameter\\ncannot be unambiguously removed since it creates a term 0 / 0.\\nIn this case the hypergeometric series is understood to terminate before\\nthe division by zero occurs. This convention is consistent with Mathematica.\\nAn alternative convention of eliminating the parameters can be toggled\\nwith ``eliminate_all=True``:\\n\\n    >>> hyper([2,-1], [-1], 3)\\n    7.0\\n    >>> hyper([2,-1], [-1], 3, eliminate_all=True)\\n    0.25\\n    >>> hyper([2], [], 3)\\n    0.25\\n\\n\\\"\\\"\\\"\\n\\nhypercomb = r\\\"\\\"\\\"\\nComputes a weighted combination of hypergeometric functions\\n\\n.. math ::\\n\\n    \\\\sum_{r=1}^N \\\\left[ \\\\prod_{k=1}^{l_r} {w_{r,k}}^{c_{r,k}}\\n    \\\\frac{\\\\prod_{k=1}^{m_r} \\\\Gamma(\\\\alpha_{r,k})}{\\\\prod_{k=1}^{n_r}\\n    \\\\Gamma(\\\\beta_{r,k})}\\n    \\\\,_{p_r}F_{q_r}(a_{r,1},\\\\ldots,a_{r,p}; b_{r,1},\\n    \\\\ldots, b_{r,q}; z_r)\\\\right].\\n\\nTypically the parameters are linear combinations of a small set of base\\nparameters; :func:`~mpmath.hypercomb` permits computing a correct value in\\nthe case that some of the `\\\\alpha`, `\\\\beta`, `b` turn out to be\\nnonpositive integers, or if division by zero occurs for some `w^c`,\\nassuming that there are opposing singularities that cancel out.\\nThe limit is computed by evaluating the function with the base\\nparameters perturbed, at a higher working precision.\\n\\nThe first argument should be a function that takes the perturbable\\nbase parameters ``params`` as input and returns `N` tuples\\n``(w, c, alpha, beta, a, b, z)``, where the coefficients ``w``, ``c``,\\ngamma factors ``alpha``, ``beta``, and hypergeometric coefficients\\n``a``, ``b`` each should be lists of numbers, and ``z`` should be a single\\nnumber.\\n\\n**Examples**\\n\\nThe following evaluates\\n\\n.. math ::\\n\\n    (a-1) \\\\frac{\\\\Gamma(a-3)}{\\\\Gamma(a-4)} \\\\,_1F_1(a,a-1,z) = e^z(a-4)(a+z-1)\\n\\nwith `a=1, z=3`. There is a zero factor, two gamma function poles, and\\nthe 1F1 function is singular; all singularities cancel out to give a finite\\nvalue::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> hypercomb(lambda a: [([a-1],[1],[a-3],[a-4],[a],[a-1],3)], [1])\\n    -180.769832308689\\n    >>> -9*exp(3)\\n    -180.769832308689\\n\\n\\\"\\\"\\\"\\n\\nhyp0f1 = r\\\"\\\"\\\"\\nGives the hypergeometric function `\\\\,_0F_1`, sometimes known as the\\nconfluent limit function, defined as\\n\\n.. math ::\\n\\n    \\\\,_0F_1(a,z) = \\\\sum_{k=0}^{\\\\infty} \\\\frac{1}{(a)_k} \\\\frac{z^k}{k!}.\\n\\nThis function satisfies the differential equation `z f''(z) + a f'(z) = f(z)`,\\nand is related to the Bessel function of the first kind (see :func:`~mpmath.besselj`).\\n\\n``hyp0f1(a,z)`` is equivalent to ``hyper([],[a],z)``; see documentation for\\n:func:`~mpmath.hyper` for more information.\\n\\n**Examples**\\n\\nEvaluation for arbitrary arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyp0f1(2, 0.25)\\n    1.130318207984970054415392\\n    >>> hyp0f1((1,2), 1234567)\\n    6.27287187546220705604627e+964\\n    >>> hyp0f1(3+4j, 1000000j)\\n    (3.905169561300910030267132e+606 + 3.807708544441684513934213e+606j)\\n\\nEvaluation is supported for arbitrarily large values of `z`,\\nusing asymptotic expansions::\\n\\n    >>> hyp0f1(1, 10**50)\\n    2.131705322874965310390701e+8685889638065036553022565\\n    >>> hyp0f1(1, -10**50)\\n    1.115945364792025420300208e-13\\n\\nVerifying the differential equation::\\n\\n    >>> a = 2.5\\n    >>> f = lambda z: hyp0f1(a,z)\\n    >>> for z in [0, 10, 3+4j]:\\n    ...     chop(z*diff(f,z,2) + a*diff(f,z) - f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\nhyp1f1 = r\\\"\\\"\\\"\\nGives the confluent hypergeometric function of the first kind,\\n\\n.. math ::\\n\\n    \\\\,_1F_1(a,b,z) = \\\\sum_{k=0}^{\\\\infty} \\\\frac{(a)_k}{(b)_k} \\\\frac{z^k}{k!},\\n\\nalso known as Kummer's function and sometimes denoted by `M(a,b,z)`. This\\nfunction gives one solution to the confluent (Kummer's) differential equation\\n\\n.. math ::\\n\\n    z f''(z) + (b-z) f'(z) - af(z) = 0.\\n\\nA second solution is given by the `U` function; see :func:`~mpmath.hyperu`.\\nSolutions are also given in an alternate form by the Whittaker\\nfunctions (:func:`~mpmath.whitm`, :func:`~mpmath.whitw`).\\n\\n``hyp1f1(a,b,z)`` is equivalent\\nto ``hyper([a],[b],z)``; see documentation for :func:`~mpmath.hyper` for more\\ninformation.\\n\\n**Examples**\\n\\nEvaluation for real and complex values of the argument `z`, with\\nfixed parameters `a = 2, b = -1/3`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyp1f1(2, (-1,3), 3.25)\\n    -2815.956856924817275640248\\n    >>> hyp1f1(2, (-1,3), -3.25)\\n    -1.145036502407444445553107\\n    >>> hyp1f1(2, (-1,3), 1000)\\n    -8.021799872770764149793693e+441\\n    >>> hyp1f1(2, (-1,3), -1000)\\n    0.000003131987633006813594535331\\n    >>> hyp1f1(2, (-1,3), 100+100j)\\n    (-3.189190365227034385898282e+48 - 1.106169926814270418999315e+49j)\\n\\nParameters may be complex::\\n\\n    >>> hyp1f1(2+3j, -1+j, 10j)\\n    (261.8977905181045142673351 + 160.8930312845682213562172j)\\n\\nArbitrarily large values of `z` are supported::\\n\\n    >>> hyp1f1(3, 4, 10**20)\\n    3.890569218254486878220752e+43429448190325182745\\n    >>> hyp1f1(3, 4, -10**20)\\n    6.0e-60\\n    >>> hyp1f1(3, 4, 10**20*j)\\n    (-1.935753855797342532571597e-20 - 2.291911213325184901239155e-20j)\\n\\nVerifying the differential equation::\\n\\n    >>> a, b = 1.5, 2\\n    >>> f = lambda z: hyp1f1(a,b,z)\\n    >>> for z in [0, -10, 3, 3+4j]:\\n    ...     chop(z*diff(f,z,2) + (b-z)*diff(f,z) - a*f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\nAn integral representation::\\n\\n    >>> a, b = 1.5, 3\\n    >>> z = 1.5\\n    >>> hyp1f1(a,b,z)\\n    2.269381460919952778587441\\n    >>> g = lambda t: exp(z*t)*t**(a-1)*(1-t)**(b-a-1)\\n    >>> gammaprod([b],[a,b-a])*quad(g, [0,1])\\n    2.269381460919952778587441\\n\\n\\n\\\"\\\"\\\"\\n\\nhyp1f2 = r\\\"\\\"\\\"\\nGives the hypergeometric function `\\\\,_1F_2(a_1,a_2;b_1,b_2; z)`.\\nThe call ``hyp1f2(a1,b1,b2,z)`` is equivalent to\\n``hyper([a1],[b1,b2],z)``.\\n\\nEvaluation works for complex and arbitrarily large arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> a, b, c = 1.5, (-1,3), 2.25\\n    >>> hyp1f2(a, b, c, 10**20)\\n    -1.159388148811981535941434e+8685889639\\n    >>> hyp1f2(a, b, c, -10**20)\\n    -12.60262607892655945795907\\n    >>> hyp1f2(a, b, c, 10**20*j)\\n    (4.237220401382240876065501e+6141851464 - 2.950930337531768015892987e+6141851464j)\\n    >>> hyp1f2(2+3j, -2j, 0.5j, 10-20j)\\n    (135881.9905586966432662004 - 86681.95885418079535738828j)\\n\\n\\\"\\\"\\\"\\n\\nhyp2f2 = r\\\"\\\"\\\"\\nGives the hypergeometric function `\\\\,_2F_2(a_1,a_2;b_1,b_2; z)`.\\nThe call ``hyp2f2(a1,a2,b1,b2,z)`` is equivalent to\\n``hyper([a1,a2],[b1,b2],z)``.\\n\\nEvaluation works for complex and arbitrarily large arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> a, b, c, d = 1.5, (-1,3), 2.25, 4\\n    >>> hyp2f2(a, b, c, d, 10**20)\\n    -5.275758229007902299823821e+43429448190325182663\\n    >>> hyp2f2(a, b, c, d, -10**20)\\n    2561445.079983207701073448\\n    >>> hyp2f2(a, b, c, d, 10**20*j)\\n    (2218276.509664121194836667 - 1280722.539991603850462856j)\\n    >>> hyp2f2(2+3j, -2j, 0.5j, 4j, 10-20j)\\n    (80500.68321405666957342788 - 20346.82752982813540993502j)\\n\\n\\\"\\\"\\\"\\n\\nhyp2f3 = r\\\"\\\"\\\"\\nGives the hypergeometric function `\\\\,_2F_3(a_1,a_2;b_1,b_2,b_3; z)`.\\nThe call ``hyp2f3(a1,a2,b1,b2,b3,z)`` is equivalent to\\n``hyper([a1,a2],[b1,b2,b3],z)``.\\n\\nEvaluation works for arbitrarily large arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> a1,a2,b1,b2,b3 = 1.5, (-1,3), 2.25, 4, (1,5)\\n    >>> hyp2f3(a1,a2,b1,b2,b3,10**20)\\n    -4.169178177065714963568963e+8685889590\\n    >>> hyp2f3(a1,a2,b1,b2,b3,-10**20)\\n    7064472.587757755088178629\\n    >>> hyp2f3(a1,a2,b1,b2,b3,10**20*j)\\n    (-5.163368465314934589818543e+6141851415 + 1.783578125755972803440364e+6141851416j)\\n    >>> hyp2f3(2+3j, -2j, 0.5j, 4j, -1-j, 10-20j)\\n    (-2280.938956687033150740228 + 13620.97336609573659199632j)\\n    >>> hyp2f3(2+3j, -2j, 0.5j, 4j, -1-j, 10000000-20000000j)\\n    (4.849835186175096516193e+3504 - 3.365981529122220091353633e+3504j)\\n\\n\\\"\\\"\\\"\\n\\nhyp2f1 = r\\\"\\\"\\\"\\nGives the Gauss hypergeometric function `\\\\,_2F_1` (often simply referred to as\\n*the* hypergeometric function), defined for `|z| < 1` as\\n\\n.. math ::\\n\\n    \\\\,_2F_1(a,b,c,z) = \\\\sum_{k=0}^{\\\\infty}\\n        \\\\frac{(a)_k (b)_k}{(c)_k} \\\\frac{z^k}{k!}.\\n\\nand for `|z| \\\\ge 1` by analytic continuation, with a branch cut on `(1, \\\\infty)`\\nwhen necessary.\\n\\nSpecial cases of this function include many of the orthogonal polynomials as\\nwell as the incomplete beta function and other functions. Properties of the\\nGauss hypergeometric function are documented comprehensively in many references,\\nfor example Abramowitz & Stegun, section 15.\\n\\nThe implementation supports the analytic continuation as well as evaluation\\nclose to the unit circle where `|z| \\\\approx 1`. The syntax ``hyp2f1(a,b,c,z)``\\nis equivalent to ``hyper([a,b],[c],z)``.\\n\\n**Examples**\\n\\nEvaluation with `z` inside, outside and on the unit circle, for\\nfixed parameters::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyp2f1(2, (1,2), 4, 0.75)\\n    1.303703703703703703703704\\n    >>> hyp2f1(2, (1,2), 4, -1.75)\\n    0.7431290566046919177853916\\n    >>> hyp2f1(2, (1,2), 4, 1.75)\\n    (1.418075801749271137026239 - 1.114976146679907015775102j)\\n    >>> hyp2f1(2, (1,2), 4, 1)\\n    1.6\\n    >>> hyp2f1(2, (1,2), 4, -1)\\n    0.8235498012182875315037882\\n    >>> hyp2f1(2, (1,2), 4, j)\\n    (0.9144026291433065674259078 + 0.2050415770437884900574923j)\\n    >>> hyp2f1(2, (1,2), 4, 2+j)\\n    (0.9274013540258103029011549 + 0.7455257875808100868984496j)\\n    >>> hyp2f1(2, (1,2), 4, 0.25j)\\n    (0.9931169055799728251931672 + 0.06154836525312066938147793j)\\n\\nEvaluation with complex parameter values::\\n\\n    >>> hyp2f1(1+j, 0.75, 10j, 1+5j)\\n    (0.8834833319713479923389638 + 0.7053886880648105068343509j)\\n\\nEvaluation with `z = 1`::\\n\\n    >>> hyp2f1(-2.5, 3.5, 1.5, 1)\\n    0.0\\n    >>> hyp2f1(-2.5, 3, 4, 1)\\n    0.06926406926406926406926407\\n    >>> hyp2f1(2, 3, 4, 1)\\n    +inf\\n\\nEvaluation for huge arguments::\\n\\n    >>> hyp2f1((-1,3), 1.75, 4, '1e100')\\n    (7.883714220959876246415651e+32 + 1.365499358305579597618785e+33j)\\n    >>> hyp2f1((-1,3), 1.75, 4, '1e1000000')\\n    (7.883714220959876246415651e+333332 + 1.365499358305579597618785e+333333j)\\n    >>> hyp2f1((-1,3), 1.75, 4, '1e1000000j')\\n    (1.365499358305579597618785e+333333 - 7.883714220959876246415651e+333332j)\\n\\nAn integral representation::\\n\\n    >>> a,b,c,z = -0.5, 1, 2.5, 0.25\\n    >>> g = lambda t: t**(b-1) * (1-t)**(c-b-1) * (1-t*z)**(-a)\\n    >>> gammaprod([c],[b,c-b]) * quad(g, [0,1])\\n    0.9480458814362824478852618\\n    >>> hyp2f1(a,b,c,z)\\n    0.9480458814362824478852618\\n\\nVerifying the hypergeometric differential equation::\\n\\n    >>> f = lambda z: hyp2f1(a,b,c,z)\\n    >>> chop(z*(1-z)*diff(f,z,2) + (c-(a+b+1)*z)*diff(f,z) - a*b*f(z))\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\nhyp3f2 = r\\\"\\\"\\\"\\nGives the generalized hypergeometric function `\\\\,_3F_2`, defined for `|z| < 1`\\nas\\n\\n.. math ::\\n\\n    \\\\,_3F_2(a_1,a_2,a_3,b_1,b_2,z) = \\\\sum_{k=0}^{\\\\infty}\\n        \\\\frac{(a_1)_k (a_2)_k (a_3)_k}{(b_1)_k (b_2)_k} \\\\frac{z^k}{k!}.\\n\\nand for `|z| \\\\ge 1` by analytic continuation. The analytic structure of this\\nfunction is similar to that of `\\\\,_2F_1`, generally with a singularity at\\n`z = 1` and a branch cut on `(1, \\\\infty)`.\\n\\nEvaluation is supported inside, on, and outside\\nthe circle of convergence `|z| = 1`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyp3f2(1,2,3,4,5,0.25)\\n    1.083533123380934241548707\\n    >>> hyp3f2(1,2+2j,3,4,5,-10+10j)\\n    (0.1574651066006004632914361 - 0.03194209021885226400892963j)\\n    >>> hyp3f2(1,2,3,4,5,-10)\\n    0.3071141169208772603266489\\n    >>> hyp3f2(1,2,3,4,5,10)\\n    (-0.4857045320523947050581423 - 0.5988311440454888436888028j)\\n    >>> hyp3f2(0.25,1,1,2,1.5,1)\\n    1.157370995096772047567631\\n    >>> (8-pi-2*ln2)/3\\n    1.157370995096772047567631\\n    >>> hyp3f2(1+j,0.5j,2,1,-2j,-1)\\n    (1.74518490615029486475959 + 0.1454701525056682297614029j)\\n    >>> hyp3f2(1+j,0.5j,2,1,-2j,sqrt(j))\\n    (0.9829816481834277511138055 - 0.4059040020276937085081127j)\\n    >>> hyp3f2(-3,2,1,-5,4,1)\\n    1.41\\n    >>> hyp3f2(-3,2,1,-5,4,2)\\n    2.12\\n\\nEvaluation very close to the unit circle::\\n\\n    >>> hyp3f2(1,2,3,4,5,'1.0001')\\n    (1.564877796743282766872279 - 3.76821518787438186031973e-11j)\\n    >>> hyp3f2(1,2,3,4,5,'1+0.0001j')\\n    (1.564747153061671573212831 + 0.0001305757570366084557648482j)\\n    >>> hyp3f2(1,2,3,4,5,'0.9999')\\n    1.564616644881686134983664\\n    >>> hyp3f2(1,2,3,4,5,'-0.9999')\\n    0.7823896253461678060196207\\n\\n.. note ::\\n\\n    Evaluation for `|z-1|` small can currently be inaccurate or slow\\n    for some parameter combinations.\\n\\nFor various parameter combinations, `\\\\,_3F_2` admits representation in terms\\nof hypergeometric functions of lower degree, or in terms of\\nsimpler functions::\\n\\n    >>> for a, b, z in [(1,2,-1), (2,0.5,1)]:\\n    ...     hyp2f1(a,b,a+b+0.5,z)**2\\n    ...     hyp3f2(2*a,a+b,2*b,a+b+0.5,2*a+2*b,z)\\n    ...\\n    0.4246104461966439006086308\\n    0.4246104461966439006086308\\n    7.111111111111111111111111\\n    7.111111111111111111111111\\n\\n    >>> z = 2+3j\\n    >>> hyp3f2(0.5,1,1.5,2,2,z)\\n    (0.7621440939243342419729144 + 0.4249117735058037649915723j)\\n    >>> 4*(pi-2*ellipe(z))/(pi*z)\\n    (0.7621440939243342419729144 + 0.4249117735058037649915723j)\\n\\n\\\"\\\"\\\"\\n\\nhyperu = r\\\"\\\"\\\"\\nGives the Tricomi confluent hypergeometric function `U`, also known as\\nthe Kummer or confluent hypergeometric function of the second kind. This\\nfunction gives a second linearly independent solution to the confluent\\nhypergeometric differential equation (the first is provided by `\\\\,_1F_1`  --\\nsee :func:`~mpmath.hyp1f1`).\\n\\n**Examples**\\n\\nEvaluation for arbitrary complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyperu(2,3,4)\\n    0.0625\\n    >>> hyperu(0.25, 5, 1000)\\n    0.1779949416140579573763523\\n    >>> hyperu(0.25, 5, -1000)\\n    (0.1256256609322773150118907 - 0.1256256609322773150118907j)\\n\\nThe `U` function may be singular at `z = 0`::\\n\\n    >>> hyperu(1.5, 2, 0)\\n    +inf\\n    >>> hyperu(1.5, -2, 0)\\n    0.1719434921288400112603671\\n\\nVerifying the differential equation::\\n\\n    >>> a, b = 1.5, 2\\n    >>> f = lambda z: hyperu(a,b,z)\\n    >>> for z in [-10, 3, 3+4j]:\\n    ...     chop(z*diff(f,z,2) + (b-z)*diff(f,z) - a*f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n\\nAn integral representation::\\n\\n    >>> a,b,z = 2, 3.5, 4.25\\n    >>> hyperu(a,b,z)\\n    0.06674960718150520648014567\\n    >>> quad(lambda t: exp(-z*t)*t**(a-1)*(1+t)**(b-a-1),[0,inf]) / gamma(a)\\n    0.06674960718150520648014567\\n\\n\\n[1] http://people.math.sfu.ca/~cbm/aands/page_504.htm\\n\\\"\\\"\\\"\\n\\nhyp2f0 = r\\\"\\\"\\\"\\nGives the hypergeometric function `\\\\,_2F_0`, defined formally by the\\nseries\\n\\n.. math ::\\n\\n    \\\\,_2F_0(a,b;;z) = \\\\sum_{n=0}^{\\\\infty} (a)_n (b)_n \\\\frac{z^n}{n!}.\\n\\nThis series usually does not converge. For small enough `z`, it can be viewed\\nas an asymptotic series that may be summed directly with an appropriate\\ntruncation. When this is not the case, :func:`~mpmath.hyp2f0` gives a regularized sum,\\nor equivalently, it uses a representation in terms of the\\nhypergeometric U function [1]. The series also converges when either `a` or `b`\\nis a nonpositive integer, as it then terminates into a polynomial\\nafter `-a` or `-b` terms.\\n\\n**Examples**\\n\\nEvaluation is supported for arbitrary complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hyp2f0((2,3), 1.25, -100)\\n    0.07095851870980052763312791\\n    >>> hyp2f0((2,3), 1.25, 100)\\n    (-0.03254379032170590665041131 + 0.07269254613282301012735797j)\\n    >>> hyp2f0(-0.75, 1-j, 4j)\\n    (-0.3579987031082732264862155 - 3.052951783922142735255881j)\\n\\nEven with real arguments, the regularized value of 2F0 is often complex-valued,\\nbut the imaginary part decreases exponentially as `z \\\\to 0`. In the following\\nexample, the first call uses complex evaluation while the second has a small\\nenough `z` to evaluate using the direct series and thus the returned value\\nis strictly real (this should be taken to indicate that the imaginary\\npart is less than ``eps``)::\\n\\n    >>> mp.dps = 15\\n    >>> hyp2f0(1.5, 0.5, 0.05)\\n    (1.04166637647907 + 8.34584913683906e-8j)\\n    >>> hyp2f0(1.5, 0.5, 0.0005)\\n    1.00037535207621\\n\\nThe imaginary part can be retrieved by increasing the working precision::\\n\\n    >>> mp.dps = 80\\n    >>> nprint(hyp2f0(1.5, 0.5, 0.009).imag)\\n    1.23828e-46\\n\\nIn the polynomial case (the series terminating), 2F0 can evaluate exactly::\\n\\n    >>> mp.dps = 15\\n    >>> hyp2f0(-6,-6,2)\\n    291793.0\\n    >>> identify(hyp2f0(-2,1,0.25))\\n    '(5/8)'\\n\\nThe coefficients of the polynomials can be recovered using Taylor expansion::\\n\\n    >>> nprint(taylor(lambda x: hyp2f0(-3,0.5,x), 0, 10))\\n    [1.0, -1.5, 2.25, -1.875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\\n    >>> nprint(taylor(lambda x: hyp2f0(-4,0.5,x), 0, 10))\\n    [1.0, -2.0, 4.5, -7.5, 6.5625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\\n\\n\\n[1] http://people.math.sfu.ca/~cbm/aands/page_504.htm\\n\\\"\\\"\\\"\\n\\n\\ngammainc = r\\\"\\\"\\\"\\n``gammainc(z, a=0, b=inf)`` computes the (generalized) incomplete\\ngamma function with integration limits `[a, b]`:\\n\\n.. math ::\\n\\n  \\\\Gamma(z,a,b) = \\\\int_a^b t^{z-1} e^{-t} \\\\, dt\\n\\nThe generalized incomplete gamma function reduces to the\\nfollowing special cases when one or both endpoints are fixed:\\n\\n* `\\\\Gamma(z,0,\\\\infty)` is the standard (\\\"complete\\\")\\n  gamma function, `\\\\Gamma(z)` (available directly\\n  as the mpmath function :func:`~mpmath.gamma`)\\n* `\\\\Gamma(z,a,\\\\infty)` is the \\\"upper\\\" incomplete gamma\\n  function, `\\\\Gamma(z,a)`\\n* `\\\\Gamma(z,0,b)` is the \\\"lower\\\" incomplete gamma\\n  function, `\\\\gamma(z,b)`.\\n\\nOf course, we have\\n`\\\\Gamma(z,0,x) + \\\\Gamma(z,x,\\\\infty) = \\\\Gamma(z)`\\nfor all `z` and `x`.\\n\\nNote however that some authors reverse the order of the\\narguments when defining the lower and upper incomplete\\ngamma function, so one should be careful to get the correct\\ndefinition.\\n\\nIf also given the keyword argument ``regularized=True``,\\n:func:`~mpmath.gammainc` computes the \\\"regularized\\\" incomplete gamma\\nfunction\\n\\n.. math ::\\n\\n  P(z,a,b) = \\\\frac{\\\\Gamma(z,a,b)}{\\\\Gamma(z)}.\\n\\n**Examples**\\n\\nWe can compare with numerical quadrature to verify that\\n:func:`~mpmath.gammainc` computes the integral in the definition::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> gammainc(2+3j, 4, 10)\\n    (0.00977212668627705160602312 - 0.0770637306312989892451977j)\\n    >>> quad(lambda t: t**(2+3j-1) * exp(-t), [4, 10])\\n    (0.00977212668627705160602312 - 0.0770637306312989892451977j)\\n\\nArgument symmetries follow directly from the integral definition::\\n\\n    >>> gammainc(3, 4, 5) + gammainc(3, 5, 4)\\n    0.0\\n    >>> gammainc(3,0,2) + gammainc(3,2,4); gammainc(3,0,4)\\n    1.523793388892911312363331\\n    1.523793388892911312363331\\n    >>> findroot(lambda z: gammainc(2,z,3), 1)\\n    3.0\\n\\nEvaluation for arbitrarily large arguments::\\n\\n    >>> gammainc(10, 100)\\n    4.083660630910611272288592e-26\\n    >>> gammainc(10, 10000000000000000)\\n    5.290402449901174752972486e-4342944819032375\\n    >>> gammainc(3+4j, 1000000+1000000j)\\n    (-1.257913707524362408877881e-434284 + 2.556691003883483531962095e-434284j)\\n\\nEvaluation of a generalized incomplete gamma function automatically chooses\\nthe representation that gives a more accurate result, depending on which\\nparameter is larger::\\n\\n    >>> gammainc(10000000, 3) - gammainc(10000000, 2)   # Bad\\n    0.0\\n    >>> gammainc(10000000, 2, 3)   # Good\\n    1.755146243738946045873491e+4771204\\n    >>> gammainc(2, 0, 100000001) - gammainc(2, 0, 100000000)   # Bad\\n    0.0\\n    >>> gammainc(2, 100000000, 100000001)   # Good\\n    4.078258353474186729184421e-43429441\\n\\nThe incomplete gamma functions satisfy simple recurrence\\nrelations::\\n\\n    >>> mp.dps = 25\\n    >>> z, a = mpf(3.5), mpf(2)\\n    >>> gammainc(z+1, a); z*gammainc(z,a) + a**z*exp(-a)\\n    10.60130296933533459267329\\n    10.60130296933533459267329\\n    >>> gammainc(z+1,0,a); z*gammainc(z,0,a) - a**z*exp(-a)\\n    1.030425427232114336470932\\n    1.030425427232114336470932\\n\\nEvaluation at integers and poles::\\n\\n    >>> gammainc(-3, -4, -5)\\n    (-0.2214577048967798566234192 + 0.0j)\\n    >>> gammainc(-3, 0, 5)\\n    +inf\\n\\nIf `z` is an integer, the recurrence reduces the incomplete gamma\\nfunction to `P(a) \\\\exp(-a) + Q(b) \\\\exp(-b)` where `P` and\\n`Q` are polynomials::\\n\\n    >>> gammainc(1, 2); exp(-2)\\n    0.1353352832366126918939995\\n    0.1353352832366126918939995\\n    >>> mp.dps = 50\\n    >>> identify(gammainc(6, 1, 2), ['exp(-1)', 'exp(-2)'])\\n    '(326*exp(-1) + (-872)*exp(-2))'\\n\\nThe incomplete gamma functions reduce to functions such as\\nthe exponential integral Ei and the error function for special\\narguments::\\n\\n    >>> mp.dps = 25\\n    >>> gammainc(0, 4); -ei(-4)\\n    0.00377935240984890647887486\\n    0.00377935240984890647887486\\n    >>> gammainc(0.5, 0, 2); sqrt(pi)*erf(sqrt(2))\\n    1.691806732945198336509541\\n    1.691806732945198336509541\\n\\n\\\"\\\"\\\"\\n\\nerf = r\\\"\\\"\\\"\\nComputes the error function, `\\\\mathrm{erf}(x)`. The error\\nfunction is the normalized antiderivative of the Gaussian function\\n`\\\\exp(-t^2)`. More precisely,\\n\\n.. math::\\n\\n  \\\\mathrm{erf}(x) = \\\\frac{2}{\\\\sqrt \\\\pi} \\\\int_0^x \\\\exp(-t^2) \\\\,dt\\n\\n**Basic examples**\\n\\nSimple values and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> erf(0)\\n    0.0\\n    >>> erf(1)\\n    0.842700792949715\\n    >>> erf(-1)\\n    -0.842700792949715\\n    >>> erf(inf)\\n    1.0\\n    >>> erf(-inf)\\n    -1.0\\n\\nFor large real `x`, `\\\\mathrm{erf}(x)` approaches 1 very\\nrapidly::\\n\\n    >>> erf(3)\\n    0.999977909503001\\n    >>> erf(5)\\n    0.999999999998463\\n\\nThe error function is an odd function::\\n\\n    >>> nprint(chop(taylor(erf, 0, 5)))\\n    [0.0, 1.12838, 0.0, -0.376126, 0.0, 0.112838]\\n\\n:func:`~mpmath.erf` implements arbitrary-precision evaluation and\\nsupports complex numbers::\\n\\n    >>> mp.dps = 50\\n    >>> erf(0.5)\\n    0.52049987781304653768274665389196452873645157575796\\n    >>> mp.dps = 25\\n    >>> erf(1+j)\\n    (1.316151281697947644880271 + 0.1904534692378346862841089j)\\n\\nEvaluation is supported for large arguments::\\n\\n    >>> mp.dps = 25\\n    >>> erf('1e1000')\\n    1.0\\n    >>> erf('-1e1000')\\n    -1.0\\n    >>> erf('1e-1000')\\n    1.128379167095512573896159e-1000\\n    >>> erf('1e7j')\\n    (0.0 + 8.593897639029319267398803e+43429448190317j)\\n    >>> erf('1e7+1e7j')\\n    (0.9999999858172446172631323 + 3.728805278735270407053139e-8j)\\n\\n**Related functions**\\n\\nSee also :func:`~mpmath.erfc`, which is more accurate for large `x`,\\nand :func:`~mpmath.erfi` which gives the antiderivative of\\n`\\\\exp(t^2)`.\\n\\nThe Fresnel integrals :func:`~mpmath.fresnels` and :func:`~mpmath.fresnelc`\\nare also related to the error function.\\n\\\"\\\"\\\"\\n\\nerfc = r\\\"\\\"\\\"\\nComputes the complementary error function,\\n`\\\\mathrm{erfc}(x) = 1-\\\\mathrm{erf}(x)`.\\nThis function avoids cancellation that occurs when naively\\ncomputing the complementary error function as ``1-erf(x)``::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> 1 - erf(10)\\n    0.0\\n    >>> erfc(10)\\n    2.08848758376254e-45\\n\\n:func:`~mpmath.erfc` works accurately even for ludicrously large\\narguments::\\n\\n    >>> erfc(10**10)\\n    4.3504398860243e-43429448190325182776\\n\\nComplex arguments are supported::\\n\\n    >>> erfc(500+50j)\\n    (1.19739830969552e-107492 + 1.46072418957528e-107491j)\\n\\n\\\"\\\"\\\"\\n\\n\\nerfi = r\\\"\\\"\\\"\\nComputes the imaginary error function, `\\\\mathrm{erfi}(x)`.\\nThe imaginary error function is defined in analogy with the\\nerror function, but with a positive sign in the integrand:\\n\\n.. math ::\\n\\n  \\\\mathrm{erfi}(x) = \\\\frac{2}{\\\\sqrt \\\\pi} \\\\int_0^x \\\\exp(t^2) \\\\,dt\\n\\nWhereas the error function rapidly converges to 1 as `x` grows,\\nthe imaginary error function rapidly diverges to infinity.\\nThe functions are related as\\n`\\\\mathrm{erfi}(x) = -i\\\\,\\\\mathrm{erf}(ix)` for all complex\\nnumbers `x`.\\n\\n**Examples**\\n\\nBasic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> erfi(0)\\n    0.0\\n    >>> erfi(1)\\n    1.65042575879754\\n    >>> erfi(-1)\\n    -1.65042575879754\\n    >>> erfi(inf)\\n    +inf\\n    >>> erfi(-inf)\\n    -inf\\n\\nNote the symmetry between erf and erfi::\\n\\n    >>> erfi(3j)\\n    (0.0 + 0.999977909503001j)\\n    >>> erf(3)\\n    0.999977909503001\\n    >>> erf(1+2j)\\n    (-0.536643565778565 - 5.04914370344703j)\\n    >>> erfi(2+1j)\\n    (-5.04914370344703 - 0.536643565778565j)\\n\\nLarge arguments are supported::\\n\\n    >>> erfi(1000)\\n    1.71130938718796e+434291\\n    >>> erfi(10**10)\\n    7.3167287567024e+43429448190325182754\\n    >>> erfi(-10**10)\\n    -7.3167287567024e+43429448190325182754\\n    >>> erfi(1000-500j)\\n    (2.49895233563961e+325717 + 2.6846779342253e+325717j)\\n    >>> erfi(100000j)\\n    (0.0 + 1.0j)\\n    >>> erfi(-100000j)\\n    (0.0 - 1.0j)\\n\\n\\n\\\"\\\"\\\"\\n\\nerfinv = r\\\"\\\"\\\"\\nComputes the inverse error function, satisfying\\n\\n.. math ::\\n\\n    \\\\mathrm{erf}(\\\\mathrm{erfinv}(x)) =\\n    \\\\mathrm{erfinv}(\\\\mathrm{erf}(x)) = x.\\n\\nThis function is defined only for `-1 \\\\le x \\\\le 1`.\\n\\n**Examples**\\n\\nSpecial values include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> erfinv(0)\\n    0.0\\n    >>> erfinv(1)\\n    +inf\\n    >>> erfinv(-1)\\n    -inf\\n\\nThe domain is limited to the standard interval::\\n\\n    >>> erfinv(2)\\n    Traceback (most recent call last):\\n      ...\\n    ValueError: erfinv(x) is defined only for -1 <= x <= 1\\n\\nIt is simple to check that :func:`~mpmath.erfinv` computes inverse values of\\n:func:`~mpmath.erf` as promised::\\n\\n    >>> erf(erfinv(0.75))\\n    0.75\\n    >>> erf(erfinv(-0.995))\\n    -0.995\\n\\n:func:`~mpmath.erfinv` supports arbitrary-precision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> x = erf(2)\\n    >>> x\\n    0.99532226501895273416206925636725292861089179704006\\n    >>> erfinv(x)\\n    2.0\\n\\nA definite integral involving the inverse error function::\\n\\n    >>> mp.dps = 15\\n    >>> quad(erfinv, [0, 1])\\n    0.564189583547756\\n    >>> 1/sqrt(pi)\\n    0.564189583547756\\n\\nThe inverse error function can be used to generate random numbers\\nwith a Gaussian distribution (although this is a relatively\\ninefficient algorithm)::\\n\\n    >>> nprint([erfinv(2*rand()-1) for n in range(6)]) # doctest: +SKIP\\n    [-0.586747, 1.10233, -0.376796, 0.926037, -0.708142, -0.732012]\\n\\n\\\"\\\"\\\"\\n\\nnpdf = r\\\"\\\"\\\"\\n``npdf(x, mu=0, sigma=1)`` evaluates the probability density\\nfunction of a normal distribution with mean value `\\\\mu`\\nand variance `\\\\sigma^2`.\\n\\nElementary properties of the probability distribution can\\nbe verified using numerical integration::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> quad(npdf, [-inf, inf])\\n    1.0\\n    >>> quad(lambda x: npdf(x, 3), [3, inf])\\n    0.5\\n    >>> quad(lambda x: npdf(x, 3, 2), [3, inf])\\n    0.5\\n\\nSee also :func:`~mpmath.ncdf`, which gives the cumulative\\ndistribution.\\n\\\"\\\"\\\"\\n\\nncdf = r\\\"\\\"\\\"\\n``ncdf(x, mu=0, sigma=1)`` evaluates the cumulative distribution\\nfunction of a normal distribution with mean value `\\\\mu`\\nand variance `\\\\sigma^2`.\\n\\nSee also :func:`~mpmath.npdf`, which gives the probability density.\\n\\nElementary properties include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> ncdf(pi, mu=pi)\\n    0.5\\n    >>> ncdf(-inf)\\n    0.0\\n    >>> ncdf(+inf)\\n    1.0\\n\\nThe cumulative distribution is the integral of the density\\nfunction having identical mu and sigma::\\n\\n    >>> mp.dps = 15\\n    >>> diff(ncdf, 2)\\n    0.053990966513188\\n    >>> npdf(2)\\n    0.053990966513188\\n    >>> diff(lambda x: ncdf(x, 1, 0.5), 0)\\n    0.107981933026376\\n    >>> npdf(0, 1, 0.5)\\n    0.107981933026376\\n\\\"\\\"\\\"\\n\\nexpint = r\\\"\\\"\\\"\\n:func:`~mpmath.expint(n,z)` gives the generalized exponential integral\\nor En-function,\\n\\n.. math ::\\n\\n    \\\\mathrm{E}_n(z) = \\\\int_1^{\\\\infty} \\\\frac{e^{-zt}}{t^n} dt,\\n\\nwhere `n` and `z` may both be complex numbers. The case with `n = 1` is\\nalso given by :func:`~mpmath.e1`.\\n\\n**Examples**\\n\\nEvaluation at real and complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> expint(1, 6.25)\\n    0.0002704758872637179088496194\\n    >>> expint(-3, 2+3j)\\n    (0.00299658467335472929656159 + 0.06100816202125885450319632j)\\n    >>> expint(2+3j, 4-5j)\\n    (0.001803529474663565056945248 - 0.002235061547756185403349091j)\\n\\nAt negative integer values of `n`, `E_n(z)` reduces to a\\nrational-exponential function::\\n\\n    >>> f = lambda n, z: fac(n)*sum(z**k/fac(k-1) for k in range(1,n+2))/\\\\\\n    ...     exp(z)/z**(n+2)\\n    >>> n = 3\\n    >>> z = 1/pi\\n    >>> expint(-n,z)\\n    584.2604820613019908668219\\n    >>> f(n,z)\\n    584.2604820613019908668219\\n    >>> n = 5\\n    >>> expint(-n,z)\\n    115366.5762594725451811138\\n    >>> f(n,z)\\n    115366.5762594725451811138\\n\\\"\\\"\\\"\\n\\ne1 = r\\\"\\\"\\\"\\nComputes the exponential integral `\\\\mathrm{E}_1(z)`, given by\\n\\n.. math ::\\n\\n    \\\\mathrm{E}_1(z) = \\\\int_z^{\\\\infty} \\\\frac{e^{-t}}{t} dt.\\n\\nThis is equivalent to :func:`~mpmath.expint` with `n = 1`.\\n\\n**Examples**\\n\\nTwo ways to evaluate this function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> e1(6.25)\\n    0.0002704758872637179088496194\\n    >>> expint(1,6.25)\\n    0.0002704758872637179088496194\\n\\nThe E1-function is essentially the same as the Ei-function (:func:`~mpmath.ei`)\\nwith negated argument, except for an imaginary branch cut term::\\n\\n    >>> e1(2.5)\\n    0.02491491787026973549562801\\n    >>> -ei(-2.5)\\n    0.02491491787026973549562801\\n    >>> e1(-2.5)\\n    (-7.073765894578600711923552 - 3.141592653589793238462643j)\\n    >>> -ei(2.5)\\n    -7.073765894578600711923552\\n\\n\\\"\\\"\\\"\\n\\nei = r\\\"\\\"\\\"\\nComputes the exponential integral or Ei-function, `\\\\mathrm{Ei}(x)`.\\nThe exponential integral is defined as\\n\\n.. math ::\\n\\n  \\\\mathrm{Ei}(x) = \\\\int_{-\\\\infty\\\\,}^x \\\\frac{e^t}{t} \\\\, dt.\\n\\nWhen the integration range includes `t = 0`, the exponential\\nintegral is interpreted as providing the Cauchy principal value.\\n\\nFor real `x`, the Ei-function behaves roughly like\\n`\\\\mathrm{Ei}(x) \\\\approx \\\\exp(x) + \\\\log(|x|)`.\\n\\nThe Ei-function is related to the more general family of exponential\\nintegral functions denoted by `E_n`, which are available as :func:`~mpmath.expint`.\\n\\n**Basic examples**\\n\\nSome basic values and limits are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> ei(0)\\n    -inf\\n    >>> ei(1)\\n    1.89511781635594\\n    >>> ei(inf)\\n    +inf\\n    >>> ei(-inf)\\n    0.0\\n\\nFor `x < 0`, the defining integral can be evaluated\\nnumerically as a reference::\\n\\n    >>> ei(-4)\\n    -0.00377935240984891\\n    >>> quad(lambda t: exp(t)/t, [-inf, -4])\\n    -0.00377935240984891\\n\\n:func:`~mpmath.ei` supports complex arguments and arbitrary\\nprecision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> ei(pi)\\n    10.928374389331410348638445906907535171566338835056\\n    >>> mp.dps = 25\\n    >>> ei(3+4j)\\n    (-4.154091651642689822535359 + 4.294418620024357476985535j)\\n\\n**Related functions**\\n\\nThe exponential integral is closely related to the logarithmic\\nintegral. See :func:`~mpmath.li` for additional information.\\n\\nThe exponential integral is related to the hyperbolic\\nand trigonometric integrals (see :func:`~mpmath.chi`, :func:`~mpmath.shi`,\\n:func:`~mpmath.ci`, :func:`~mpmath.si`) similarly to how the ordinary\\nexponential function is related to the hyperbolic and\\ntrigonometric functions::\\n\\n    >>> mp.dps = 15\\n    >>> ei(3)\\n    9.93383257062542\\n    >>> chi(3) + shi(3)\\n    9.93383257062542\\n    >>> chop(ci(3j) - j*si(3j) - pi*j/2)\\n    9.93383257062542\\n\\nBeware that logarithmic corrections, as in the last example\\nabove, are required to obtain the correct branch in general.\\nFor details, see [1].\\n\\nThe exponential integral is also a special case of the\\nhypergeometric function `\\\\,_2F_2`::\\n\\n    >>> z = 0.6\\n    >>> z*hyper([1,1],[2,2],z) + (ln(z)-ln(1/z))/2 + euler\\n    0.769881289937359\\n    >>> ei(z)\\n    0.769881289937359\\n\\n**References**\\n\\n1. Relations between Ei and other functions:\\n   http://functions.wolfram.com/GammaBetaErf/ExpIntegralEi/27/01/\\n\\n2. Abramowitz & Stegun, section 5:\\n   http://people.math.sfu.ca/~cbm/aands/page_228.htm\\n\\n3. Asymptotic expansion for Ei:\\n   http://mathworld.wolfram.com/En-Function.html\\n\\\"\\\"\\\"\\n\\nli = r\\\"\\\"\\\"\\nComputes the logarithmic integral or li-function\\n`\\\\mathrm{li}(x)`, defined by\\n\\n.. math ::\\n\\n    \\\\mathrm{li}(x) = \\\\int_0^x \\\\frac{1}{\\\\log t} \\\\, dt\\n\\nThe logarithmic integral has a singularity at `x = 1`.\\n\\nAlternatively, ``li(x, offset=True)`` computes the offset\\nlogarithmic integral (used in number theory)\\n\\n.. math ::\\n\\n    \\\\mathrm{Li}(x) = \\\\int_2^x \\\\frac{1}{\\\\log t} \\\\, dt.\\n\\nThese two functions are related via the simple identity\\n`\\\\mathrm{Li}(x) = \\\\mathrm{li}(x) - \\\\mathrm{li}(2)`.\\n\\nThe logarithmic integral should also not be confused with\\nthe polylogarithm (also denoted by Li), which is implemented\\nas :func:`~mpmath.polylog`.\\n\\n**Examples**\\n\\nSome basic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 30; mp.pretty = True\\n    >>> li(0)\\n    0.0\\n    >>> li(1)\\n    -inf\\n    >>> li(1)\\n    -inf\\n    >>> li(2)\\n    1.04516378011749278484458888919\\n    >>> findroot(li, 2)\\n    1.45136923488338105028396848589\\n    >>> li(inf)\\n    +inf\\n    >>> li(2, offset=True)\\n    0.0\\n    >>> li(1, offset=True)\\n    -inf\\n    >>> li(0, offset=True)\\n    -1.04516378011749278484458888919\\n    >>> li(10, offset=True)\\n    5.12043572466980515267839286347\\n\\nThe logarithmic integral can be evaluated for arbitrary\\ncomplex arguments::\\n\\n    >>> mp.dps = 20\\n    >>> li(3+4j)\\n    (3.1343755504645775265 + 2.6769247817778742392j)\\n\\nThe logarithmic integral is related to the exponential integral::\\n\\n    >>> ei(log(3))\\n    2.1635885946671919729\\n    >>> li(3)\\n    2.1635885946671919729\\n\\nThe logarithmic integral grows like `O(x/\\\\log(x))`::\\n\\n    >>> mp.dps = 15\\n    >>> x = 10**100\\n    >>> x/log(x)\\n    4.34294481903252e+97\\n    >>> li(x)\\n    4.3619719871407e+97\\n\\nThe prime number theorem states that the number of primes less\\nthan `x` is asymptotic to `\\\\mathrm{Li}(x)` (equivalently\\n`\\\\mathrm{li}(x)`). For example, it is known that there are\\nexactly 1,925,320,391,606,803,968,923 prime numbers less than\\n`10^{23}` [1]. The logarithmic integral provides a very\\naccurate estimate::\\n\\n    >>> li(10**23, offset=True)\\n    1.92532039161405e+21\\n\\nA definite integral is::\\n\\n    >>> quad(li, [0, 1])\\n    -0.693147180559945\\n    >>> -ln(2)\\n    -0.693147180559945\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/PrimeCountingFunction.html\\n\\n2. http://mathworld.wolfram.com/LogarithmicIntegral.html\\n\\n\\\"\\\"\\\"\\n\\nci = r\\\"\\\"\\\"\\nComputes the cosine integral,\\n\\n.. math ::\\n\\n    \\\\mathrm{Ci}(x) = -\\\\int_x^{\\\\infty} \\\\frac{\\\\cos t}{t}\\\\,dt\\n    = \\\\gamma + \\\\log x + \\\\int_0^x \\\\frac{\\\\cos t - 1}{t}\\\\,dt\\n\\n**Examples**\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> ci(0)\\n    -inf\\n    >>> ci(1)\\n    0.3374039229009681346626462\\n    >>> ci(pi)\\n    0.07366791204642548599010096\\n    >>> ci(inf)\\n    0.0\\n    >>> ci(-inf)\\n    (0.0 + 3.141592653589793238462643j)\\n    >>> ci(2+3j)\\n    (1.408292501520849518759125 - 2.983617742029605093121118j)\\n\\nThe cosine integral behaves roughly like the sinc function\\n(see :func:`~mpmath.sinc`) for large real `x`::\\n\\n    >>> ci(10**10)\\n    -4.875060251748226537857298e-11\\n    >>> sinc(10**10)\\n    -4.875060250875106915277943e-11\\n    >>> chop(limit(ci, inf))\\n    0.0\\n\\nIt has infinitely many roots on the positive real axis::\\n\\n    >>> findroot(ci, 1)\\n    0.6165054856207162337971104\\n    >>> findroot(ci, 2)\\n    3.384180422551186426397851\\n\\nEvaluation is supported for `z` anywhere in the complex plane::\\n\\n    >>> ci(10**6*(1+j))\\n    (4.449410587611035724984376e+434287 + 9.75744874290013526417059e+434287j)\\n\\nWe can evaluate the defining integral as a reference::\\n\\n    >>> mp.dps = 15\\n    >>> -quadosc(lambda t: cos(t)/t, [5, inf], omega=1)\\n    -0.190029749656644\\n    >>> ci(5)\\n    -0.190029749656644\\n\\nSome infinite series can be evaluated using the\\ncosine integral::\\n\\n    >>> nsum(lambda k: (-1)**k/(fac(2*k)*(2*k)), [1,inf])\\n    -0.239811742000565\\n    >>> ci(1) - euler\\n    -0.239811742000565\\n\\n\\\"\\\"\\\"\\n\\nsi = r\\\"\\\"\\\"\\nComputes the sine integral,\\n\\n.. math ::\\n\\n    \\\\mathrm{Si}(x) = \\\\int_0^x \\\\frac{\\\\sin t}{t}\\\\,dt.\\n\\nThe sine integral is thus the antiderivative of the sinc\\nfunction (see :func:`~mpmath.sinc`).\\n\\n**Examples**\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> si(0)\\n    0.0\\n    >>> si(1)\\n    0.9460830703671830149413533\\n    >>> si(-1)\\n    -0.9460830703671830149413533\\n    >>> si(pi)\\n    1.851937051982466170361053\\n    >>> si(inf)\\n    1.570796326794896619231322\\n    >>> si(-inf)\\n    -1.570796326794896619231322\\n    >>> si(2+3j)\\n    (4.547513889562289219853204 + 1.399196580646054789459839j)\\n\\nThe sine integral approaches `\\\\pi/2` for large real `x`::\\n\\n    >>> si(10**10)\\n    1.570796326707584656968511\\n    >>> pi/2\\n    1.570796326794896619231322\\n\\nEvaluation is supported for `z` anywhere in the complex plane::\\n\\n    >>> si(10**6*(1+j))\\n    (-9.75744874290013526417059e+434287 + 4.449410587611035724984376e+434287j)\\n\\nWe can evaluate the defining integral as a reference::\\n\\n    >>> mp.dps = 15\\n    >>> quad(sinc, [0, 5])\\n    1.54993124494467\\n    >>> si(5)\\n    1.54993124494467\\n\\nSome infinite series can be evaluated using the\\nsine integral::\\n\\n    >>> nsum(lambda k: (-1)**k/(fac(2*k+1)*(2*k+1)), [0,inf])\\n    0.946083070367183\\n    >>> si(1)\\n    0.946083070367183\\n\\n\\\"\\\"\\\"\\n\\nchi = r\\\"\\\"\\\"\\nComputes the hyperbolic cosine integral, defined\\nin analogy with the cosine integral (see :func:`~mpmath.ci`) as\\n\\n.. math ::\\n\\n    \\\\mathrm{Chi}(x) = -\\\\int_x^{\\\\infty} \\\\frac{\\\\cosh t}{t}\\\\,dt\\n    = \\\\gamma + \\\\log x + \\\\int_0^x \\\\frac{\\\\cosh t - 1}{t}\\\\,dt\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> chi(0)\\n    -inf\\n    >>> chi(1)\\n    0.8378669409802082408946786\\n    >>> chi(inf)\\n    +inf\\n    >>> findroot(chi, 0.5)\\n    0.5238225713898644064509583\\n    >>> chi(2+3j)\\n    (-0.1683628683277204662429321 + 2.625115880451325002151688j)\\n\\nEvaluation is supported for `z` anywhere in the complex plane::\\n\\n    >>> chi(10**6*(1+j))\\n    (4.449410587611035724984376e+434287 - 9.75744874290013526417059e+434287j)\\n\\n\\\"\\\"\\\"\\n\\nshi = r\\\"\\\"\\\"\\nComputes the hyperbolic sine integral, defined\\nin analogy with the sine integral (see :func:`~mpmath.si`) as\\n\\n.. math ::\\n\\n    \\\\mathrm{Shi}(x) = \\\\int_0^x \\\\frac{\\\\sinh t}{t}\\\\,dt.\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> shi(0)\\n    0.0\\n    >>> shi(1)\\n    1.057250875375728514571842\\n    >>> shi(-1)\\n    -1.057250875375728514571842\\n    >>> shi(inf)\\n    +inf\\n    >>> shi(2+3j)\\n    (-0.1931890762719198291678095 + 2.645432555362369624818525j)\\n\\nEvaluation is supported for `z` anywhere in the complex plane::\\n\\n    >>> shi(10**6*(1+j))\\n    (4.449410587611035724984376e+434287 - 9.75744874290013526417059e+434287j)\\n\\n\\\"\\\"\\\"\\n\\nfresnels = r\\\"\\\"\\\"\\nComputes the Fresnel sine integral\\n\\n.. math ::\\n\\n    S(x) = \\\\int_0^x \\\\sin\\\\left(\\\\frac{\\\\pi t^2}{2}\\\\right) \\\\,dt\\n\\nNote that some sources define this function\\nwithout the normalization factor `\\\\pi/2`.\\n\\n**Examples**\\n\\nSome basic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> fresnels(0)\\n    0.0\\n    >>> fresnels(inf)\\n    0.5\\n    >>> fresnels(-inf)\\n    -0.5\\n    >>> fresnels(1)\\n    0.4382591473903547660767567\\n    >>> fresnels(1+2j)\\n    (36.72546488399143842838788 + 15.58775110440458732748279j)\\n\\nComparing with the definition::\\n\\n    >>> fresnels(3)\\n    0.4963129989673750360976123\\n    >>> quad(lambda t: sin(pi*t**2/2), [0,3])\\n    0.4963129989673750360976123\\n\\\"\\\"\\\"\\n\\nfresnelc = r\\\"\\\"\\\"\\nComputes the Fresnel cosine integral\\n\\n.. math ::\\n\\n    C(x) = \\\\int_0^x \\\\cos\\\\left(\\\\frac{\\\\pi t^2}{2}\\\\right) \\\\,dt\\n\\nNote that some sources define this function\\nwithout the normalization factor `\\\\pi/2`.\\n\\n**Examples**\\n\\nSome basic values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> fresnelc(0)\\n    0.0\\n    >>> fresnelc(inf)\\n    0.5\\n    >>> fresnelc(-inf)\\n    -0.5\\n    >>> fresnelc(1)\\n    0.7798934003768228294742064\\n    >>> fresnelc(1+2j)\\n    (16.08787137412548041729489 - 36.22568799288165021578758j)\\n\\nComparing with the definition::\\n\\n    >>> fresnelc(3)\\n    0.6057207892976856295561611\\n    >>> quad(lambda t: cos(pi*t**2/2), [0,3])\\n    0.6057207892976856295561611\\n\\\"\\\"\\\"\\n\\nairyai = r\\\"\\\"\\\"\\nComputes the Airy function `\\\\operatorname{Ai}(z)`, which is\\nthe solution of the Airy differential equation `f''(z) - z f(z) = 0`\\nwith initial conditions\\n\\n.. math ::\\n\\n    \\\\operatorname{Ai}(0) =\\n        \\\\frac{1}{3^{2/3}\\\\Gamma\\\\left(\\\\frac{2}{3}\\\\right)}\\n\\n    \\\\operatorname{Ai}'(0) =\\n        -\\\\frac{1}{3^{1/3}\\\\Gamma\\\\left(\\\\frac{1}{3}\\\\right)}.\\n\\nOther common ways of defining the Ai-function include\\nintegrals such as\\n\\n.. math ::\\n\\n    \\\\operatorname{Ai}(x) = \\\\frac{1}{\\\\pi}\\n        \\\\int_0^{\\\\infty} \\\\cos\\\\left(\\\\frac{1}{3}t^3+xt\\\\right) dt\\n        \\\\qquad x \\\\in \\\\mathbb{R}\\n\\n    \\\\operatorname{Ai}(z) = \\\\frac{\\\\sqrt{3}}{2\\\\pi}\\n        \\\\int_0^{\\\\infty}\\n        \\\\exp\\\\left(-\\\\frac{t^3}{3}-\\\\frac{z^3}{3t^3}\\\\right) dt.\\n\\nThe Ai-function is an entire function with a turning point,\\nbehaving roughly like a slowly decaying sine wave for `z < 0` and\\nlike a rapidly decreasing exponential for `z > 0`.\\nA second solution of the Airy differential equation\\nis given by `\\\\operatorname{Bi}(z)` (see :func:`~mpmath.airybi`).\\n\\nOptionally, with *derivative=alpha*, :func:`airyai` can compute the\\n`\\\\alpha`-th order fractional derivative with respect to `z`.\\nFor `\\\\alpha = n = 1,2,3,\\\\ldots` this gives the derivative\\n`\\\\operatorname{Ai}^{(n)}(z)`, and for `\\\\alpha = -n = -1,-2,-3,\\\\ldots`\\nthis gives the `n`-fold iterated integral\\n\\n.. math ::\\n\\n    f_0(z) = \\\\operatorname{Ai}(z)\\n\\n    f_n(z) = \\\\int_0^z f_{n-1}(t) dt.\\n\\nThe Ai-function has infinitely many zeros, all located along the\\nnegative half of the real axis. They can be computed with\\n:func:`~mpmath.airyaizero`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/ai.py\\n.. image :: /plots/ai.png\\n.. literalinclude :: /plots/ai_c.py\\n.. image :: /plots/ai_c.png\\n\\n**Basic examples**\\n\\nLimits and values include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> airyai(0); 1/(power(3,'2/3')*gamma('2/3'))\\n    0.3550280538878172392600632\\n    0.3550280538878172392600632\\n    >>> airyai(1)\\n    0.1352924163128814155241474\\n    >>> airyai(-1)\\n    0.5355608832923521187995166\\n    >>> airyai(inf); airyai(-inf)\\n    0.0\\n    0.0\\n\\nEvaluation is supported for large magnitudes of the argument::\\n\\n    >>> airyai(-100)\\n    0.1767533932395528780908311\\n    >>> airyai(100)\\n    2.634482152088184489550553e-291\\n    >>> airyai(50+50j)\\n    (-5.31790195707456404099817e-68 - 1.163588003770709748720107e-67j)\\n    >>> airyai(-50+50j)\\n    (1.041242537363167632587245e+158 + 3.347525544923600321838281e+157j)\\n\\nHuge arguments are also fine::\\n\\n    >>> airyai(10**10)\\n    1.162235978298741779953693e-289529654602171\\n    >>> airyai(-10**10)\\n    0.0001736206448152818510510181\\n    >>> w = airyai(10**10*(1+j))\\n    >>> w.real\\n    5.711508683721355528322567e-186339621747698\\n    >>> w.imag\\n    1.867245506962312577848166e-186339621747697\\n\\nThe first root of the Ai-function is::\\n\\n    >>> findroot(airyai, -2)\\n    -2.338107410459767038489197\\n    >>> airyaizero(1)\\n    -2.338107410459767038489197\\n\\n**Properties and relations**\\n\\nVerifying the Airy differential equation::\\n\\n    >>> for z in [-3.4, 0, 2.5, 1+2j]:\\n    ...     chop(airyai(z,2) - z*airyai(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\nThe first few terms of the Taylor series expansion around `z = 0`\\n(every third term is zero)::\\n\\n    >>> nprint(taylor(airyai, 0, 5))\\n    [0.355028, -0.258819, 0.0, 0.0591713, -0.0215683, 0.0]\\n\\nThe Airy functions satisfy the Wronskian relation\\n`\\\\operatorname{Ai}(z) \\\\operatorname{Bi}'(z) -\\n\\\\operatorname{Ai}'(z) \\\\operatorname{Bi}(z) = 1/\\\\pi`::\\n\\n    >>> z = -0.5\\n    >>> airyai(z)*airybi(z,1) - airyai(z,1)*airybi(z)\\n    0.3183098861837906715377675\\n    >>> 1/pi\\n    0.3183098861837906715377675\\n\\nThe Airy functions can be expressed in terms of Bessel\\nfunctions of order `\\\\pm 1/3`. For `\\\\Re[z] \\\\le 0`, we have::\\n\\n    >>> z = -3\\n    >>> airyai(z)\\n    -0.3788142936776580743472439\\n    >>> y = 2*power(-z,'3/2')/3\\n    >>> (sqrt(-z) * (besselj('1/3',y) + besselj('-1/3',y)))/3\\n    -0.3788142936776580743472439\\n\\n**Derivatives and integrals**\\n\\nDerivatives of the Ai-function (directly and using :func:`~mpmath.diff`)::\\n\\n    >>> airyai(-3,1); diff(airyai,-3)\\n    0.3145837692165988136507873\\n    0.3145837692165988136507873\\n    >>> airyai(-3,2); diff(airyai,-3,2)\\n    1.136442881032974223041732\\n    1.136442881032974223041732\\n    >>> airyai(1000,1); diff(airyai,1000)\\n    -2.943133917910336090459748e-9156\\n    -2.943133917910336090459748e-9156\\n\\nSeveral derivatives at `z = 0`::\\n\\n    >>> airyai(0,0); airyai(0,1); airyai(0,2)\\n    0.3550280538878172392600632\\n    -0.2588194037928067984051836\\n    0.0\\n    >>> airyai(0,3); airyai(0,4); airyai(0,5)\\n    0.3550280538878172392600632\\n    -0.5176388075856135968103671\\n    0.0\\n    >>> airyai(0,15); airyai(0,16); airyai(0,17)\\n    1292.30211615165475090663\\n    -3188.655054727379756351861\\n    0.0\\n\\nThe integral of the Ai-function::\\n\\n    >>> airyai(3,-1); quad(airyai, [0,3])\\n    0.3299203760070217725002701\\n    0.3299203760070217725002701\\n    >>> airyai(-10,-1); quad(airyai, [0,-10])\\n    -0.765698403134212917425148\\n    -0.765698403134212917425148\\n\\nIntegrals of high or fractional order::\\n\\n    >>> airyai(-2,0.5); differint(airyai,-2,0.5,0)\\n    (0.0 + 0.2453596101351438273844725j)\\n    (0.0 + 0.2453596101351438273844725j)\\n    >>> airyai(-2,-4); differint(airyai,-2,-4,0)\\n    0.2939176441636809580339365\\n    0.2939176441636809580339365\\n    >>> airyai(0,-1); airyai(0,-2); airyai(0,-3)\\n    0.0\\n    0.0\\n    0.0\\n\\nIntegrals of the Ai-function can be evaluated at limit points::\\n\\n    >>> airyai(-1000000,-1); airyai(-inf,-1)\\n    -0.6666843728311539978751512\\n    -0.6666666666666666666666667\\n    >>> airyai(10,-1); airyai(+inf,-1)\\n    0.3333333332991690159427932\\n    0.3333333333333333333333333\\n    >>> airyai(+inf,-2); airyai(+inf,-3)\\n    +inf\\n    +inf\\n    >>> airyai(-1000000,-2); airyai(-inf,-2)\\n    666666.4078472650651209742\\n    +inf\\n    >>> airyai(-1000000,-3); airyai(-inf,-3)\\n    -333333074513.7520264995733\\n    -inf\\n\\n**References**\\n\\n1. [DLMF]_ Chapter 9: Airy and Related Functions\\n2. [WolframFunctions]_ section: Bessel-Type Functions\\n\\n\\\"\\\"\\\"\\n\\nairybi = r\\\"\\\"\\\"\\nComputes the Airy function `\\\\operatorname{Bi}(z)`, which is\\nthe solution of the Airy differential equation `f''(z) - z f(z) = 0`\\nwith initial conditions\\n\\n.. math ::\\n\\n    \\\\operatorname{Bi}(0) =\\n        \\\\frac{1}{3^{1/6}\\\\Gamma\\\\left(\\\\frac{2}{3}\\\\right)}\\n\\n    \\\\operatorname{Bi}'(0) =\\n        \\\\frac{3^{1/6}}{\\\\Gamma\\\\left(\\\\frac{1}{3}\\\\right)}.\\n\\nLike the Ai-function (see :func:`~mpmath.airyai`), the Bi-function\\nis oscillatory for `z < 0`, but it grows rather than decreases\\nfor `z > 0`.\\n\\nOptionally, as for :func:`~mpmath.airyai`, derivatives, integrals\\nand fractional derivatives can be computed with the *derivative*\\nparameter.\\n\\nThe Bi-function has infinitely many zeros along the negative\\nhalf-axis, as well as complex zeros, which can all be computed\\nwith :func:`~mpmath.airybizero`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/bi.py\\n.. image :: /plots/bi.png\\n.. literalinclude :: /plots/bi_c.py\\n.. image :: /plots/bi_c.png\\n\\n**Basic examples**\\n\\nLimits and values include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> airybi(0); 1/(power(3,'1/6')*gamma('2/3'))\\n    0.6149266274460007351509224\\n    0.6149266274460007351509224\\n    >>> airybi(1)\\n    1.207423594952871259436379\\n    >>> airybi(-1)\\n    0.10399738949694461188869\\n    >>> airybi(inf); airybi(-inf)\\n    +inf\\n    0.0\\n\\nEvaluation is supported for large magnitudes of the argument::\\n\\n    >>> airybi(-100)\\n    0.02427388768016013160566747\\n    >>> airybi(100)\\n    6.041223996670201399005265e+288\\n    >>> airybi(50+50j)\\n    (-5.322076267321435669290334e+63 + 1.478450291165243789749427e+65j)\\n    >>> airybi(-50+50j)\\n    (-3.347525544923600321838281e+157 + 1.041242537363167632587245e+158j)\\n\\nHuge arguments::\\n\\n    >>> airybi(10**10)\\n    1.369385787943539818688433e+289529654602165\\n    >>> airybi(-10**10)\\n    0.001775656141692932747610973\\n    >>> w = airybi(10**10*(1+j))\\n    >>> w.real\\n    -6.559955931096196875845858e+186339621747689\\n    >>> w.imag\\n    -6.822462726981357180929024e+186339621747690\\n\\nThe first real root of the Bi-function is::\\n\\n    >>> findroot(airybi, -1); airybizero(1)\\n    -1.17371322270912792491998\\n    -1.17371322270912792491998\\n\\n**Properties and relations**\\n\\nVerifying the Airy differential equation::\\n\\n    >>> for z in [-3.4, 0, 2.5, 1+2j]:\\n    ...     chop(airybi(z,2) - z*airybi(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\nThe first few terms of the Taylor series expansion around `z = 0`\\n(every third term is zero)::\\n\\n    >>> nprint(taylor(airybi, 0, 5))\\n    [0.614927, 0.448288, 0.0, 0.102488, 0.0373574, 0.0]\\n\\nThe Airy functions can be expressed in terms of Bessel\\nfunctions of order `\\\\pm 1/3`. For `\\\\Re[z] \\\\le 0`, we have::\\n\\n    >>> z = -3\\n    >>> airybi(z)\\n    -0.1982896263749265432206449\\n    >>> p = 2*power(-z,'3/2')/3\\n    >>> sqrt(-mpf(z)/3)*(besselj('-1/3',p) - besselj('1/3',p))\\n    -0.1982896263749265432206449\\n\\n**Derivatives and integrals**\\n\\nDerivatives of the Bi-function (directly and using :func:`~mpmath.diff`)::\\n\\n    >>> airybi(-3,1); diff(airybi,-3)\\n    -0.675611222685258537668032\\n    -0.675611222685258537668032\\n    >>> airybi(-3,2); diff(airybi,-3,2)\\n    0.5948688791247796296619346\\n    0.5948688791247796296619346\\n    >>> airybi(1000,1); diff(airybi,1000)\\n    1.710055114624614989262335e+9156\\n    1.710055114624614989262335e+9156\\n\\nSeveral derivatives at `z = 0`::\\n\\n    >>> airybi(0,0); airybi(0,1); airybi(0,2)\\n    0.6149266274460007351509224\\n    0.4482883573538263579148237\\n    0.0\\n    >>> airybi(0,3); airybi(0,4); airybi(0,5)\\n    0.6149266274460007351509224\\n    0.8965767147076527158296474\\n    0.0\\n    >>> airybi(0,15); airybi(0,16); airybi(0,17)\\n    2238.332923903442675949357\\n    5522.912562599140729510628\\n    0.0\\n\\nThe integral of the Bi-function::\\n\\n    >>> airybi(3,-1); quad(airybi, [0,3])\\n    10.06200303130620056316655\\n    10.06200303130620056316655\\n    >>> airybi(-10,-1); quad(airybi, [0,-10])\\n    -0.01504042480614002045135483\\n    -0.01504042480614002045135483\\n\\nIntegrals of high or fractional order::\\n\\n    >>> airybi(-2,0.5); differint(airybi, -2, 0.5, 0)\\n    (0.0 + 0.5019859055341699223453257j)\\n    (0.0 + 0.5019859055341699223453257j)\\n    >>> airybi(-2,-4); differint(airybi,-2,-4,0)\\n    0.2809314599922447252139092\\n    0.2809314599922447252139092\\n    >>> airybi(0,-1); airybi(0,-2); airybi(0,-3)\\n    0.0\\n    0.0\\n    0.0\\n\\nIntegrals of the Bi-function can be evaluated at limit points::\\n\\n    >>> airybi(-1000000,-1); airybi(-inf,-1)\\n    0.000002191261128063434047966873\\n    0.0\\n    >>> airybi(10,-1); airybi(+inf,-1)\\n    147809803.1074067161675853\\n    +inf\\n    >>> airybi(+inf,-2); airybi(+inf,-3)\\n    +inf\\n    +inf\\n    >>> airybi(-1000000,-2); airybi(-inf,-2)\\n    0.4482883750599908479851085\\n    0.4482883573538263579148237\\n    >>> gamma('2/3')*power(3,'2/3')/(2*pi)\\n    0.4482883573538263579148237\\n    >>> airybi(-100000,-3); airybi(-inf,-3)\\n    -44828.52827206932872493133\\n    -inf\\n    >>> airybi(-100000,-4); airybi(-inf,-4)\\n    2241411040.437759489540248\\n    +inf\\n\\n\\\"\\\"\\\"\\n\\nairyaizero = r\\\"\\\"\\\"\\nGives the `k`-th zero of the Airy Ai-function,\\ni.e. the `k`-th number `a_k` ordered by magnitude for which\\n`\\\\operatorname{Ai}(a_k) = 0`.\\n\\nOptionally, with *derivative=1*, the corresponding\\nzero `a'_k` of the derivative function, i.e.\\n`\\\\operatorname{Ai}'(a'_k) = 0`, is computed.\\n\\n**Examples**\\n\\nSome values of `a_k`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> airyaizero(1)\\n    -2.338107410459767038489197\\n    >>> airyaizero(2)\\n    -4.087949444130970616636989\\n    >>> airyaizero(3)\\n    -5.520559828095551059129856\\n    >>> airyaizero(1000)\\n    -281.0315196125215528353364\\n\\nSome values of `a'_k`::\\n\\n    >>> airyaizero(1,1)\\n    -1.018792971647471089017325\\n    >>> airyaizero(2,1)\\n    -3.248197582179836537875424\\n    >>> airyaizero(3,1)\\n    -4.820099211178735639400616\\n    >>> airyaizero(1000,1)\\n    -280.9378080358935070607097\\n\\nVerification::\\n\\n    >>> chop(airyai(airyaizero(1)))\\n    0.0\\n    >>> chop(airyai(airyaizero(1,1),1))\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\nairybizero = r\\\"\\\"\\\"\\nWith *complex=False*, gives the `k`-th real zero of the Airy Bi-function,\\ni.e. the `k`-th number `b_k` ordered by magnitude for which\\n`\\\\operatorname{Bi}(b_k) = 0`.\\n\\nWith *complex=True*, gives the `k`-th complex zero in the upper\\nhalf plane `\\\\beta_k`. Also the conjugate `\\\\overline{\\\\beta_k}`\\nis a zero.\\n\\nOptionally, with *derivative=1*, the corresponding\\nzero `b'_k` or `\\\\beta'_k` of the derivative function, i.e.\\n`\\\\operatorname{Bi}'(b'_k) = 0` or `\\\\operatorname{Bi}'(\\\\beta'_k) = 0`,\\nis computed.\\n\\n**Examples**\\n\\nSome values of `b_k`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> airybizero(1)\\n    -1.17371322270912792491998\\n    >>> airybizero(2)\\n    -3.271093302836352715680228\\n    >>> airybizero(3)\\n    -4.830737841662015932667709\\n    >>> airybizero(1000)\\n    -280.9378112034152401578834\\n\\nSome values of `b_k`::\\n\\n    >>> airybizero(1,1)\\n    -2.294439682614123246622459\\n    >>> airybizero(2,1)\\n    -4.073155089071828215552369\\n    >>> airybizero(3,1)\\n    -5.512395729663599496259593\\n    >>> airybizero(1000,1)\\n    -281.0315164471118527161362\\n\\nSome values of `\\\\beta_k`::\\n\\n    >>> airybizero(1,complex=True)\\n    (0.9775448867316206859469927 + 2.141290706038744575749139j)\\n    >>> airybizero(2,complex=True)\\n    (1.896775013895336346627217 + 3.627291764358919410440499j)\\n    >>> airybizero(3,complex=True)\\n    (2.633157739354946595708019 + 4.855468179979844983174628j)\\n    >>> airybizero(1000,complex=True)\\n    (140.4978560578493018899793 + 243.3907724215792121244867j)\\n\\nSome values of `\\\\beta'_k`::\\n\\n    >>> airybizero(1,1,complex=True)\\n    (0.2149470745374305676088329 + 1.100600143302797880647194j)\\n    >>> airybizero(2,1,complex=True)\\n    (1.458168309223507392028211 + 2.912249367458445419235083j)\\n    >>> airybizero(3,1,complex=True)\\n    (2.273760763013482299792362 + 4.254528549217097862167015j)\\n    >>> airybizero(1000,1,complex=True)\\n    (140.4509972835270559730423 + 243.3096175398562811896208j)\\n\\nVerification::\\n\\n    >>> chop(airybi(airybizero(1)))\\n    0.0\\n    >>> chop(airybi(airybizero(1,1),1))\\n    0.0\\n    >>> u = airybizero(1,complex=True)\\n    >>> chop(airybi(u))\\n    0.0\\n    >>> chop(airybi(conj(u)))\\n    0.0\\n\\nThe complex zeros (in the upper and lower half-planes respectively)\\nasymptotically approach the rays `z = R \\\\exp(\\\\pm i \\\\pi /3)`::\\n\\n    >>> arg(airybizero(1,complex=True))\\n    1.142532510286334022305364\\n    >>> arg(airybizero(1000,complex=True))\\n    1.047271114786212061583917\\n    >>> arg(airybizero(1000000,complex=True))\\n    1.047197624741816183341355\\n    >>> pi/3\\n    1.047197551196597746154214\\n\\n\\\"\\\"\\\"\\n\\n\\nellipk = r\\\"\\\"\\\"\\nEvaluates the complete elliptic integral of the first kind,\\n`K(m)`, defined by\\n\\n.. math ::\\n\\n    K(m) = \\\\int_0^{\\\\pi/2} \\\\frac{dt}{\\\\sqrt{1-m \\\\sin^2 t}} \\\\, = \\\\,\\n    \\\\frac{\\\\pi}{2} \\\\,_2F_1\\\\left(\\\\frac{1}{2}, \\\\frac{1}{2}, 1, m\\\\right).\\n\\nNote that the argument is the parameter `m = k^2`,\\nnot the modulus `k` which is sometimes used.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/ellipk.py\\n.. image :: /plots/ellipk.png\\n\\n**Examples**\\n\\nValues and limits include::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> ellipk(0)\\n    1.570796326794896619231322\\n    >>> ellipk(inf)\\n    (0.0 + 0.0j)\\n    >>> ellipk(-inf)\\n    0.0\\n    >>> ellipk(1)\\n    +inf\\n    >>> ellipk(-1)\\n    1.31102877714605990523242\\n    >>> ellipk(2)\\n    (1.31102877714605990523242 - 1.31102877714605990523242j)\\n\\nVerifying the defining integral and hypergeometric\\nrepresentation::\\n\\n    >>> ellipk(0.5)\\n    1.85407467730137191843385\\n    >>> quad(lambda t: (1-0.5*sin(t)**2)**-0.5, [0, pi/2])\\n    1.85407467730137191843385\\n    >>> pi/2*hyp2f1(0.5,0.5,1,0.5)\\n    1.85407467730137191843385\\n\\nEvaluation is supported for arbitrary complex `m`::\\n\\n    >>> ellipk(3+4j)\\n    (0.9111955638049650086562171 + 0.6313342832413452438845091j)\\n\\nA definite integral::\\n\\n    >>> quad(ellipk, [0, 1])\\n    2.0\\n\\\"\\\"\\\"\\n\\nagm = r\\\"\\\"\\\"\\n``agm(a, b)`` computes the arithmetic-geometric mean of `a` and\\n`b`, defined as the limit of the following iteration:\\n\\n.. math ::\\n\\n    a_0 = a\\n\\n    b_0 = b\\n\\n    a_{n+1} = \\\\frac{a_n+b_n}{2}\\n\\n    b_{n+1} = \\\\sqrt{a_n b_n}\\n\\nThis function can be called with a single argument, computing\\n`\\\\mathrm{agm}(a,1) = \\\\mathrm{agm}(1,a)`.\\n\\n**Examples**\\n\\nIt is a well-known theorem that the geometric mean of\\ntwo distinct positive numbers is less than the arithmetic\\nmean. It follows that the arithmetic-geometric mean lies\\nbetween the two means::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> a = mpf(3)\\n    >>> b = mpf(4)\\n    >>> sqrt(a*b)\\n    3.46410161513775\\n    >>> agm(a,b)\\n    3.48202767635957\\n    >>> (a+b)/2\\n    3.5\\n\\nThe arithmetic-geometric mean is scale-invariant::\\n\\n    >>> agm(10*e, 10*pi)\\n    29.261085515723\\n    >>> 10*agm(e, pi)\\n    29.261085515723\\n\\nAs an order-of-magnitude estimate, `\\\\mathrm{agm}(1,x) \\\\approx x`\\nfor large `x`::\\n\\n    >>> agm(10**10)\\n    643448704.760133\\n    >>> agm(10**50)\\n    1.34814309345871e+48\\n\\nFor tiny `x`, `\\\\mathrm{agm}(1,x) \\\\approx -\\\\pi/(2 \\\\log(x/4))`::\\n\\n    >>> agm('0.01')\\n    0.262166887202249\\n    >>> -pi/2/log('0.0025')\\n    0.262172347753122\\n\\nThe arithmetic-geometric mean can also be computed for complex\\nnumbers::\\n\\n    >>> agm(3, 2+j)\\n    (2.51055133276184 + 0.547394054060638j)\\n\\nThe AGM iteration converges very quickly (each step doubles\\nthe number of correct digits), so :func:`~mpmath.agm` supports efficient\\nhigh-precision evaluation::\\n\\n    >>> mp.dps = 10000\\n    >>> a = agm(1,2)\\n    >>> str(a)[-10:]\\n    '1679581912'\\n\\n**Mathematical relations**\\n\\nThe arithmetic-geometric mean may be used to evaluate the\\nfollowing two parametric definite integrals:\\n\\n.. math ::\\n\\n  I_1 = \\\\int_0^{\\\\infty}\\n    \\\\frac{1}{\\\\sqrt{(x^2+a^2)(x^2+b^2)}} \\\\,dx\\n\\n  I_2 = \\\\int_0^{\\\\pi/2}\\n    \\\\frac{1}{\\\\sqrt{a^2 \\\\cos^2(x) + b^2 \\\\sin^2(x)}} \\\\,dx\\n\\nWe have::\\n\\n    >>> mp.dps = 15\\n    >>> a = 3\\n    >>> b = 4\\n    >>> f1 = lambda x: ((x**2+a**2)*(x**2+b**2))**-0.5\\n    >>> f2 = lambda x: ((a*cos(x))**2 + (b*sin(x))**2)**-0.5\\n    >>> quad(f1, [0, inf])\\n    0.451115405388492\\n    >>> quad(f2, [0, pi/2])\\n    0.451115405388492\\n    >>> pi/(2*agm(a,b))\\n    0.451115405388492\\n\\nA formula for `\\\\Gamma(1/4)`::\\n\\n    >>> gamma(0.25)\\n    3.62560990822191\\n    >>> sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2)))\\n    3.62560990822191\\n\\n**Possible issues**\\n\\nThe branch cut chosen for complex `a` and `b` is somewhat\\narbitrary.\\n\\n\\\"\\\"\\\"\\n\\ngegenbauer = r\\\"\\\"\\\"\\nEvaluates the Gegenbauer polynomial, or ultraspherical polynomial,\\n\\n.. math ::\\n\\n    C_n^{(a)}(z) = {n+2a-1 \\\\choose n} \\\\,_2F_1\\\\left(-n, n+2a;\\n        a+\\\\frac{1}{2}; \\\\frac{1}{2}(1-z)\\\\right).\\n\\nWhen `n` is a nonnegative integer, this formula gives a polynomial\\nin `z` of degree `n`, but all parameters are permitted to be\\ncomplex numbers. With `a = 1/2`, the Gegenbauer polynomial\\nreduces to a Legendre polynomial.\\n\\n**Examples**\\n\\nEvaluation for arbitrary arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> gegenbauer(3, 0.5, -10)\\n    -2485.0\\n    >>> gegenbauer(1000, 10, 100)\\n    3.012757178975667428359374e+2322\\n    >>> gegenbauer(2+3j, -0.75, -1000j)\\n    (-5038991.358609026523401901 + 9414549.285447104177860806j)\\n\\nEvaluation at negative integer orders::\\n\\n    >>> gegenbauer(-4, 2, 1.75)\\n    -1.0\\n    >>> gegenbauer(-4, 3, 1.75)\\n    0.0\\n    >>> gegenbauer(-4, 2j, 1.75)\\n    0.0\\n    >>> gegenbauer(-7, 0.5, 3)\\n    8989.0\\n\\nThe Gegenbauer polynomials solve the differential equation::\\n\\n    >>> n, a = 4.5, 1+2j\\n    >>> f = lambda z: gegenbauer(n, a, z)\\n    >>> for z in [0, 0.75, -0.5j]:\\n    ...     chop((1-z**2)*diff(f,z,2) - (2*a+1)*z*diff(f,z) + n*(n+2*a)*f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n\\nThe Gegenbauer polynomials have generating function\\n`(1-2zt+t^2)^{-a}`::\\n\\n    >>> a, z = 2.5, 1\\n    >>> taylor(lambda t: (1-2*z*t+t**2)**(-a), 0, 3)\\n    [1.0, 5.0, 15.0, 35.0]\\n    >>> [gegenbauer(n,a,z) for n in range(4)]\\n    [1.0, 5.0, 15.0, 35.0]\\n\\nThe Gegenbauer polynomials are orthogonal on `[-1, 1]` with respect\\nto the weight `(1-z^2)^{a-\\\\frac{1}{2}}`::\\n\\n    >>> a, n, m = 2.5, 4, 5\\n    >>> Cn = lambda z: gegenbauer(n, a, z, zeroprec=1000)\\n    >>> Cm = lambda z: gegenbauer(m, a, z, zeroprec=1000)\\n    >>> chop(quad(lambda z: Cn(z)*Cm(z)*(1-z**2)*(a-0.5), [-1, 1]))\\n    0.0\\n\\\"\\\"\\\"\\n\\nlaguerre = r\\\"\\\"\\\"\\nGives the generalized (associated) Laguerre polynomial, defined by\\n\\n.. math ::\\n\\n    L_n^a(z) = \\\\frac{\\\\Gamma(n+b+1)}{\\\\Gamma(b+1) \\\\Gamma(n+1)}\\n        \\\\,_1F_1(-n, a+1, z).\\n\\nWith `a = 0` and `n` a nonnegative integer, this reduces to an ordinary\\nLaguerre polynomial, the sequence of which begins\\n`L_0(z) = 1, L_1(z) = 1-z, L_2(z) = z^2-2z+1, \\\\ldots`.\\n\\nThe Laguerre polynomials are orthogonal with respect to the weight\\n`z^a e^{-z}` on `[0, \\\\infty)`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/laguerre.py\\n.. image :: /plots/laguerre.png\\n\\n**Examples**\\n\\nEvaluation for arbitrary arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> laguerre(5, 0, 0.25)\\n    0.03726399739583333333333333\\n    >>> laguerre(1+j, 0.5, 2+3j)\\n    (4.474921610704496808379097 - 11.02058050372068958069241j)\\n    >>> laguerre(2, 0, 10000)\\n    49980001.0\\n    >>> laguerre(2.5, 0, 10000)\\n    -9.327764910194842158583189e+4328\\n\\nThe first few Laguerre polynomials, normalized to have integer\\ncoefficients::\\n\\n    >>> for n in range(7):\\n    ...     chop(taylor(lambda z: fac(n)*laguerre(n, 0, z), 0, n))\\n    ...\\n    [1.0]\\n    [1.0, -1.0]\\n    [2.0, -4.0, 1.0]\\n    [6.0, -18.0, 9.0, -1.0]\\n    [24.0, -96.0, 72.0, -16.0, 1.0]\\n    [120.0, -600.0, 600.0, -200.0, 25.0, -1.0]\\n    [720.0, -4320.0, 5400.0, -2400.0, 450.0, -36.0, 1.0]\\n\\nVerifying orthogonality::\\n\\n    >>> Lm = lambda t: laguerre(m,a,t)\\n    >>> Ln = lambda t: laguerre(n,a,t)\\n    >>> a, n, m = 2.5, 2, 3\\n    >>> chop(quad(lambda t: exp(-t)*t**a*Lm(t)*Ln(t), [0,inf]))\\n    0.0\\n\\n\\n\\\"\\\"\\\"\\n\\nhermite = r\\\"\\\"\\\"\\nEvaluates the Hermite polynomial `H_n(z)`, which may be defined using\\nthe recurrence\\n\\n.. math ::\\n\\n    H_0(z) = 1\\n\\n    H_1(z) = 2z\\n\\n    H_{n+1} = 2z H_n(z) - 2n H_{n-1}(z).\\n\\nThe Hermite polynomials are orthogonal on `(-\\\\infty, \\\\infty)` with\\nrespect to the weight `e^{-z^2}`. More generally, allowing arbitrary complex\\nvalues of `n`, the Hermite function `H_n(z)` is defined as\\n\\n.. math ::\\n\\n    H_n(z) = (2z)^n \\\\,_2F_0\\\\left(-\\\\frac{n}{2}, \\\\frac{1-n}{2},\\n        -\\\\frac{1}{z^2}\\\\right)\\n\\nfor `\\\\Re{z} > 0`, or generally\\n\\n.. math ::\\n\\n    H_n(z) = 2^n \\\\sqrt{\\\\pi} \\\\left(\\n        \\\\frac{1}{\\\\Gamma\\\\left(\\\\frac{1-n}{2}\\\\right)}\\n        \\\\,_1F_1\\\\left(-\\\\frac{n}{2}, \\\\frac{1}{2}, z^2\\\\right) -\\n        \\\\frac{2z}{\\\\Gamma\\\\left(-\\\\frac{n}{2}\\\\right)}\\n        \\\\,_1F_1\\\\left(\\\\frac{1-n}{2}, \\\\frac{3}{2}, z^2\\\\right)\\n    \\\\right).\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/hermite.py\\n.. image :: /plots/hermite.png\\n\\n**Examples**\\n\\nEvaluation for arbitrary arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hermite(0, 10)\\n    1.0\\n    >>> hermite(1, 10); hermite(2, 10)\\n    20.0\\n    398.0\\n    >>> hermite(10000, 2)\\n    4.950440066552087387515653e+19334\\n    >>> hermite(3, -10**8)\\n    -7999999999999998800000000.0\\n    >>> hermite(-3, -10**8)\\n    1.675159751729877682920301e+4342944819032534\\n    >>> hermite(2+3j, -1+2j)\\n    (-0.07652130602993513389421901 - 0.1084662449961914580276007j)\\n\\nCoefficients of the first few Hermite polynomials are::\\n\\n    >>> for n in range(7):\\n    ...     chop(taylor(lambda z: hermite(n, z), 0, n))\\n    ...\\n    [1.0]\\n    [0.0, 2.0]\\n    [-2.0, 0.0, 4.0]\\n    [0.0, -12.0, 0.0, 8.0]\\n    [12.0, 0.0, -48.0, 0.0, 16.0]\\n    [0.0, 120.0, 0.0, -160.0, 0.0, 32.0]\\n    [-120.0, 0.0, 720.0, 0.0, -480.0, 0.0, 64.0]\\n\\nValues at `z = 0`::\\n\\n    >>> for n in range(-5, 9):\\n    ...     hermite(n, 0)\\n    ...\\n    0.02769459142039868792653387\\n    0.08333333333333333333333333\\n    0.2215567313631895034122709\\n    0.5\\n    0.8862269254527580136490837\\n    1.0\\n    0.0\\n    -2.0\\n    0.0\\n    12.0\\n    0.0\\n    -120.0\\n    0.0\\n    1680.0\\n\\nHermite functions satisfy the differential equation::\\n\\n    >>> n = 4\\n    >>> f = lambda z: hermite(n, z)\\n    >>> z = 1.5\\n    >>> chop(diff(f,z,2) - 2*z*diff(f,z) + 2*n*f(z))\\n    0.0\\n\\nVerifying orthogonality::\\n\\n    >>> chop(quad(lambda t: hermite(2,t)*hermite(4,t)*exp(-t**2), [-inf,inf]))\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\njacobi = r\\\"\\\"\\\"\\n``jacobi(n, a, b, x)`` evaluates the Jacobi polynomial\\n`P_n^{(a,b)}(x)`. The Jacobi polynomials are a special\\ncase of the hypergeometric function `\\\\,_2F_1` given by:\\n\\n.. math ::\\n\\n    P_n^{(a,b)}(x) = {n+a \\\\choose n}\\n      \\\\,_2F_1\\\\left(-n,1+a+b+n,a+1,\\\\frac{1-x}{2}\\\\right).\\n\\nNote that this definition generalizes to nonintegral values\\nof `n`. When `n` is an integer, the hypergeometric series\\nterminates after a finite number of terms, giving\\na polynomial in `x`.\\n\\n**Evaluation of Jacobi polynomials**\\n\\nA special evaluation is `P_n^{(a,b)}(1) = {n+a \\\\choose n}`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> jacobi(4, 0.5, 0.25, 1)\\n    2.4609375\\n    >>> binomial(4+0.5, 4)\\n    2.4609375\\n\\nA Jacobi polynomial of degree `n` is equal to its\\nTaylor polynomial of degree `n`. The explicit\\ncoefficients of Jacobi polynomials can therefore\\nbe recovered easily using :func:`~mpmath.taylor`::\\n\\n    >>> for n in range(5):\\n    ...     nprint(taylor(lambda x: jacobi(n,1,2,x), 0, n))\\n    ...\\n    [1.0]\\n    [-0.5, 2.5]\\n    [-0.75, -1.5, 5.25]\\n    [0.5, -3.5, -3.5, 10.5]\\n    [0.625, 2.5, -11.25, -7.5, 20.625]\\n\\nFor nonintegral `n`, the Jacobi \\\"polynomial\\\" is no longer\\na polynomial::\\n\\n    >>> nprint(taylor(lambda x: jacobi(0.5,1,2,x), 0, 4))\\n    [0.309983, 1.84119, -1.26933, 1.26699, -1.34808]\\n\\n**Orthogonality**\\n\\nThe Jacobi polynomials are orthogonal on the interval\\n`[-1, 1]` with respect to the weight function\\n`w(x) = (1-x)^a (1+x)^b`. That is,\\n`w(x) P_n^{(a,b)}(x) P_m^{(a,b)}(x)` integrates to\\nzero if `m \\\\ne n` and to a nonzero number if `m = n`.\\n\\nThe orthogonality is easy to verify using numerical\\nquadrature::\\n\\n    >>> P = jacobi\\n    >>> f = lambda x: (1-x)**a * (1+x)**b * P(m,a,b,x) * P(n,a,b,x)\\n    >>> a = 2\\n    >>> b = 3\\n    >>> m, n = 3, 4\\n    >>> chop(quad(f, [-1, 1]), 1)\\n    0.0\\n    >>> m, n = 4, 4\\n    >>> quad(f, [-1, 1])\\n    1.9047619047619\\n\\n**Differential equation**\\n\\nThe Jacobi polynomials are solutions of the differential\\nequation\\n\\n.. math ::\\n\\n  (1-x^2) y'' + (b-a-(a+b+2)x) y' + n (n+a+b+1) y = 0.\\n\\nWe can verify that :func:`~mpmath.jacobi` approximately satisfies\\nthis equation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15\\n    >>> a = 2.5\\n    >>> b = 4\\n    >>> n = 3\\n    >>> y = lambda x: jacobi(n,a,b,x)\\n    >>> x = pi\\n    >>> A0 = n*(n+a+b+1)*y(x)\\n    >>> A1 = (b-a-(a+b+2)*x)*diff(y,x)\\n    >>> A2 = (1-x**2)*diff(y,x,2)\\n    >>> nprint(A2 + A1 + A0, 1)\\n    4.0e-12\\n\\nThe difference of order `10^{-12}` is as close to zero as\\nit could be at 15-digit working precision, since the terms\\nare large::\\n\\n    >>> A0, A1, A2\\n    (26560.2328981879, -21503.7641037294, -5056.46879445852)\\n\\n\\\"\\\"\\\"\\n\\nlegendre = r\\\"\\\"\\\"\\n``legendre(n, x)`` evaluates the Legendre polynomial `P_n(x)`.\\nThe Legendre polynomials are given by the formula\\n\\n.. math ::\\n\\n    P_n(x) = \\\\frac{1}{2^n n!} \\\\frac{d^n}{dx^n} (x^2 -1)^n.\\n\\nAlternatively, they can be computed recursively using\\n\\n.. math ::\\n\\n    P_0(x) = 1\\n\\n    P_1(x) = x\\n\\n    (n+1) P_{n+1}(x) = (2n+1) x P_n(x) - n P_{n-1}(x).\\n\\nA third definition is in terms of the hypergeometric function\\n`\\\\,_2F_1`, whereby they can be generalized to arbitrary `n`:\\n\\n.. math ::\\n\\n    P_n(x) = \\\\,_2F_1\\\\left(-n, n+1, 1, \\\\frac{1-x}{2}\\\\right)\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/legendre.py\\n.. image :: /plots/legendre.png\\n\\n**Basic evaluation**\\n\\nThe Legendre polynomials assume fixed values at the points\\n`x = -1` and `x = 1`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> nprint([legendre(n, 1) for n in range(6)])\\n    [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\\n    >>> nprint([legendre(n, -1) for n in range(6)])\\n    [1.0, -1.0, 1.0, -1.0, 1.0, -1.0]\\n\\nThe coefficients of Legendre polynomials can be recovered\\nusing degree-`n` Taylor expansion::\\n\\n    >>> for n in range(5):\\n    ...     nprint(chop(taylor(lambda x: legendre(n, x), 0, n)))\\n    ...\\n    [1.0]\\n    [0.0, 1.0]\\n    [-0.5, 0.0, 1.5]\\n    [0.0, -1.5, 0.0, 2.5]\\n    [0.375, 0.0, -3.75, 0.0, 4.375]\\n\\nThe roots of Legendre polynomials are located symmetrically\\non the interval `[-1, 1]`::\\n\\n    >>> for n in range(5):\\n    ...     nprint(polyroots(taylor(lambda x: legendre(n, x), 0, n)[::-1]))\\n    ...\\n    []\\n    [0.0]\\n    [-0.57735, 0.57735]\\n    [-0.774597, 0.0, 0.774597]\\n    [-0.861136, -0.339981, 0.339981, 0.861136]\\n\\nAn example of an evaluation for arbitrary `n`::\\n\\n    >>> legendre(0.75, 2+4j)\\n    (1.94952805264875 + 2.1071073099422j)\\n\\n**Orthogonality**\\n\\nThe Legendre polynomials are orthogonal on `[-1, 1]` with respect\\nto the trivial weight `w(x) = 1`. That is, `P_m(x) P_n(x)`\\nintegrates to zero if `m \\\\ne n` and to `2/(2n+1)` if `m = n`::\\n\\n    >>> m, n = 3, 4\\n    >>> quad(lambda x: legendre(m,x)*legendre(n,x), [-1, 1])\\n    0.0\\n    >>> m, n = 4, 4\\n    >>> quad(lambda x: legendre(m,x)*legendre(n,x), [-1, 1])\\n    0.222222222222222\\n\\n**Differential equation**\\n\\nThe Legendre polynomials satisfy the differential equation\\n\\n.. math ::\\n\\n    ((1-x^2) y')' + n(n+1) y' = 0.\\n\\nWe can verify this numerically::\\n\\n    >>> n = 3.6\\n    >>> x = 0.73\\n    >>> P = legendre\\n    >>> A = diff(lambda t: (1-t**2)*diff(lambda u: P(n,u), t), x)\\n    >>> B = n*(n+1)*P(n,x)\\n    >>> nprint(A+B,1)\\n    9.0e-16\\n\\n\\\"\\\"\\\"\\n\\n\\nlegenp = r\\\"\\\"\\\"\\nCalculates the (associated) Legendre function of the first kind of\\ndegree *n* and order *m*, `P_n^m(z)`. Taking `m = 0` gives the ordinary\\nLegendre function of the first kind, `P_n(z)`. The parameters may be\\ncomplex numbers.\\n\\nIn terms of the Gauss hypergeometric function, the (associated) Legendre\\nfunction is defined as\\n\\n.. math ::\\n\\n    P_n^m(z) = \\\\frac{1}{\\\\Gamma(1-m)} \\\\frac{(1+z)^{m/2}}{(1-z)^{m/2}}\\n        \\\\,_2F_1\\\\left(-n, n+1, 1-m, \\\\frac{1-z}{2}\\\\right).\\n\\nWith *type=3* instead of *type=2*, the alternative\\ndefinition\\n\\n.. math ::\\n\\n    \\\\hat{P}_n^m(z) = \\\\frac{1}{\\\\Gamma(1-m)} \\\\frac{(z+1)^{m/2}}{(z-1)^{m/2}}\\n        \\\\,_2F_1\\\\left(-n, n+1, 1-m, \\\\frac{1-z}{2}\\\\right).\\n\\nis used. These functions correspond respectively to ``LegendreP[n,m,2,z]``\\nand ``LegendreP[n,m,3,z]`` in Mathematica.\\n\\nThe general solution of the (associated) Legendre differential equation\\n\\n.. math ::\\n\\n    (1-z^2) f''(z) - 2zf'(z) + \\\\left(n(n+1)-\\\\frac{m^2}{1-z^2}\\\\right)f(z) = 0\\n\\nis given by `C_1 P_n^m(z) + C_2 Q_n^m(z)` for arbitrary constants\\n`C_1`, `C_2`, where `Q_n^m(z)` is a Legendre function of the\\nsecond kind as implemented by :func:`~mpmath.legenq`.\\n\\n**Examples**\\n\\nEvaluation for arbitrary parameters and arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> legenp(2, 0, 10); legendre(2, 10)\\n    149.5\\n    149.5\\n    >>> legenp(-2, 0.5, 2.5)\\n    (1.972260393822275434196053 - 1.972260393822275434196053j)\\n    >>> legenp(2+3j, 1-j, -0.5+4j)\\n    (-3.335677248386698208736542 - 5.663270217461022307645625j)\\n    >>> chop(legenp(3, 2, -1.5, type=2))\\n    28.125\\n    >>> chop(legenp(3, 2, -1.5, type=3))\\n    -28.125\\n\\nVerifying the associated Legendre differential equation::\\n\\n    >>> n, m = 2, -0.5\\n    >>> C1, C2 = 1, -3\\n    >>> f = lambda z: C1*legenp(n,m,z) + C2*legenq(n,m,z)\\n    >>> deq = lambda z: (1-z**2)*diff(f,z,2) - 2*z*diff(f,z) + \\\\\\n    ...     (n*(n+1)-m**2/(1-z**2))*f(z)\\n    >>> for z in [0, 2, -1.5, 0.5+2j]:\\n    ...     chop(deq(mpmathify(z)))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\\"\\\"\\\"\\n\\nlegenq = r\\\"\\\"\\\"\\nCalculates the (associated) Legendre function of the second kind of\\ndegree *n* and order *m*, `Q_n^m(z)`. Taking `m = 0` gives the ordinary\\nLegendre function of the second kind, `Q_n(z)`. The parameters may be\\ncomplex numbers.\\n\\nThe Legendre functions of the second kind give a second set of\\nsolutions to the (associated) Legendre differential equation.\\n(See :func:`~mpmath.legenp`.)\\nUnlike the Legendre functions of the first kind, they are not\\npolynomials of `z` for integer `n`, `m` but rational or logarithmic\\nfunctions with poles at `z = \\\\pm 1`.\\n\\nThere are various ways to define Legendre functions of\\nthe second kind, giving rise to different complex structure.\\nA version can be selected using the *type* keyword argument.\\nThe *type=2* and *type=3* functions are given respectively by\\n\\n.. math ::\\n\\n    Q_n^m(z) = \\\\frac{\\\\pi}{2 \\\\sin(\\\\pi m)}\\n        \\\\left( \\\\cos(\\\\pi m) P_n^m(z) -\\n        \\\\frac{\\\\Gamma(1+m+n)}{\\\\Gamma(1-m+n)} P_n^{-m}(z)\\\\right)\\n\\n    \\\\hat{Q}_n^m(z) = \\\\frac{\\\\pi}{2 \\\\sin(\\\\pi m)} e^{\\\\pi i m}\\n        \\\\left( \\\\hat{P}_n^m(z) -\\n        \\\\frac{\\\\Gamma(1+m+n)}{\\\\Gamma(1-m+n)} \\\\hat{P}_n^{-m}(z)\\\\right)\\n\\nwhere `P` and `\\\\hat{P}` are the *type=2* and *type=3* Legendre functions\\nof the first kind. The formulas above should be understood as limits\\nwhen `m` is an integer.\\n\\nThese functions correspond to ``LegendreQ[n,m,2,z]`` (or ``LegendreQ[n,m,z]``)\\nand ``LegendreQ[n,m,3,z]`` in Mathematica. The *type=3* function\\nis essentially the same as the function defined in\\nAbramowitz & Stegun (eq. 8.1.3) but with `(z+1)^{m/2}(z-1)^{m/2}` instead\\nof `(z^2-1)^{m/2}`, giving slightly different branches.\\n\\n**Examples**\\n\\nEvaluation for arbitrary parameters and arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> legenq(2, 0, 0.5)\\n    -0.8186632680417568557122028\\n    >>> legenq(-1.5, -2, 2.5)\\n    (0.6655964618250228714288277 + 0.3937692045497259717762649j)\\n    >>> legenq(2-j, 3+4j, -6+5j)\\n    (-10001.95256487468541686564 - 6011.691337610097577791134j)\\n\\nDifferent versions of the function::\\n\\n    >>> legenq(2, 1, 0.5)\\n    0.7298060598018049369381857\\n    >>> legenq(2, 1, 1.5)\\n    (-7.902916572420817192300921 + 0.1998650072605976600724502j)\\n    >>> legenq(2, 1, 0.5, type=3)\\n    (2.040524284763495081918338 - 0.7298060598018049369381857j)\\n    >>> chop(legenq(2, 1, 1.5, type=3))\\n    -0.1998650072605976600724502\\n\\n\\\"\\\"\\\"\\n\\nchebyt = r\\\"\\\"\\\"\\n``chebyt(n, x)`` evaluates the Chebyshev polynomial of the first\\nkind `T_n(x)`, defined by the identity\\n\\n.. math ::\\n\\n    T_n(\\\\cos x) = \\\\cos(n x).\\n\\nThe Chebyshev polynomials of the first kind are a special\\ncase of the Jacobi polynomials, and by extension of the\\nhypergeometric function `\\\\,_2F_1`. They can thus also be\\nevaluated for nonintegral `n`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/chebyt.py\\n.. image :: /plots/chebyt.png\\n\\n**Basic evaluation**\\n\\nThe coefficients of the `n`-th polynomial can be recovered\\nusing using degree-`n` Taylor expansion::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(5):\\n    ...     nprint(chop(taylor(lambda x: chebyt(n, x), 0, n)))\\n    ...\\n    [1.0]\\n    [0.0, 1.0]\\n    [-1.0, 0.0, 2.0]\\n    [0.0, -3.0, 0.0, 4.0]\\n    [1.0, 0.0, -8.0, 0.0, 8.0]\\n\\n**Orthogonality**\\n\\nThe Chebyshev polynomials of the first kind are orthogonal\\non the interval `[-1, 1]` with respect to the weight\\nfunction `w(x) = 1/\\\\sqrt{1-x^2}`::\\n\\n    >>> f = lambda x: chebyt(m,x)*chebyt(n,x)/sqrt(1-x**2)\\n    >>> m, n = 3, 4\\n    >>> nprint(quad(f, [-1, 1]),1)\\n    0.0\\n    >>> m, n = 4, 4\\n    >>> quad(f, [-1, 1])\\n    1.57079632596448\\n\\n\\\"\\\"\\\"\\n\\nchebyu = r\\\"\\\"\\\"\\n``chebyu(n, x)`` evaluates the Chebyshev polynomial of the second\\nkind `U_n(x)`, defined by the identity\\n\\n.. math ::\\n\\n    U_n(\\\\cos x) = \\\\frac{\\\\sin((n+1)x)}{\\\\sin(x)}.\\n\\nThe Chebyshev polynomials of the second kind are a special\\ncase of the Jacobi polynomials, and by extension of the\\nhypergeometric function `\\\\,_2F_1`. They can thus also be\\nevaluated for nonintegral `n`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/chebyu.py\\n.. image :: /plots/chebyu.png\\n\\n**Basic evaluation**\\n\\nThe coefficients of the `n`-th polynomial can be recovered\\nusing using degree-`n` Taylor expansion::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(5):\\n    ...     nprint(chop(taylor(lambda x: chebyu(n, x), 0, n)))\\n    ...\\n    [1.0]\\n    [0.0, 2.0]\\n    [-1.0, 0.0, 4.0]\\n    [0.0, -4.0, 0.0, 8.0]\\n    [1.0, 0.0, -12.0, 0.0, 16.0]\\n\\n**Orthogonality**\\n\\nThe Chebyshev polynomials of the second kind are orthogonal\\non the interval `[-1, 1]` with respect to the weight\\nfunction `w(x) = \\\\sqrt{1-x^2}`::\\n\\n    >>> f = lambda x: chebyu(m,x)*chebyu(n,x)*sqrt(1-x**2)\\n    >>> m, n = 3, 4\\n    >>> quad(f, [-1, 1])\\n    0.0\\n    >>> m, n = 4, 4\\n    >>> quad(f, [-1, 1])\\n    1.5707963267949\\n\\\"\\\"\\\"\\n\\nbesselj = r\\\"\\\"\\\"\\n``besselj(n, x, derivative=0)`` gives the Bessel function of the first kind\\n`J_n(x)`. Bessel functions of the first kind are defined as\\nsolutions of the differential equation\\n\\n.. math ::\\n\\n    x^2 y'' + x y' + (x^2 - n^2) y = 0\\n\\nwhich appears, among other things, when solving the radial\\npart of Laplace's equation in cylindrical coordinates. This\\nequation has two solutions for given `n`, where the\\n`J_n`-function is the solution that is nonsingular at `x = 0`.\\nFor positive integer `n`, `J_n(x)` behaves roughly like a sine\\n(odd `n`) or cosine (even `n`) multiplied by a magnitude factor\\nthat decays slowly as `x \\\\to \\\\pm\\\\infty`.\\n\\nGenerally, `J_n` is a special case of the hypergeometric\\nfunction `\\\\,_0F_1`:\\n\\n.. math ::\\n\\n    J_n(x) = \\\\frac{x^n}{2^n \\\\Gamma(n+1)}\\n             \\\\,_0F_1\\\\left(n+1,-\\\\frac{x^2}{4}\\\\right)\\n\\nWith *derivative* = `m \\\\ne 0`, the `m`-th derivative\\n\\n.. math ::\\n\\n    \\\\frac{d^m}{dx^m} J_n(x)\\n\\nis computed.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/besselj.py\\n.. image :: /plots/besselj.png\\n.. literalinclude :: /plots/besselj_c.py\\n.. image :: /plots/besselj_c.png\\n\\n**Examples**\\n\\nEvaluation is supported for arbitrary arguments, and at\\narbitrary precision::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> besselj(2, 1000)\\n    -0.024777229528606\\n    >>> besselj(4, 0.75)\\n    0.000801070086542314\\n    >>> besselj(2, 1000j)\\n    (-2.48071721019185e+432 + 6.41567059811949e-437j)\\n    >>> mp.dps = 25\\n    >>> besselj(0.75j, 3+4j)\\n    (-2.778118364828153309919653 - 1.5863603889018621585533j)\\n    >>> mp.dps = 50\\n    >>> besselj(1, pi)\\n    0.28461534317975275734531059968613140570981118184947\\n\\nArguments may be large::\\n\\n    >>> mp.dps = 25\\n    >>> besselj(0, 10000)\\n    -0.007096160353388801477265164\\n    >>> besselj(0, 10**10)\\n    0.000002175591750246891726859055\\n    >>> besselj(2, 10**100)\\n    7.337048736538615712436929e-51\\n    >>> besselj(2, 10**5*j)\\n    (-3.540725411970948860173735e+43426 + 4.4949812409615803110051e-43433j)\\n\\nThe Bessel functions of the first kind satisfy simple\\nsymmetries around `x = 0`::\\n\\n    >>> mp.dps = 15\\n    >>> nprint([besselj(n,0) for n in range(5)])\\n    [1.0, 0.0, 0.0, 0.0, 0.0]\\n    >>> nprint([besselj(n,pi) for n in range(5)])\\n    [-0.304242, 0.284615, 0.485434, 0.333458, 0.151425]\\n    >>> nprint([besselj(n,-pi) for n in range(5)])\\n    [-0.304242, -0.284615, 0.485434, -0.333458, 0.151425]\\n\\nRoots of Bessel functions are often used::\\n\\n    >>> nprint([findroot(j0, k) for k in [2, 5, 8, 11, 14]])\\n    [2.40483, 5.52008, 8.65373, 11.7915, 14.9309]\\n    >>> nprint([findroot(j1, k) for k in [3, 7, 10, 13, 16]])\\n    [3.83171, 7.01559, 10.1735, 13.3237, 16.4706]\\n\\nThe roots are not periodic, but the distance between successive\\nroots asymptotically approaches `2 \\\\pi`. Bessel functions of\\nthe first kind have the following normalization::\\n\\n    >>> quadosc(j0, [0, inf], period=2*pi)\\n    1.0\\n    >>> quadosc(j1, [0, inf], period=2*pi)\\n    1.0\\n\\nFor `n = 1/2` or `n = -1/2`, the Bessel function reduces to a\\ntrigonometric function::\\n\\n    >>> x = 10\\n    >>> besselj(0.5, x), sqrt(2/(pi*x))*sin(x)\\n    (-0.13726373575505, -0.13726373575505)\\n    >>> besselj(-0.5, x), sqrt(2/(pi*x))*cos(x)\\n    (-0.211708866331398, -0.211708866331398)\\n\\nDerivatives of any order can be computed (negative orders\\ncorrespond to integration)::\\n\\n    >>> mp.dps = 25\\n    >>> besselj(0, 7.5, 1)\\n    -0.1352484275797055051822405\\n    >>> diff(lambda x: besselj(0,x), 7.5)\\n    -0.1352484275797055051822405\\n    >>> besselj(0, 7.5, 10)\\n    -0.1377811164763244890135677\\n    >>> diff(lambda x: besselj(0,x), 7.5, 10)\\n    -0.1377811164763244890135677\\n    >>> besselj(0,7.5,-1) - besselj(0,3.5,-1)\\n    -0.1241343240399987693521378\\n    >>> quad(j0, [3.5, 7.5])\\n    -0.1241343240399987693521378\\n\\nDifferentiation with a noninteger order gives the fractional derivative\\nin the sense of the Riemann-Liouville differintegral, as computed by\\n:func:`~mpmath.differint`::\\n\\n    >>> mp.dps = 15\\n    >>> besselj(1, 3.5, 0.75)\\n    -0.385977722939384\\n    >>> differint(lambda x: besselj(1, x), 3.5, 0.75)\\n    -0.385977722939384\\n\\n\\\"\\\"\\\"\\n\\nbesseli = r\\\"\\\"\\\"\\n``besseli(n, x, derivative=0)`` gives the modified Bessel function of the\\nfirst kind,\\n\\n.. math ::\\n\\n    I_n(x) = i^{-n} J_n(ix).\\n\\nWith *derivative* = `m \\\\ne 0`, the `m`-th derivative\\n\\n.. math ::\\n\\n    \\\\frac{d^m}{dx^m} I_n(x)\\n\\nis computed.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/besseli.py\\n.. image :: /plots/besseli.png\\n.. literalinclude :: /plots/besseli_c.py\\n.. image :: /plots/besseli_c.png\\n\\n**Examples**\\n\\nSome values of `I_n(x)`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> besseli(0,0)\\n    1.0\\n    >>> besseli(1,0)\\n    0.0\\n    >>> besseli(0,1)\\n    1.266065877752008335598245\\n    >>> besseli(3.5, 2+3j)\\n    (-0.2904369752642538144289025 - 0.4469098397654815837307006j)\\n\\nArguments may be large::\\n\\n    >>> besseli(2, 1000)\\n    2.480717210191852440616782e+432\\n    >>> besseli(2, 10**10)\\n    4.299602851624027900335391e+4342944813\\n    >>> besseli(2, 6000+10000j)\\n    (-2.114650753239580827144204e+2603 + 4.385040221241629041351886e+2602j)\\n\\nFor integers `n`, the following integral representation holds::\\n\\n    >>> mp.dps = 15\\n    >>> n = 3\\n    >>> x = 2.3\\n    >>> quad(lambda t: exp(x*cos(t))*cos(n*t), [0,pi])/pi\\n    0.349223221159309\\n    >>> besseli(n,x)\\n    0.349223221159309\\n\\nDerivatives and antiderivatives of any order can be computed::\\n\\n    >>> mp.dps = 25\\n    >>> besseli(2, 7.5, 1)\\n    195.8229038931399062565883\\n    >>> diff(lambda x: besseli(2,x), 7.5)\\n    195.8229038931399062565883\\n    >>> besseli(2, 7.5, 10)\\n    153.3296508971734525525176\\n    >>> diff(lambda x: besseli(2,x), 7.5, 10)\\n    153.3296508971734525525176\\n    >>> besseli(2,7.5,-1) - besseli(2,3.5,-1)\\n    202.5043900051930141956876\\n    >>> quad(lambda x: besseli(2,x), [3.5, 7.5])\\n    202.5043900051930141956876\\n\\n\\\"\\\"\\\"\\n\\nbessely = r\\\"\\\"\\\"\\n``bessely(n, x, derivative=0)`` gives the Bessel function of the second kind,\\n\\n.. math ::\\n\\n    Y_n(x) = \\\\frac{J_n(x) \\\\cos(\\\\pi n) - J_{-n}(x)}{\\\\sin(\\\\pi n)}.\\n\\nFor `n` an integer, this formula should be understood as a\\nlimit. With *derivative* = `m \\\\ne 0`, the `m`-th derivative\\n\\n.. math ::\\n\\n    \\\\frac{d^m}{dx^m} Y_n(x)\\n\\nis computed.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/bessely.py\\n.. image :: /plots/bessely.png\\n.. literalinclude :: /plots/bessely_c.py\\n.. image :: /plots/bessely_c.png\\n\\n**Examples**\\n\\nSome values of `Y_n(x)`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> bessely(0,0), bessely(1,0), bessely(2,0)\\n    (-inf, -inf, -inf)\\n    >>> bessely(1, pi)\\n    0.3588729167767189594679827\\n    >>> bessely(0.5, 3+4j)\\n    (9.242861436961450520325216 - 3.085042824915332562522402j)\\n\\nArguments may be large::\\n\\n    >>> bessely(0, 10000)\\n    0.00364780555898660588668872\\n    >>> bessely(2.5, 10**50)\\n    -4.8952500412050989295774e-26\\n    >>> bessely(2.5, -10**50)\\n    (0.0 + 4.8952500412050989295774e-26j)\\n\\nDerivatives and antiderivatives of any order can be computed::\\n\\n    >>> bessely(2, 3.5, 1)\\n    0.3842618820422660066089231\\n    >>> diff(lambda x: bessely(2, x), 3.5)\\n    0.3842618820422660066089231\\n    >>> bessely(0.5, 3.5, 1)\\n    -0.2066598304156764337900417\\n    >>> diff(lambda x: bessely(0.5, x), 3.5)\\n    -0.2066598304156764337900417\\n    >>> diff(lambda x: bessely(2, x), 0.5, 10)\\n    -208173867409.5547350101511\\n    >>> bessely(2, 0.5, 10)\\n    -208173867409.5547350101511\\n    >>> bessely(2, 100.5, 100)\\n    0.02668487547301372334849043\\n    >>> quad(lambda x: bessely(2,x), [1,3])\\n    -1.377046859093181969213262\\n    >>> bessely(2,3,-1) - bessely(2,1,-1)\\n    -1.377046859093181969213262\\n\\n\\\"\\\"\\\"\\n\\nbesselk = r\\\"\\\"\\\"\\n``besselk(n, x)`` gives the modified Bessel function of the\\nsecond kind,\\n\\n.. math ::\\n\\n    K_n(x) = \\\\frac{\\\\pi}{2} \\\\frac{I_{-n}(x)-I_{n}(x)}{\\\\sin(\\\\pi n)}\\n\\nFor `n` an integer, this formula should be understood as a\\nlimit.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/besselk.py\\n.. image :: /plots/besselk.png\\n.. literalinclude :: /plots/besselk_c.py\\n.. image :: /plots/besselk_c.png\\n\\n**Examples**\\n\\nEvaluation is supported for arbitrary complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> besselk(0,1)\\n    0.4210244382407083333356274\\n    >>> besselk(0, -1)\\n    (0.4210244382407083333356274 - 3.97746326050642263725661j)\\n    >>> besselk(3.5, 2+3j)\\n    (-0.02090732889633760668464128 + 0.2464022641351420167819697j)\\n    >>> besselk(2+3j, 0.5)\\n    (0.9615816021726349402626083 + 0.1918250181801757416908224j)\\n\\nArguments may be large::\\n\\n    >>> besselk(0, 100)\\n    4.656628229175902018939005e-45\\n    >>> besselk(1, 10**6)\\n    4.131967049321725588398296e-434298\\n    >>> besselk(1, 10**6*j)\\n    (0.001140348428252385844876706 - 0.0005200017201681152909000961j)\\n    >>> besselk(4.5, fmul(10**50, j, exact=True))\\n    (1.561034538142413947789221e-26 + 1.243554598118700063281496e-25j)\\n\\nThe point `x = 0` is a singularity (logarithmic if `n = 0`)::\\n\\n    >>> besselk(0,0)\\n    +inf\\n    >>> besselk(1,0)\\n    +inf\\n    >>> for n in range(-4, 5):\\n    ...     print(besselk(n, '1e-1000'))\\n    ...\\n    4.8e+4001\\n    8.0e+3000\\n    2.0e+2000\\n    1.0e+1000\\n    2302.701024509704096466802\\n    1.0e+1000\\n    2.0e+2000\\n    8.0e+3000\\n    4.8e+4001\\n\\n\\\"\\\"\\\"\\n\\nhankel1 = r\\\"\\\"\\\"\\n``hankel1(n,x)`` computes the Hankel function of the first kind,\\nwhich is the complex combination of Bessel functions given by\\n\\n.. math ::\\n\\n    H_n^{(1)}(x) = J_n(x) + i Y_n(x).\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/hankel1.py\\n.. image :: /plots/hankel1.png\\n.. literalinclude :: /plots/hankel1_c.py\\n.. image :: /plots/hankel1_c.png\\n\\n**Examples**\\n\\nThe Hankel function is generally complex-valued::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hankel1(2, pi)\\n    (0.4854339326315091097054957 - 0.0999007139290278787734903j)\\n    >>> hankel1(3.5, pi)\\n    (0.2340002029630507922628888 - 0.6419643823412927142424049j)\\n\\\"\\\"\\\"\\n\\nhankel2 = r\\\"\\\"\\\"\\n``hankel2(n,x)`` computes the Hankel function of the second kind,\\nwhich is the complex combination of Bessel functions given by\\n\\n.. math ::\\n\\n    H_n^{(2)}(x) = J_n(x) - i Y_n(x).\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/hankel2.py\\n.. image :: /plots/hankel2.png\\n.. literalinclude :: /plots/hankel2_c.py\\n.. image :: /plots/hankel2_c.png\\n\\n**Examples**\\n\\nThe Hankel function is generally complex-valued::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> hankel2(2, pi)\\n    (0.4854339326315091097054957 + 0.0999007139290278787734903j)\\n    >>> hankel2(3.5, pi)\\n    (0.2340002029630507922628888 + 0.6419643823412927142424049j)\\n\\\"\\\"\\\"\\n\\nlambertw = r\\\"\\\"\\\"\\nThe Lambert W function `W(z)` is defined as the inverse function\\nof `w \\\\exp(w)`. In other words, the value of `W(z)` is such that\\n`z = W(z) \\\\exp(W(z))` for any complex number `z`.\\n\\nThe Lambert W function is a multivalued function with infinitely\\nmany branches `W_k(z)`, indexed by `k \\\\in \\\\mathbb{Z}`. Each branch\\ngives a different solution `w` of the equation `z = w \\\\exp(w)`.\\nAll branches are supported by :func:`~mpmath.lambertw`:\\n\\n* ``lambertw(z)`` gives the principal solution (branch 0)\\n\\n* ``lambertw(z, k)`` gives the solution on branch `k`\\n\\nThe Lambert W function has two partially real branches: the\\nprincipal branch (`k = 0`) is real for real `z > -1/e`, and the\\n`k = -1` branch is real for `-1/e < z < 0`. All branches except\\n`k = 0` have a logarithmic singularity at `z = 0`.\\n\\nThe definition, implementation and choice of branches\\nis based on [Corless]_.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/lambertw.py\\n.. image :: /plots/lambertw.png\\n.. literalinclude :: /plots/lambertw_c.py\\n.. image :: /plots/lambertw_c.png\\n\\n**Basic examples**\\n\\nThe Lambert W function is the inverse of `w \\\\exp(w)`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> w = lambertw(1)\\n    >>> w\\n    0.5671432904097838729999687\\n    >>> w*exp(w)\\n    1.0\\n\\nAny branch gives a valid inverse::\\n\\n    >>> w = lambertw(1, k=3)\\n    >>> w\\n    (-2.853581755409037807206819 + 17.11353553941214591260783j)\\n    >>> w = lambertw(1, k=25)\\n    >>> w\\n    (-5.047020464221569709378686 + 155.4763860949415867162066j)\\n    >>> chop(w*exp(w))\\n    1.0\\n\\n**Applications to equation-solving**\\n\\nThe Lambert W function may be used to solve various kinds of\\nequations, such as finding the value of the infinite power\\ntower `z^{z^{z^{\\\\ldots}}}`::\\n\\n    >>> def tower(z, n):\\n    ...     if n == 0:\\n    ...         return z\\n    ...     return z ** tower(z, n-1)\\n    ...\\n    >>> tower(mpf(0.5), 100)\\n    0.6411857445049859844862005\\n    >>> -lambertw(-log(0.5))/log(0.5)\\n    0.6411857445049859844862005\\n\\n**Properties**\\n\\nThe Lambert W function grows roughly like the natural logarithm\\nfor large arguments::\\n\\n    >>> lambertw(1000); log(1000)\\n    5.249602852401596227126056\\n    6.907755278982137052053974\\n    >>> lambertw(10**100); log(10**100)\\n    224.8431064451185015393731\\n    230.2585092994045684017991\\n\\nThe principal branch of the Lambert W function has a rational\\nTaylor series expansion around `z = 0`::\\n\\n    >>> nprint(taylor(lambertw, 0, 6), 10)\\n    [0.0, 1.0, -1.0, 1.5, -2.666666667, 5.208333333, -10.8]\\n\\nSome special values and limits are::\\n\\n    >>> lambertw(0)\\n    0.0\\n    >>> lambertw(1)\\n    0.5671432904097838729999687\\n    >>> lambertw(e)\\n    1.0\\n    >>> lambertw(inf)\\n    +inf\\n    >>> lambertw(0, k=-1)\\n    -inf\\n    >>> lambertw(0, k=3)\\n    -inf\\n    >>> lambertw(inf, k=2)\\n    (+inf + 12.56637061435917295385057j)\\n    >>> lambertw(inf, k=3)\\n    (+inf + 18.84955592153875943077586j)\\n    >>> lambertw(-inf, k=3)\\n    (+inf + 21.9911485751285526692385j)\\n\\nThe `k = 0` and `k = -1` branches join at `z = -1/e` where\\n`W(z) = -1` for both branches. Since `-1/e` can only be represented\\napproximately with binary floating-point numbers, evaluating the\\nLambert W function at this point only gives `-1` approximately::\\n\\n    >>> lambertw(-1/e, 0)\\n    -0.9999999999998371330228251\\n    >>> lambertw(-1/e, -1)\\n    -1.000000000000162866977175\\n\\nIf `-1/e` happens to round in the negative direction, there might be\\na small imaginary part::\\n\\n    >>> mp.dps = 15\\n    >>> lambertw(-1/e)\\n    (-1.0 + 8.22007971483662e-9j)\\n    >>> lambertw(-1/e+eps)\\n    -0.999999966242188\\n\\n**References**\\n\\n1. [Corless]_\\n\\\"\\\"\\\"\\n\\nbarnesg = r\\\"\\\"\\\"\\nEvaluates the Barnes G-function, which generalizes the\\nsuperfactorial (:func:`~mpmath.superfac`) and by extension also the\\nhyperfactorial (:func:`~mpmath.hyperfac`) to the complex numbers\\nin an analogous way to how the gamma function generalizes\\nthe ordinary factorial.\\n\\nThe Barnes G-function may be defined in terms of a Weierstrass\\nproduct:\\n\\n.. math ::\\n\\n    G(z+1) = (2\\\\pi)^{z/2} e^{-[z(z+1)+\\\\gamma z^2]/2}\\n    \\\\prod_{n=1}^\\\\infty\\n    \\\\left[\\\\left(1+\\\\frac{z}{n}\\\\right)^ne^{-z+z^2/(2n)}\\\\right]\\n\\nFor positive integers `n`, we have have relation to superfactorials\\n`G(n) = \\\\mathrm{sf}(n-2) = 0! \\\\cdot 1! \\\\cdots (n-2)!`.\\n\\n**Examples**\\n\\nSome elementary values and limits of the Barnes G-function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> barnesg(1), barnesg(2), barnesg(3)\\n    (1.0, 1.0, 1.0)\\n    >>> barnesg(4)\\n    2.0\\n    >>> barnesg(5)\\n    12.0\\n    >>> barnesg(6)\\n    288.0\\n    >>> barnesg(7)\\n    34560.0\\n    >>> barnesg(8)\\n    24883200.0\\n    >>> barnesg(inf)\\n    +inf\\n    >>> barnesg(0), barnesg(-1), barnesg(-2)\\n    (0.0, 0.0, 0.0)\\n\\nClosed-form values are known for some rational arguments::\\n\\n    >>> barnesg('1/2')\\n    0.603244281209446\\n    >>> sqrt(exp(0.25+log(2)/12)/sqrt(pi)/glaisher**3)\\n    0.603244281209446\\n    >>> barnesg('1/4')\\n    0.29375596533861\\n    >>> nthroot(exp('3/8')/exp(catalan/pi)/\\n    ...      gamma(0.25)**3/sqrt(glaisher)**9, 4)\\n    0.29375596533861\\n\\nThe Barnes G-function satisfies the functional equation\\n`G(z+1) = \\\\Gamma(z) G(z)`::\\n\\n    >>> z = pi\\n    >>> barnesg(z+1)\\n    2.39292119327948\\n    >>> gamma(z)*barnesg(z)\\n    2.39292119327948\\n\\nThe asymptotic growth rate of the Barnes G-function is related to\\nthe Glaisher-Kinkelin constant::\\n\\n    >>> limit(lambda n: barnesg(n+1)/(n**(n**2/2-mpf(1)/12)*\\n    ...     (2*pi)**(n/2)*exp(-3*n**2/4)), inf)\\n    0.847536694177301\\n    >>> exp('1/12')/glaisher\\n    0.847536694177301\\n\\nThe Barnes G-function can be differentiated in closed form::\\n\\n    >>> z = 3\\n    >>> diff(barnesg, z)\\n    0.264507203401607\\n    >>> barnesg(z)*((z-1)*psi(0,z)-z+(log(2*pi)+1)/2)\\n    0.264507203401607\\n\\nEvaluation is supported for arbitrary arguments and at arbitrary\\nprecision::\\n\\n    >>> barnesg(6.5)\\n    2548.7457695685\\n    >>> barnesg(-pi)\\n    0.00535976768353037\\n    >>> barnesg(3+4j)\\n    (-0.000676375932234244 - 4.42236140124728e-5j)\\n    >>> mp.dps = 50\\n    >>> barnesg(1/sqrt(2))\\n    0.81305501090451340843586085064413533788206204124732\\n    >>> q = barnesg(10j)\\n    >>> q.real\\n    0.000000000021852360840356557241543036724799812371995850552234\\n    >>> q.imag\\n    -0.00000000000070035335320062304849020654215545839053210041457588\\n    >>> mp.dps = 15\\n    >>> barnesg(100)\\n    3.10361006263698e+6626\\n    >>> barnesg(-101)\\n    0.0\\n    >>> barnesg(-10.5)\\n    5.94463017605008e+25\\n    >>> barnesg(-10000.5)\\n    -6.14322868174828e+167480422\\n    >>> barnesg(1000j)\\n    (5.21133054865546e-1173597 + 4.27461836811016e-1173597j)\\n    >>> barnesg(-1000+1000j)\\n    (2.43114569750291e+1026623 + 2.24851410674842e+1026623j)\\n\\n\\n**References**\\n\\n1. Whittaker & Watson, *A Course of Modern Analysis*,\\n   Cambridge University Press, 4th edition (1927), p.264\\n2. http://en.wikipedia.org/wiki/Barnes_G-function\\n3. http://mathworld.wolfram.com/BarnesG-Function.html\\n\\n\\\"\\\"\\\"\\n\\nsuperfac = r\\\"\\\"\\\"\\nComputes the superfactorial, defined as the product of\\nconsecutive factorials\\n\\n.. math ::\\n\\n    \\\\mathrm{sf}(n) = \\\\prod_{k=1}^n k!\\n\\nFor general complex `z`, `\\\\mathrm{sf}(z)` is defined\\nin terms of the Barnes G-function (see :func:`~mpmath.barnesg`).\\n\\n**Examples**\\n\\nThe first few superfactorials are (OEIS A000178)::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(10):\\n    ...     print(\\\"%s %s\\\" % (n, superfac(n)))\\n    ...\\n    0 1.0\\n    1 1.0\\n    2 2.0\\n    3 12.0\\n    4 288.0\\n    5 34560.0\\n    6 24883200.0\\n    7 125411328000.0\\n    8 5.05658474496e+15\\n    9 1.83493347225108e+21\\n\\nSuperfactorials grow very rapidly::\\n\\n    >>> superfac(1000)\\n    3.24570818422368e+1177245\\n    >>> superfac(10**10)\\n    2.61398543581249e+467427913956904067453\\n\\nEvaluation is supported for arbitrary arguments::\\n\\n    >>> mp.dps = 25\\n    >>> superfac(pi)\\n    17.20051550121297985285333\\n    >>> superfac(2+3j)\\n    (-0.005915485633199789627466468 + 0.008156449464604044948738263j)\\n    >>> diff(superfac, 1)\\n    0.2645072034016070205673056\\n\\n**References**\\n\\n1. http://oeis.org/A000178\\n\\n\\\"\\\"\\\"\\n\\n\\nhyperfac = r\\\"\\\"\\\"\\nComputes the hyperfactorial, defined for integers as the product\\n\\n.. math ::\\n\\n    H(n) = \\\\prod_{k=1}^n k^k.\\n\\n\\nThe hyperfactorial satisfies the recurrence formula `H(z) = z^z H(z-1)`.\\nIt can be defined more generally in terms of the Barnes G-function (see\\n:func:`~mpmath.barnesg`) and the gamma function by the formula\\n\\n.. math ::\\n\\n    H(z) = \\\\frac{\\\\Gamma(z+1)^z}{G(z)}.\\n\\nThe extension to complex numbers can also be done via\\nthe integral representation\\n\\n.. math ::\\n\\n    H(z) = (2\\\\pi)^{-z/2} \\\\exp \\\\left[\\n        {z+1 \\\\choose 2} + \\\\int_0^z \\\\log(t!)\\\\,dt\\n        \\\\right].\\n\\n**Examples**\\n\\nThe rapidly-growing sequence of hyperfactorials begins\\n(OEIS A002109)::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(10):\\n    ...     print(\\\"%s %s\\\" % (n, hyperfac(n)))\\n    ...\\n    0 1.0\\n    1 1.0\\n    2 4.0\\n    3 108.0\\n    4 27648.0\\n    5 86400000.0\\n    6 4031078400000.0\\n    7 3.3197663987712e+18\\n    8 5.56964379417266e+25\\n    9 2.15779412229419e+34\\n\\nSome even larger hyperfactorials are::\\n\\n    >>> hyperfac(1000)\\n    5.46458120882585e+1392926\\n    >>> hyperfac(10**10)\\n    4.60408207642219e+489142638002418704309\\n\\nThe hyperfactorial can be evaluated for arbitrary arguments::\\n\\n    >>> hyperfac(0.5)\\n    0.880449235173423\\n    >>> diff(hyperfac, 1)\\n    0.581061466795327\\n    >>> hyperfac(pi)\\n    205.211134637462\\n    >>> hyperfac(-10+1j)\\n    (3.01144471378225e+46 - 2.45285242480185e+46j)\\n\\nThe recurrence property of the hyperfactorial holds\\ngenerally::\\n\\n    >>> z = 3-4*j\\n    >>> hyperfac(z)\\n    (-4.49795891462086e-7 - 6.33262283196162e-7j)\\n    >>> z**z * hyperfac(z-1)\\n    (-4.49795891462086e-7 - 6.33262283196162e-7j)\\n    >>> z = mpf(-0.6)\\n    >>> chop(z**z * hyperfac(z-1))\\n    1.28170142849352\\n    >>> hyperfac(z)\\n    1.28170142849352\\n\\nThe hyperfactorial may also be computed using the integral\\ndefinition::\\n\\n    >>> z = 2.5\\n    >>> hyperfac(z)\\n    15.9842119922237\\n    >>> (2*pi)**(-z/2)*exp(binomial(z+1,2) +\\n    ...     quad(lambda t: loggamma(t+1), [0, z]))\\n    15.9842119922237\\n\\n:func:`~mpmath.hyperfac` supports arbitrary-precision evaluation::\\n\\n    >>> mp.dps = 50\\n    >>> hyperfac(10)\\n    215779412229418562091680268288000000000000000.0\\n    >>> hyperfac(1/sqrt(2))\\n    0.89404818005227001975423476035729076375705084390942\\n\\n**References**\\n\\n1. http://oeis.org/A002109\\n2. http://mathworld.wolfram.com/Hyperfactorial.html\\n\\n\\\"\\\"\\\"\\n\\nrgamma = r\\\"\\\"\\\"\\nComputes the reciprocal of the gamma function, `1/\\\\Gamma(z)`. This\\nfunction evaluates to zero at the poles\\nof the gamma function, `z = 0, -1, -2, \\\\ldots`.\\n\\n**Examples**\\n\\nBasic examples::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> rgamma(1)\\n    1.0\\n    >>> rgamma(4)\\n    0.1666666666666666666666667\\n    >>> rgamma(0); rgamma(-1)\\n    0.0\\n    0.0\\n    >>> rgamma(1000)\\n    2.485168143266784862783596e-2565\\n    >>> rgamma(inf)\\n    0.0\\n\\nA definite integral that can be evaluated in terms of elementary\\nintegrals::\\n\\n    >>> quad(rgamma, [0,inf])\\n    2.807770242028519365221501\\n    >>> e + quad(lambda t: exp(-t)/(pi**2+log(t)**2), [0,inf])\\n    2.807770242028519365221501\\n\\\"\\\"\\\"\\n\\nloggamma = r\\\"\\\"\\\"\\nComputes the principal branch of the log-gamma function,\\n`\\\\ln \\\\Gamma(z)`. Unlike `\\\\ln(\\\\Gamma(z))`, which has infinitely many\\ncomplex branch cuts, the principal log-gamma function only has a single\\nbranch cut along the negative half-axis. The principal branch\\ncontinuously matches the asymptotic Stirling expansion\\n\\n.. math ::\\n\\n    \\\\ln \\\\Gamma(z) \\\\sim \\\\frac{\\\\ln(2 \\\\pi)}{2} +\\n        \\\\left(z-\\\\frac{1}{2}\\\\right) \\\\ln(z) - z + O(z^{-1}).\\n\\nThe real parts of both functions agree, but their imaginary\\nparts generally differ by `2 n \\\\pi` for some `n \\\\in \\\\mathbb{Z}`.\\nThey coincide for `z \\\\in \\\\mathbb{R}, z > 0`.\\n\\nComputationally, it is advantageous to use :func:`~mpmath.loggamma`\\ninstead of :func:`~mpmath.gamma` for extremely large arguments.\\n\\n**Examples**\\n\\nComparing with `\\\\ln(\\\\Gamma(z))`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> loggamma('13.2'); log(gamma('13.2'))\\n    20.49400419456603678498394\\n    20.49400419456603678498394\\n    >>> loggamma(3+4j)\\n    (-1.756626784603784110530604 + 4.742664438034657928194889j)\\n    >>> log(gamma(3+4j))\\n    (-1.756626784603784110530604 - 1.540520869144928548730397j)\\n    >>> log(gamma(3+4j)) + 2*pi*j\\n    (-1.756626784603784110530604 + 4.742664438034657928194889j)\\n\\nNote the imaginary parts for negative arguments::\\n\\n    >>> loggamma(-0.5); loggamma(-1.5); loggamma(-2.5)\\n    (1.265512123484645396488946 - 3.141592653589793238462643j)\\n    (0.8600470153764810145109327 - 6.283185307179586476925287j)\\n    (-0.05624371649767405067259453 - 9.42477796076937971538793j)\\n\\nSome special values::\\n\\n    >>> loggamma(1); loggamma(2)\\n    0.0\\n    0.0\\n    >>> loggamma(3); +ln2\\n    0.6931471805599453094172321\\n    0.6931471805599453094172321\\n    >>> loggamma(3.5); log(15*sqrt(pi)/8)\\n    1.200973602347074224816022\\n    1.200973602347074224816022\\n    >>> loggamma(inf)\\n    +inf\\n\\nHuge arguments are permitted::\\n\\n    >>> loggamma('1e30')\\n    6.807755278982137052053974e+31\\n    >>> loggamma('1e300')\\n    6.897755278982137052053974e+302\\n    >>> loggamma('1e3000')\\n    6.906755278982137052053974e+3003\\n    >>> loggamma('1e100000000000000000000')\\n    2.302585092994045684007991e+100000000000000000020\\n    >>> loggamma('1e30j')\\n    (-1.570796326794896619231322e+30 + 6.807755278982137052053974e+31j)\\n    >>> loggamma('1e300j')\\n    (-1.570796326794896619231322e+300 + 6.897755278982137052053974e+302j)\\n    >>> loggamma('1e3000j')\\n    (-1.570796326794896619231322e+3000 + 6.906755278982137052053974e+3003j)\\n\\nThe log-gamma function can be integrated analytically\\non any interval of unit length::\\n\\n    >>> z = 0\\n    >>> quad(loggamma, [z,z+1]); log(2*pi)/2\\n    0.9189385332046727417803297\\n    0.9189385332046727417803297\\n    >>> z = 3+4j\\n    >>> quad(loggamma, [z,z+1]); (log(z)-1)*z + log(2*pi)/2\\n    (-0.9619286014994750641314421 + 5.219637303741238195688575j)\\n    (-0.9619286014994750641314421 + 5.219637303741238195688575j)\\n\\nThe derivatives of the log-gamma function are given by the\\npolygamma function (:func:`~mpmath.psi`)::\\n\\n    >>> diff(loggamma, -4+3j); psi(0, -4+3j)\\n    (1.688493531222971393607153 + 2.554898911356806978892748j)\\n    (1.688493531222971393607153 + 2.554898911356806978892748j)\\n    >>> diff(loggamma, -4+3j, 2); psi(1, -4+3j)\\n    (-0.1539414829219882371561038 - 0.1020485197430267719746479j)\\n    (-0.1539414829219882371561038 - 0.1020485197430267719746479j)\\n\\nThe log-gamma function satisfies an additive form of the\\nrecurrence relation for the ordinary gamma function::\\n\\n    >>> z = 2+3j\\n    >>> loggamma(z); loggamma(z+1) - log(z)\\n    (-2.092851753092733349564189 + 2.302396543466867626153708j)\\n    (-2.092851753092733349564189 + 2.302396543466867626153708j)\\n\\n\\\"\\\"\\\"\\n\\nsiegeltheta = r\\\"\\\"\\\"\\nComputes the Riemann-Siegel theta function,\\n\\n.. math ::\\n\\n    \\\\theta(t) = \\\\frac{\\n    \\\\log\\\\Gamma\\\\left(\\\\frac{1+2it}{4}\\\\right) -\\n    \\\\log\\\\Gamma\\\\left(\\\\frac{1-2it}{4}\\\\right)\\n    }{2i} - \\\\frac{\\\\log \\\\pi}{2} t.\\n\\nThe Riemann-Siegel theta function is important in\\nproviding the phase factor for the Z-function\\n(see :func:`~mpmath.siegelz`). Evaluation is supported for real and\\ncomplex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> siegeltheta(0)\\n    0.0\\n    >>> siegeltheta(inf)\\n    +inf\\n    >>> siegeltheta(-inf)\\n    -inf\\n    >>> siegeltheta(1)\\n    -1.767547952812290388302216\\n    >>> siegeltheta(10+0.25j)\\n    (-3.068638039426838572528867 + 0.05804937947429712998395177j)\\n\\nArbitrary derivatives may be computed with derivative = k\\n\\n    >>> siegeltheta(1234, derivative=2)\\n    0.0004051864079114053109473741\\n    >>> diff(siegeltheta, 1234, n=2)\\n    0.0004051864079114053109473741\\n\\n\\nThe Riemann-Siegel theta function has odd symmetry around `t = 0`,\\ntwo local extreme points and three real roots including 0 (located\\nsymmetrically)::\\n\\n    >>> nprint(chop(taylor(siegeltheta, 0, 5)))\\n    [0.0, -2.68609, 0.0, 2.69433, 0.0, -6.40218]\\n    >>> findroot(diffun(siegeltheta), 7)\\n    6.28983598883690277966509\\n    >>> findroot(siegeltheta, 20)\\n    17.84559954041086081682634\\n\\nFor large `t`, there is a famous asymptotic formula\\nfor `\\\\theta(t)`, to first order given by::\\n\\n    >>> t = mpf(10**6)\\n    >>> siegeltheta(t)\\n    5488816.353078403444882823\\n    >>> -t*log(2*pi/t)/2-t/2\\n    5488816.745777464310273645\\n\\\"\\\"\\\"\\n\\ngrampoint = r\\\"\\\"\\\"\\nGives the `n`-th Gram point `g_n`, defined as the solution\\nto the equation `\\\\theta(g_n) = \\\\pi n` where `\\\\theta(t)`\\nis the Riemann-Siegel theta function (:func:`~mpmath.siegeltheta`).\\n\\nThe first few Gram points are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> grampoint(0)\\n    17.84559954041086081682634\\n    >>> grampoint(1)\\n    23.17028270124630927899664\\n    >>> grampoint(2)\\n    27.67018221781633796093849\\n    >>> grampoint(3)\\n    31.71797995476405317955149\\n\\nChecking the definition::\\n\\n    >>> siegeltheta(grampoint(3))\\n    9.42477796076937971538793\\n    >>> 3*pi\\n    9.42477796076937971538793\\n\\nA large Gram point::\\n\\n    >>> grampoint(10**10)\\n    3293531632.728335454561153\\n\\nGram points are useful when studying the Z-function\\n(:func:`~mpmath.siegelz`). See the documentation of that function\\nfor additional examples.\\n\\n:func:`~mpmath.grampoint` can solve the defining equation for\\nnonintegral `n`. There is a fixed point where `g(x) = x`::\\n\\n    >>> findroot(lambda x: grampoint(x) - x, 10000)\\n    9146.698193171459265866198\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/GramPoint.html\\n\\n\\\"\\\"\\\"\\n\\nsiegelz = r\\\"\\\"\\\"\\nComputes the Z-function, also known as the Riemann-Siegel Z function,\\n\\n.. math ::\\n\\n    Z(t) = e^{i \\\\theta(t)} \\\\zeta(1/2+it)\\n\\nwhere `\\\\zeta(s)` is the Riemann zeta function (:func:`~mpmath.zeta`)\\nand where `\\\\theta(t)` denotes the Riemann-Siegel theta function\\n(see :func:`~mpmath.siegeltheta`).\\n\\nEvaluation is supported for real and complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> siegelz(1)\\n    -0.7363054628673177346778998\\n    >>> siegelz(3+4j)\\n    (-0.1852895764366314976003936 - 0.2773099198055652246992479j)\\n\\nThe first four derivatives are supported, using the\\noptional *derivative* keyword argument::\\n\\n    >>> siegelz(1234567, derivative=3)\\n    56.89689348495089294249178\\n    >>> diff(siegelz, 1234567, n=3)\\n    56.89689348495089294249178\\n\\n\\nThe Z-function has a Maclaurin expansion::\\n\\n    >>> nprint(chop(taylor(siegelz, 0, 4)))\\n    [-1.46035, 0.0, 2.73588, 0.0, -8.39357]\\n\\nThe Z-function `Z(t)` is equal to `\\\\pm |\\\\zeta(s)|` on the\\ncritical line `s = 1/2+it` (i.e. for real arguments `t`\\nto `Z`).  Its zeros coincide with those of the Riemann zeta\\nfunction::\\n\\n    >>> findroot(siegelz, 14)\\n    14.13472514173469379045725\\n    >>> findroot(siegelz, 20)\\n    21.02203963877155499262848\\n    >>> findroot(zeta, 0.5+14j)\\n    (0.5 + 14.13472514173469379045725j)\\n    >>> findroot(zeta, 0.5+20j)\\n    (0.5 + 21.02203963877155499262848j)\\n\\nSince the Z-function is real-valued on the critical line\\n(and unlike `|\\\\zeta(s)|` analytic), it is useful for\\ninvestigating the zeros of the Riemann zeta function.\\nFor example, one can use a root-finding algorithm based\\non sign changes::\\n\\n    >>> findroot(siegelz, [100, 200], solver='bisect')\\n    176.4414342977104188888926\\n\\nTo locate roots, Gram points `g_n` which can be computed\\nby :func:`~mpmath.grampoint` are useful. If `(-1)^n Z(g_n)` is\\npositive for two consecutive `n`, then `Z(t)` must have\\na zero between those points::\\n\\n    >>> g10 = grampoint(10)\\n    >>> g11 = grampoint(11)\\n    >>> (-1)**10 * siegelz(g10) > 0\\n    True\\n    >>> (-1)**11 * siegelz(g11) > 0\\n    True\\n    >>> findroot(siegelz, [g10, g11], solver='bisect')\\n    56.44624769706339480436776\\n    >>> g10, g11\\n    (54.67523744685325626632663, 57.54516517954725443703014)\\n\\n\\\"\\\"\\\"\\n\\nriemannr = r\\\"\\\"\\\"\\nEvaluates the Riemann R function, a smooth approximation of the\\nprime counting function `\\\\pi(x)` (see :func:`~mpmath.primepi`). The Riemann\\nR function gives a fast numerical approximation useful e.g. to\\nroughly estimate the number of primes in a given interval.\\n\\nThe Riemann R function is computed using the rapidly convergent Gram\\nseries,\\n\\n.. math ::\\n\\n    R(x) = 1 + \\\\sum_{k=1}^{\\\\infty}\\n        \\\\frac{\\\\log^k x}{k k! \\\\zeta(k+1)}.\\n\\nFrom the Gram series, one sees that the Riemann R function is a\\nwell-defined analytic function (except for a branch cut along\\nthe negative real half-axis); it can be evaluated for arbitrary\\nreal or complex arguments.\\n\\nThe Riemann R function gives a very accurate approximation\\nof the prime counting function. For example, it is wrong by at\\nmost 2 for `x < 1000`, and for `x = 10^9` differs from the exact\\nvalue of `\\\\pi(x)` by 79, or less than two parts in a million.\\nIt is about 10 times more accurate than the logarithmic integral\\nestimate (see :func:`~mpmath.li`), which however is even faster to evaluate.\\nIt is orders of magnitude more accurate than the extremely\\nfast `x/\\\\log x` estimate.\\n\\n**Examples**\\n\\nFor small arguments, the Riemann R function almost exactly\\ngives the prime counting function if rounded to the nearest\\ninteger::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> primepi(50), riemannr(50)\\n    (15, 14.9757023241462)\\n    >>> max(abs(primepi(n)-int(round(riemannr(n)))) for n in range(100))\\n    1\\n    >>> max(abs(primepi(n)-int(round(riemannr(n)))) for n in range(300))\\n    2\\n\\nThe Riemann R function can be evaluated for arguments far too large\\nfor exact determination of `\\\\pi(x)` to be computationally\\nfeasible with any presently known algorithm::\\n\\n    >>> riemannr(10**30)\\n    1.46923988977204e+28\\n    >>> riemannr(10**100)\\n    4.3619719871407e+97\\n    >>> riemannr(10**1000)\\n    4.3448325764012e+996\\n\\nA comparison of the Riemann R function and logarithmic integral estimates\\nfor `\\\\pi(x)` using exact values of `\\\\pi(10^n)` up to `n = 9`.\\nThe fractional error is shown in parentheses::\\n\\n    >>> exact = [4,25,168,1229,9592,78498,664579,5761455,50847534]\\n    >>> for n, p in enumerate(exact):\\n    ...     n += 1\\n    ...     r, l = riemannr(10**n), li(10**n)\\n    ...     rerr, lerr = nstr((r-p)/p,3), nstr((l-p)/p,3)\\n    ...     print(\\\"%i %i %s(%s) %s(%s)\\\" % (n, p, r, rerr, l, lerr))\\n    ...\\n    1 4 4.56458314100509(0.141) 6.1655995047873(0.541)\\n    2 25 25.6616332669242(0.0265) 30.1261415840796(0.205)\\n    3 168 168.359446281167(0.00214) 177.609657990152(0.0572)\\n    4 1229 1226.93121834343(-0.00168) 1246.13721589939(0.0139)\\n    5 9592 9587.43173884197(-0.000476) 9629.8090010508(0.00394)\\n    6 78498 78527.3994291277(0.000375) 78627.5491594622(0.00165)\\n    7 664579 664667.447564748(0.000133) 664918.405048569(0.000511)\\n    8 5761455 5761551.86732017(1.68e-5) 5762209.37544803(0.000131)\\n    9 50847534 50847455.4277214(-1.55e-6) 50849234.9570018(3.35e-5)\\n\\nThe derivative of the Riemann R function gives the approximate\\nprobability for a number of magnitude `x` to be prime::\\n\\n    >>> diff(riemannr, 1000)\\n    0.141903028110784\\n    >>> mpf(primepi(1050) - primepi(950)) / 100\\n    0.15\\n\\nEvaluation is supported for arbitrary arguments and at arbitrary\\nprecision::\\n\\n    >>> mp.dps = 30\\n    >>> riemannr(7.5)\\n    3.72934743264966261918857135136\\n    >>> riemannr(-4+2j)\\n    (-0.551002208155486427591793957644 + 2.16966398138119450043195899746j)\\n\\n\\\"\\\"\\\"\\n\\nprimepi = r\\\"\\\"\\\"\\nEvaluates the prime counting function, `\\\\pi(x)`, which gives\\nthe number of primes less than or equal to `x`. The argument\\n`x` may be fractional.\\n\\nThe prime counting function is very expensive to evaluate\\nprecisely for large `x`, and the present implementation is\\nnot optimized in any way. For numerical approximation of the\\nprime counting function, it is better to use :func:`~mpmath.primepi2`\\nor :func:`~mpmath.riemannr`.\\n\\nSome values of the prime counting function::\\n\\n    >>> from mpmath import *\\n    >>> [primepi(k) for k in range(20)]\\n    [0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8]\\n    >>> primepi(3.5)\\n    2\\n    >>> primepi(100000)\\n    9592\\n\\n\\\"\\\"\\\"\\n\\nprimepi2 = r\\\"\\\"\\\"\\nReturns an interval (as an ``mpi`` instance) providing bounds\\nfor the value of the prime counting function `\\\\pi(x)`. For small\\n`x`, :func:`~mpmath.primepi2` returns an exact interval based on\\nthe output of :func:`~mpmath.primepi`. For `x > 2656`, a loose interval\\nbased on Schoenfeld's inequality\\n\\n.. math ::\\n\\n    |\\\\pi(x) - \\\\mathrm{li}(x)| < \\\\frac{\\\\sqrt x \\\\log x}{8 \\\\pi}\\n\\nis returned. This estimate is rigorous assuming the truth of\\nthe Riemann hypothesis, and can be computed very quickly.\\n\\n**Examples**\\n\\nExact values of the prime counting function for small `x`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> iv.dps = 15; iv.pretty = True\\n    >>> primepi2(10)\\n    [4.0, 4.0]\\n    >>> primepi2(100)\\n    [25.0, 25.0]\\n    >>> primepi2(1000)\\n    [168.0, 168.0]\\n\\nLoose intervals are generated for moderately large `x`:\\n\\n    >>> primepi2(10000), primepi(10000)\\n    ([1209.0, 1283.0], 1229)\\n    >>> primepi2(50000), primepi(50000)\\n    ([5070.0, 5263.0], 5133)\\n\\nAs `x` increases, the absolute error gets worse while the relative\\nerror improves. The exact value of `\\\\pi(10^{23})` is\\n1925320391606803968923, and :func:`~mpmath.primepi2` gives 9 significant\\ndigits::\\n\\n    >>> p = primepi2(10**23)\\n    >>> p\\n    [1.9253203909477020467e+21, 1.925320392280406229e+21]\\n    >>> mpf(p.delta) / mpf(p.a)\\n    6.9219865355293e-10\\n\\nA more precise, nonrigorous estimate for `\\\\pi(x)` can be\\nobtained using the Riemann R function (:func:`~mpmath.riemannr`).\\nFor large enough `x`, the value returned by :func:`~mpmath.primepi2`\\nessentially amounts to a small perturbation of the value returned by\\n:func:`~mpmath.riemannr`::\\n\\n    >>> primepi2(10**100)\\n    [4.3619719871407024816e+97, 4.3619719871407032404e+97]\\n    >>> riemannr(10**100)\\n    4.3619719871407e+97\\n\\\"\\\"\\\"\\n\\nprimezeta = r\\\"\\\"\\\"\\nComputes the prime zeta function, which is defined\\nin analogy with the Riemann zeta function (:func:`~mpmath.zeta`)\\nas\\n\\n.. math ::\\n\\n    P(s) = \\\\sum_p \\\\frac{1}{p^s}\\n\\nwhere the sum is taken over all prime numbers `p`. Although\\nthis sum only converges for `\\\\mathrm{Re}(s) > 1`, the\\nfunction is defined by analytic continuation in the\\nhalf-plane `\\\\mathrm{Re}(s) > 0`.\\n\\n**Examples**\\n\\nArbitrary-precision evaluation for real and complex arguments is\\nsupported::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 30; mp.pretty = True\\n    >>> primezeta(2)\\n    0.452247420041065498506543364832\\n    >>> primezeta(pi)\\n    0.15483752698840284272036497397\\n    >>> mp.dps = 50\\n    >>> primezeta(3)\\n    0.17476263929944353642311331466570670097541212192615\\n    >>> mp.dps = 20\\n    >>> primezeta(3+4j)\\n    (-0.12085382601645763295 - 0.013370403397787023602j)\\n\\nThe prime zeta function has a logarithmic pole at `s = 1`,\\nwith residue equal to the difference of the Mertens and\\nEuler constants::\\n\\n    >>> primezeta(1)\\n    +inf\\n    >>> extradps(25)(lambda x: primezeta(1+x)+log(x))(+eps)\\n    -0.31571845205389007685\\n    >>> mertens-euler\\n    -0.31571845205389007685\\n\\nThe analytic continuation to `0 < \\\\mathrm{Re}(s) \\\\le 1`\\nis implemented. In this strip the function exhibits\\nvery complex behavior; on the unit interval, it has poles at\\n`1/n` for every squarefree integer `n`::\\n\\n    >>> primezeta(0.5)         # Pole at s = 1/2\\n    (-inf + 3.1415926535897932385j)\\n    >>> primezeta(0.25)\\n    (-1.0416106801757269036 + 0.52359877559829887308j)\\n    >>> primezeta(0.5+10j)\\n    (0.54892423556409790529 + 0.45626803423487934264j)\\n\\nAlthough evaluation works in principle for any `\\\\mathrm{Re}(s) > 0`,\\nit should be noted that the evaluation time increases exponentially\\nas `s` approaches the imaginary axis.\\n\\nFor large `\\\\mathrm{Re}(s)`, `P(s)` is asymptotic to `2^{-s}`::\\n\\n    >>> primezeta(inf)\\n    0.0\\n    >>> primezeta(10), mpf(2)**-10\\n    (0.00099360357443698021786, 0.0009765625)\\n    >>> primezeta(1000)\\n    9.3326361850321887899e-302\\n    >>> primezeta(1000+1000j)\\n    (-3.8565440833654995949e-302 - 8.4985390447553234305e-302j)\\n\\n**References**\\n\\nCarl-Erik Froberg, \\\"On the prime zeta function\\\",\\nBIT 8 (1968), pp. 187-202.\\n\\n\\\"\\\"\\\"\\n\\nbernpoly = r\\\"\\\"\\\"\\nEvaluates the Bernoulli polynomial `B_n(z)`.\\n\\nThe first few Bernoulli polynomials are::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(6):\\n    ...     nprint(chop(taylor(lambda x: bernpoly(n,x), 0, n)))\\n    ...\\n    [1.0]\\n    [-0.5, 1.0]\\n    [0.166667, -1.0, 1.0]\\n    [0.0, 0.5, -1.5, 1.0]\\n    [-0.0333333, 0.0, 1.0, -2.0, 1.0]\\n    [0.0, -0.166667, 0.0, 1.66667, -2.5, 1.0]\\n\\nAt `z = 0`, the Bernoulli polynomial evaluates to a\\nBernoulli number (see :func:`~mpmath.bernoulli`)::\\n\\n    >>> bernpoly(12, 0), bernoulli(12)\\n    (-0.253113553113553, -0.253113553113553)\\n    >>> bernpoly(13, 0), bernoulli(13)\\n    (0.0, 0.0)\\n\\nEvaluation is accurate for large `n` and small `z`::\\n\\n    >>> mp.dps = 25\\n    >>> bernpoly(100, 0.5)\\n    2.838224957069370695926416e+78\\n    >>> bernpoly(1000, 10.5)\\n    5.318704469415522036482914e+1769\\n\\n\\\"\\\"\\\"\\n\\npolylog = r\\\"\\\"\\\"\\nComputes the polylogarithm, defined by the sum\\n\\n.. math ::\\n\\n    \\\\mathrm{Li}_s(z) = \\\\sum_{k=1}^{\\\\infty} \\\\frac{z^k}{k^s}.\\n\\nThis series is convergent only for `|z| < 1`, so elsewhere\\nthe analytic continuation is implied.\\n\\nThe polylogarithm should not be confused with the logarithmic\\nintegral (also denoted by Li or li), which is implemented\\nas :func:`~mpmath.li`.\\n\\n**Examples**\\n\\nThe polylogarithm satisfies a huge number of functional identities.\\nA sample of polylogarithm evaluations is shown below::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> polylog(1,0.5), log(2)\\n    (0.693147180559945, 0.693147180559945)\\n    >>> polylog(2,0.5), (pi**2-6*log(2)**2)/12\\n    (0.582240526465012, 0.582240526465012)\\n    >>> polylog(2,-phi), -log(phi)**2-pi**2/10\\n    (-1.21852526068613, -1.21852526068613)\\n    >>> polylog(3,0.5), 7*zeta(3)/8-pi**2*log(2)/12+log(2)**3/6\\n    (0.53721319360804, 0.53721319360804)\\n\\n:func:`~mpmath.polylog` can evaluate the analytic continuation of the\\npolylogarithm when `s` is an integer::\\n\\n    >>> polylog(2, 10)\\n    (0.536301287357863 - 7.23378441241546j)\\n    >>> polylog(2, -10)\\n    -4.1982778868581\\n    >>> polylog(2, 10j)\\n    (-3.05968879432873 + 3.71678149306807j)\\n    >>> polylog(-2, 10)\\n    -0.150891632373114\\n    >>> polylog(-2, -10)\\n    0.067618332081142\\n    >>> polylog(-2, 10j)\\n    (0.0384353698579347 + 0.0912451798066779j)\\n\\nSome more examples, with arguments on the unit circle (note that\\nthe series definition cannot be used for computation here)::\\n\\n    >>> polylog(2,j)\\n    (-0.205616758356028 + 0.915965594177219j)\\n    >>> j*catalan-pi**2/48\\n    (-0.205616758356028 + 0.915965594177219j)\\n    >>> polylog(3,exp(2*pi*j/3))\\n    (-0.534247512515375 + 0.765587078525922j)\\n    >>> -4*zeta(3)/9 + 2*j*pi**3/81\\n    (-0.534247512515375 + 0.765587078525921j)\\n\\nPolylogarithms of different order are related by integration\\nand differentiation::\\n\\n    >>> s, z = 3, 0.5\\n    >>> polylog(s+1, z)\\n    0.517479061673899\\n    >>> quad(lambda t: polylog(s,t)/t, [0, z])\\n    0.517479061673899\\n    >>> z*diff(lambda t: polylog(s+2,t), z)\\n    0.517479061673899\\n\\nTaylor series expansions around `z = 0` are::\\n\\n    >>> for n in range(-3, 4):\\n    ...     nprint(taylor(lambda x: polylog(n,x), 0, 5))\\n    ...\\n    [0.0, 1.0, 8.0, 27.0, 64.0, 125.0]\\n    [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]\\n    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]\\n    [0.0, 1.0, 1.0, 1.0, 1.0, 1.0]\\n    [0.0, 1.0, 0.5, 0.333333, 0.25, 0.2]\\n    [0.0, 1.0, 0.25, 0.111111, 0.0625, 0.04]\\n    [0.0, 1.0, 0.125, 0.037037, 0.015625, 0.008]\\n\\nThe series defining the polylogarithm is simultaneously\\na Taylor series and an L-series. For certain values of `z`, the\\npolylogarithm reduces to a pure zeta function::\\n\\n    >>> polylog(pi, 1), zeta(pi)\\n    (1.17624173838258, 1.17624173838258)\\n    >>> polylog(pi, -1), -altzeta(pi)\\n    (-0.909670702980385, -0.909670702980385)\\n\\nEvaluation for arbitrary, nonintegral `s` is supported\\nfor `z` within the unit circle:\\n\\n    >>> polylog(3+4j, 0.25)\\n    (0.24258605789446 - 0.00222938275488344j)\\n    >>> nsum(lambda k: 0.25**k / k**(3+4j), [1,inf])\\n    (0.24258605789446 - 0.00222938275488344j)\\n\\nIt is also supported outside of the unit circle::\\n\\n    >>> polylog(1+j, 20+40j)\\n    (-7.1421172179728 - 3.92726697721369j)\\n    >>> polylog(1+j, 200+400j)\\n    (-5.41934747194626 - 9.94037752563927j)\\n\\n**References**\\n\\n1. Richard Crandall, \\\"Note on fast polylogarithm computation\\\"\\n   http://www.reed.edu/physics/faculty/crandall/papers/Polylog.pdf\\n2. http://en.wikipedia.org/wiki/Polylogarithm\\n3. http://mathworld.wolfram.com/Polylogarithm.html\\n\\n\\\"\\\"\\\"\\n\\nbell = r\\\"\\\"\\\"\\nFor `n` a nonnegative integer, ``bell(n,x)`` evaluates the Bell\\npolynomial `B_n(x)`, the first few of which are\\n\\n.. math ::\\n\\n    B_0(x) = 1\\n\\n    B_1(x) = x\\n\\n    B_2(x) = x^2+x\\n\\n    B_3(x) = x^3+3x^2+x\\n\\nIf `x = 1` or :func:`~mpmath.bell` is called with only one argument, it\\ngives the `n`-th Bell number `B_n`, which is the number of\\npartitions of a set with `n` elements. By setting the precision to\\nat least `\\\\log_{10} B_n` digits, :func:`~mpmath.bell` provides fast\\ncalculation of exact Bell numbers.\\n\\nIn general, :func:`~mpmath.bell` computes\\n\\n.. math ::\\n\\n    B_n(x) = e^{-x} \\\\left(\\\\mathrm{sinc}(\\\\pi n) + E_n(x)\\\\right)\\n\\nwhere `E_n(x)` is the generalized exponential function implemented\\nby :func:`~mpmath.polyexp`. This is an extension of Dobinski's formula [1],\\nwhere the modification is the sinc term ensuring that `B_n(x)` is\\ncontinuous in `n`; :func:`~mpmath.bell` can thus be evaluated,\\ndifferentiated, etc for arbitrary complex arguments.\\n\\n**Examples**\\n\\nSimple evaluations::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> bell(0, 2.5)\\n    1.0\\n    >>> bell(1, 2.5)\\n    2.5\\n    >>> bell(2, 2.5)\\n    8.75\\n\\nEvaluation for arbitrary complex arguments::\\n\\n    >>> bell(5.75+1j, 2-3j)\\n    (-10767.71345136587098445143 - 15449.55065599872579097221j)\\n\\nThe first few Bell polynomials::\\n\\n    >>> for k in range(7):\\n    ...     nprint(taylor(lambda x: bell(k,x), 0, k))\\n    ...\\n    [1.0]\\n    [0.0, 1.0]\\n    [0.0, 1.0, 1.0]\\n    [0.0, 1.0, 3.0, 1.0]\\n    [0.0, 1.0, 7.0, 6.0, 1.0]\\n    [0.0, 1.0, 15.0, 25.0, 10.0, 1.0]\\n    [0.0, 1.0, 31.0, 90.0, 65.0, 15.0, 1.0]\\n\\nThe first few Bell numbers and complementary Bell numbers::\\n\\n    >>> [int(bell(k)) for k in range(10)]\\n    [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147]\\n    >>> [int(bell(k,-1)) for k in range(10)]\\n    [1, -1, 0, 1, 1, -2, -9, -9, 50, 267]\\n\\nLarge Bell numbers::\\n\\n    >>> mp.dps = 50\\n    >>> bell(50)\\n    185724268771078270438257767181908917499221852770.0\\n    >>> bell(50,-1)\\n    -29113173035759403920216141265491160286912.0\\n\\nSome even larger values::\\n\\n    >>> mp.dps = 25\\n    >>> bell(1000,-1)\\n    -1.237132026969293954162816e+1869\\n    >>> bell(1000)\\n    2.989901335682408421480422e+1927\\n    >>> bell(1000,2)\\n    6.591553486811969380442171e+1987\\n    >>> bell(1000,100.5)\\n    9.101014101401543575679639e+2529\\n\\nA determinant identity satisfied by Bell numbers::\\n\\n    >>> mp.dps = 15\\n    >>> N = 8\\n    >>> det([[bell(k+j) for j in range(N)] for k in range(N)])\\n    125411328000.0\\n    >>> superfac(N-1)\\n    125411328000.0\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/DobinskisFormula.html\\n\\n\\\"\\\"\\\"\\n\\npolyexp = r\\\"\\\"\\\"\\nEvaluates the polyexponential function, defined for arbitrary\\ncomplex `s`, `z` by the series\\n\\n.. math ::\\n\\n    E_s(z) = \\\\sum_{k=1}^{\\\\infty} \\\\frac{k^s}{k!} z^k.\\n\\n`E_s(z)` is constructed from the exponential function analogously\\nto how the polylogarithm is constructed from the ordinary\\nlogarithm; as a function of `s` (with `z` fixed), `E_s` is an L-series\\nIt is an entire function of both `s` and `z`.\\n\\nThe polyexponential function provides a generalization of the\\nBell polynomials `B_n(x)` (see :func:`~mpmath.bell`) to noninteger orders `n`.\\nIn terms of the Bell polynomials,\\n\\n.. math ::\\n\\n    E_s(z) = e^z B_s(z) - \\\\mathrm{sinc}(\\\\pi s).\\n\\nNote that `B_n(x)` and `e^{-x} E_n(x)` are identical if `n`\\nis a nonzero integer, but not otherwise. In particular, they differ\\nat `n = 0`.\\n\\n**Examples**\\n\\nEvaluating a series::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> nsum(lambda k: sqrt(k)/fac(k), [1,inf])\\n    2.101755547733791780315904\\n    >>> polyexp(0.5,1)\\n    2.101755547733791780315904\\n\\nEvaluation for arbitrary arguments::\\n\\n    >>> polyexp(-3-4j, 2.5+2j)\\n    (2.351660261190434618268706 + 1.202966666673054671364215j)\\n\\nEvaluation is accurate for tiny function values::\\n\\n    >>> polyexp(4, -100)\\n    3.499471750566824369520223e-36\\n\\nIf `n` is a nonpositive integer, `E_n` reduces to a special\\ninstance of the hypergeometric function `\\\\,_pF_q`::\\n\\n    >>> n = 3\\n    >>> x = pi\\n    >>> polyexp(-n,x)\\n    4.042192318847986561771779\\n    >>> x*hyper([1]*(n+1), [2]*(n+1), x)\\n    4.042192318847986561771779\\n\\n\\\"\\\"\\\"\\n\\ncyclotomic = r\\\"\\\"\\\"\\nEvaluates the cyclotomic polynomial `\\\\Phi_n(x)`, defined by\\n\\n.. math ::\\n\\n    \\\\Phi_n(x) = \\\\prod_{\\\\zeta} (x - \\\\zeta)\\n\\nwhere `\\\\zeta` ranges over all primitive `n`-th roots of unity\\n(see :func:`~mpmath.unitroots`). An equivalent representation, used\\nfor computation, is\\n\\n.. math ::\\n\\n    \\\\Phi_n(x) = \\\\prod_{d\\\\mid n}(x^d-1)^{\\\\mu(n/d)} = \\\\Phi_n(x)\\n\\nwhere `\\\\mu(m)` denotes the Moebius function. The cyclotomic\\npolynomials are integer polynomials, the first of which can be\\nwritten explicitly as\\n\\n.. math ::\\n\\n    \\\\Phi_0(x) = 1\\n\\n    \\\\Phi_1(x) = x - 1\\n\\n    \\\\Phi_2(x) = x + 1\\n\\n    \\\\Phi_3(x) = x^3 + x^2 + 1\\n\\n    \\\\Phi_4(x) = x^2 + 1\\n\\n    \\\\Phi_5(x) = x^4 + x^3 + x^2 + x + 1\\n\\n    \\\\Phi_6(x) = x^2 - x + 1\\n\\n**Examples**\\n\\nThe coefficients of low-order cyclotomic polynomials can be recovered\\nusing Taylor expansion::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 15; mp.pretty = True\\n    >>> for n in range(9):\\n    ...     p = chop(taylor(lambda x: cyclotomic(n,x), 0, 10))\\n    ...     print(\\\"%s %s\\\" % (n, nstr(p[:10+1-p[::-1].index(1)])))\\n    ...\\n    0 [1.0]\\n    1 [-1.0, 1.0]\\n    2 [1.0, 1.0]\\n    3 [1.0, 1.0, 1.0]\\n    4 [1.0, 0.0, 1.0]\\n    5 [1.0, 1.0, 1.0, 1.0, 1.0]\\n    6 [1.0, -1.0, 1.0]\\n    7 [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\\n    8 [1.0, 0.0, 0.0, 0.0, 1.0]\\n\\nThe definition as a product over primitive roots may be checked\\nby computing the product explicitly (for a real argument, this\\nmethod will generally introduce numerical noise in the imaginary\\npart)::\\n\\n    >>> mp.dps = 25\\n    >>> z = 3+4j\\n    >>> cyclotomic(10, z)\\n    (-419.0 - 360.0j)\\n    >>> fprod(z-r for r in unitroots(10, primitive=True))\\n    (-419.0 - 360.0j)\\n    >>> z = 3\\n    >>> cyclotomic(10, z)\\n    61.0\\n    >>> fprod(z-r for r in unitroots(10, primitive=True))\\n    (61.0 - 3.146045605088568607055454e-25j)\\n\\nUp to permutation, the roots of a given cyclotomic polynomial\\ncan be checked to agree with the list of primitive roots::\\n\\n    >>> p = taylor(lambda x: cyclotomic(6,x), 0, 6)[:3]\\n    >>> for r in polyroots(p[::-1]):\\n    ...     print(r)\\n    ...\\n    (0.5 - 0.8660254037844386467637232j)\\n    (0.5 + 0.8660254037844386467637232j)\\n    >>>\\n    >>> for r in unitroots(6, primitive=True):\\n    ...     print(r)\\n    ...\\n    (0.5 + 0.8660254037844386467637232j)\\n    (0.5 - 0.8660254037844386467637232j)\\n\\n\\\"\\\"\\\"\\n\\nmeijerg = r\\\"\\\"\\\"\\nEvaluates the Meijer G-function, defined as\\n\\n.. math ::\\n\\n    G^{m,n}_{p,q} \\\\left( \\\\left. \\\\begin{matrix}\\n         a_1, \\\\dots, a_n ; a_{n+1} \\\\dots a_p \\\\\\\\\\n         b_1, \\\\dots, b_m ; b_{m+1} \\\\dots b_q\\n    \\\\end{matrix}\\\\; \\\\right| \\\\; z ; r \\\\right) =\\n    \\\\frac{1}{2 \\\\pi i} \\\\int_L\\n    \\\\frac{\\\\prod_{j=1}^m \\\\Gamma(b_j+s) \\\\prod_{j=1}^n\\\\Gamma(1-a_j-s)}\\n         {\\\\prod_{j=n+1}^{p}\\\\Gamma(a_j+s) \\\\prod_{j=m+1}^q \\\\Gamma(1-b_j-s)}\\n         z^{-s/r} ds\\n\\nfor an appropriate choice of the contour `L` (see references).\\n\\nThere are `p` elements `a_j`.\\nThe argument *a_s* should be a pair of lists, the first containing the\\n`n` elements `a_1, \\\\ldots, a_n` and the second containing\\nthe `p-n` elements `a_{n+1}, \\\\ldots a_p`.\\n\\nThere are `q` elements `b_j`.\\nThe argument *b_s* should be a pair of lists, the first containing the\\n`m` elements `b_1, \\\\ldots, b_m` and the second containing\\nthe `q-m` elements `b_{m+1}, \\\\ldots b_q`.\\n\\nThe implicit tuple `(m, n, p, q)` constitutes the order or degree of the\\nMeijer G-function, and is determined by the lengths of the coefficient\\nvectors. Confusingly, the indices in this tuple appear in a different order\\nfrom the coefficients, but this notation is standard. The many examples\\ngiven below should hopefully clear up any potential confusion.\\n\\n**Algorithm**\\n\\nThe Meijer G-function is evaluated as a combination of hypergeometric series.\\nThere are two versions of the function, which can be selected with\\nthe optional *series* argument.\\n\\n*series=1* uses a sum of `m` `\\\\,_pF_{q-1}` functions of `z`\\n\\n*series=2* uses a sum of `n` `\\\\,_qF_{p-1}` functions of `1/z`\\n\\nThe default series is chosen based on the degree and `|z|` in order\\nto be consistent with Mathematica's. This definition of the Meijer G-function\\nhas a discontinuity at `|z| = 1` for some orders, which can\\nbe avoided by explicitly specifying a series.\\n\\nKeyword arguments are forwarded to :func:`~mpmath.hypercomb`.\\n\\n**Examples**\\n\\nMany standard functions are special cases of the Meijer G-function\\n(possibly rescaled and/or with branch cut corrections). We define\\nsome test parameters::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> a = mpf(0.75)\\n    >>> b = mpf(1.5)\\n    >>> z = mpf(2.25)\\n\\nThe exponential function:\\n`e^z = G^{1,0}_{0,1} \\\\left( \\\\left. \\\\begin{matrix} - \\\\\\\\ 0 \\\\end{matrix} \\\\;\\n\\\\right| \\\\; -z \\\\right)`\\n\\n    >>> meijerg([[],[]], [[0],[]], -z)\\n    9.487735836358525720550369\\n    >>> exp(z)\\n    9.487735836358525720550369\\n\\nThe natural logarithm:\\n`\\\\log(1+z) = G^{1,2}_{2,2} \\\\left( \\\\left. \\\\begin{matrix} 1, 1 \\\\\\\\ 1, 0\\n\\\\end{matrix} \\\\; \\\\right| \\\\; -z \\\\right)`\\n\\n    >>> meijerg([[1,1],[]], [[1],[0]], z)\\n    1.178654996341646117219023\\n    >>> log(1+z)\\n    1.178654996341646117219023\\n\\nA rational function:\\n`\\\\frac{z}{z+1} = G^{1,2}_{2,2} \\\\left( \\\\left. \\\\begin{matrix} 1, 1 \\\\\\\\ 1, 1\\n\\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\n    >>> meijerg([[1,1],[]], [[1],[1]], z)\\n    0.6923076923076923076923077\\n    >>> z/(z+1)\\n    0.6923076923076923076923077\\n\\nThe sine and cosine functions:\\n\\n`\\\\frac{1}{\\\\sqrt \\\\pi} \\\\sin(2 \\\\sqrt z) = G^{1,0}_{0,2} \\\\left( \\\\left. \\\\begin{matrix}\\n- \\\\\\\\ \\\\frac{1}{2}, 0 \\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\n`\\\\frac{1}{\\\\sqrt \\\\pi} \\\\cos(2 \\\\sqrt z) = G^{1,0}_{0,2} \\\\left( \\\\left. \\\\begin{matrix}\\n- \\\\\\\\ 0, \\\\frac{1}{2} \\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\n    >>> meijerg([[],[]], [[0.5],[0]], (z/2)**2)\\n    0.4389807929218676682296453\\n    >>> sin(z)/sqrt(pi)\\n    0.4389807929218676682296453\\n    >>> meijerg([[],[]], [[0],[0.5]], (z/2)**2)\\n    -0.3544090145996275423331762\\n    >>> cos(z)/sqrt(pi)\\n    -0.3544090145996275423331762\\n\\nBessel functions:\\n\\n`J_a(2 \\\\sqrt z) = G^{1,0}_{0,2} \\\\left( \\\\left.\\n\\\\begin{matrix} - \\\\\\\\ \\\\frac{a}{2}, -\\\\frac{a}{2}\\n\\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\n`Y_a(2 \\\\sqrt z) = G^{2,0}_{1,3} \\\\left( \\\\left.\\n\\\\begin{matrix} \\\\frac{-a-1}{2} \\\\\\\\ \\\\frac{a}{2}, -\\\\frac{a}{2}, \\\\frac{-a-1}{2}\\n\\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\n`(-z)^{a/2} z^{-a/2} I_a(2 \\\\sqrt z) = G^{1,0}_{0,2} \\\\left( \\\\left.\\n\\\\begin{matrix} - \\\\\\\\ \\\\frac{a}{2}, -\\\\frac{a}{2}\\n\\\\end{matrix} \\\\; \\\\right| \\\\; -z \\\\right)`\\n\\n`2 K_a(2 \\\\sqrt z) = G^{2,0}_{0,2} \\\\left( \\\\left.\\n\\\\begin{matrix} - \\\\\\\\ \\\\frac{a}{2}, -\\\\frac{a}{2}\\n\\\\end{matrix} \\\\; \\\\right| \\\\; z \\\\right)`\\n\\nAs the example with the Bessel *I* function shows, a branch\\nfactor is required for some arguments when inverting the square root.\\n\\n    >>> meijerg([[],[]], [[a/2],[-a/2]], (z/2)**2)\\n    0.5059425789597154858527264\\n    >>> besselj(a,z)\\n    0.5059425789597154858527264\\n    >>> meijerg([[],[(-a-1)/2]], [[a/2,-a/2],[(-a-1)/2]], (z/2)**2)\\n    0.1853868950066556941442559\\n    >>> bessely(a, z)\\n    0.1853868950066556941442559\\n    >>> meijerg([[],[]], [[a/2],[-a/2]], -(z/2)**2)\\n    (0.8685913322427653875717476 + 2.096964974460199200551738j)\\n    >>> (-z)**(a/2) / z**(a/2) * besseli(a, z)\\n    (0.8685913322427653875717476 + 2.096964974460199200551738j)\\n    >>> 0.5*meijerg([[],[]], [[a/2,-a/2],[]], (z/2)**2)\\n    0.09334163695597828403796071\\n    >>> besselk(a,z)\\n    0.09334163695597828403796071\\n\\nError functions:\\n\\n`\\\\sqrt{\\\\pi} z^{2(a-1)} \\\\mathrm{erfc}(z) = G^{2,0}_{1,2} \\\\left( \\\\left.\\n\\\\begin{matrix} a \\\\\\\\ a-1, a-\\\\frac{1}{2}\\n\\\\end{matrix} \\\\; \\\\right| \\\\; z, \\\\frac{1}{2} \\\\right)`\\n\\n    >>> meijerg([[],[a]], [[a-1,a-0.5],[]], z, 0.5)\\n    0.00172839843123091957468712\\n    >>> sqrt(pi) * z**(2*a-2) * erfc(z)\\n    0.00172839843123091957468712\\n\\nA Meijer G-function of higher degree, (1,1,2,3):\\n\\n    >>> meijerg([[a],[b]], [[a],[b,a-1]], z)\\n    1.55984467443050210115617\\n    >>> sin((b-a)*pi)/pi*(exp(z)-1)*z**(a-1)\\n    1.55984467443050210115617\\n\\nA Meijer G-function of still higher degree, (4,1,2,4), that can\\nbe expanded as a messy combination of exponential integrals:\\n\\n    >>> meijerg([[a],[2*b-a]], [[b,a,b-0.5,-1-a+2*b],[]], z)\\n    0.3323667133658557271898061\\n    >>> chop(4**(a-b+1)*sqrt(pi)*gamma(2*b-2*a)*z**a*\\\\\\n    ...     expint(2*b-2*a, -2*sqrt(-z))*expint(2*b-2*a, 2*sqrt(-z)))\\n    0.3323667133658557271898061\\n\\nIn the following case, different series give different values::\\n\\n    >>> chop(meijerg([[1],[0.25]],[[3],[0.5]],-2))\\n    -0.06417628097442437076207337\\n    >>> meijerg([[1],[0.25]],[[3],[0.5]],-2,series=1)\\n    0.1428699426155117511873047\\n    >>> chop(meijerg([[1],[0.25]],[[3],[0.5]],-2,series=2))\\n    -0.06417628097442437076207337\\n\\n**References**\\n\\n1. http://en.wikipedia.org/wiki/Meijer_G-function\\n\\n2. http://mathworld.wolfram.com/MeijerG-Function.html\\n\\n3. http://functions.wolfram.com/HypergeometricFunctions/MeijerG/\\n\\n4. http://functions.wolfram.com/HypergeometricFunctions/MeijerG1/\\n\\n\\\"\\\"\\\"\\n\\nclsin = r\\\"\\\"\\\"\\nComputes the Clausen sine function, defined formally by the series\\n\\n.. math ::\\n\\n    \\\\mathrm{Cl}_s(z) = \\\\sum_{k=1}^{\\\\infty} \\\\frac{\\\\sin(kz)}{k^s}.\\n\\nThe special case `\\\\mathrm{Cl}_2(z)` (i.e. ``clsin(2,z)``) is the classical\\n\\\"Clausen function\\\". More generally, the Clausen function is defined for\\ncomplex `s` and `z`, even when the series does not converge. The\\nClausen function is related to the polylogarithm (:func:`~mpmath.polylog`) as\\n\\n.. math ::\\n\\n    \\\\mathrm{Cl}_s(z) = \\\\frac{1}{2i}\\\\left(\\\\mathrm{Li}_s\\\\left(e^{iz}\\\\right) -\\n                       \\\\mathrm{Li}_s\\\\left(e^{-iz}\\\\right)\\\\right)\\n\\n    = \\\\mathrm{Im}\\\\left[\\\\mathrm{Li}_s(e^{iz})\\\\right] \\\\quad (s, z \\\\in \\\\mathbb{R}),\\n\\nand this representation can be taken to provide the analytic continuation of the\\nseries. The complementary function :func:`~mpmath.clcos` gives the corresponding\\ncosine sum.\\n\\n**Examples**\\n\\nEvaluation for arbitrarily chosen `s` and `z`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> s, z = 3, 4\\n    >>> clsin(s, z); nsum(lambda k: sin(z*k)/k**s, [1,inf])\\n    -0.6533010136329338746275795\\n    -0.6533010136329338746275795\\n\\nUsing `z + \\\\pi` instead of `z` gives an alternating series::\\n\\n    >>> clsin(s, z+pi)\\n    0.8860032351260589402871624\\n    >>> nsum(lambda k: (-1)**k*sin(z*k)/k**s, [1,inf])\\n    0.8860032351260589402871624\\n\\nWith `s = 1`, the sum can be expressed in closed form\\nusing elementary functions::\\n\\n    >>> z = 1 + sqrt(3)\\n    >>> clsin(1, z)\\n    0.2047709230104579724675985\\n    >>> chop((log(1-exp(-j*z)) - log(1-exp(j*z)))/(2*j))\\n    0.2047709230104579724675985\\n    >>> nsum(lambda k: sin(k*z)/k, [1,inf])\\n    0.2047709230104579724675985\\n\\nThe classical Clausen function `\\\\mathrm{Cl}_2(\\\\theta)` gives the\\nvalue of the integral `\\\\int_0^{\\\\theta} -\\\\ln(2\\\\sin(x/2)) dx` for\\n`0 < \\\\theta < 2 \\\\pi`::\\n\\n    >>> cl2 = lambda t: clsin(2, t)\\n    >>> cl2(3.5)\\n    -0.2465045302347694216534255\\n    >>> -quad(lambda x: ln(2*sin(0.5*x)), [0, 3.5])\\n    -0.2465045302347694216534255\\n\\nThis function is symmetric about `\\\\theta = \\\\pi` with zeros and extreme\\npoints::\\n\\n    >>> cl2(0); cl2(pi/3); chop(cl2(pi)); cl2(5*pi/3); chop(cl2(2*pi))\\n    0.0\\n    1.014941606409653625021203\\n    0.0\\n    -1.014941606409653625021203\\n    0.0\\n\\nCatalan's constant is a special value::\\n\\n    >>> cl2(pi/2)\\n    0.9159655941772190150546035\\n    >>> +catalan\\n    0.9159655941772190150546035\\n\\nThe Clausen sine function can be expressed in closed form when\\n`s` is an odd integer (becoming zero when `s` < 0)::\\n\\n    >>> z = 1 + sqrt(2)\\n    >>> clsin(1, z); (pi-z)/2\\n    0.3636895456083490948304773\\n    0.3636895456083490948304773\\n    >>> clsin(3, z); pi**2/6*z - pi*z**2/4 + z**3/12\\n    0.5661751584451144991707161\\n    0.5661751584451144991707161\\n    >>> clsin(-1, z)\\n    0.0\\n    >>> clsin(-3, z)\\n    0.0\\n\\nIt can also be expressed in closed form for even integer `s \\\\le 0`,\\nproviding a finite sum for series such as\\n`\\\\sin(z) + \\\\sin(2z) + \\\\sin(3z) + \\\\ldots`::\\n\\n    >>> z = 1 + sqrt(2)\\n    >>> clsin(0, z)\\n    0.1903105029507513881275865\\n    >>> cot(z/2)/2\\n    0.1903105029507513881275865\\n    >>> clsin(-2, z)\\n    -0.1089406163841548817581392\\n    >>> -cot(z/2)*csc(z/2)**2/4\\n    -0.1089406163841548817581392\\n\\nCall with ``pi=True`` to multiply `z` by `\\\\pi` exactly::\\n\\n    >>> clsin(3, 3*pi)\\n    -8.892316224968072424732898e-26\\n    >>> clsin(3, 3, pi=True)\\n    0.0\\n\\nEvaluation for complex `s`, `z` in a nonconvergent case::\\n\\n    >>> s, z = -1-j, 1+2j\\n    >>> clsin(s, z)\\n    (-0.593079480117379002516034 + 0.9038644233367868273362446j)\\n    >>> extraprec(20)(nsum)(lambda k: sin(k*z)/k**s, [1,inf])\\n    (-0.593079480117379002516034 + 0.9038644233367868273362446j)\\n\\n\\\"\\\"\\\"\\n\\nclcos = r\\\"\\\"\\\"\\nComputes the Clausen cosine function, defined formally by the series\\n\\n.. math ::\\n\\n    \\\\mathrm{\\\\widetilde{Cl}}_s(z) = \\\\sum_{k=1}^{\\\\infty} \\\\frac{\\\\cos(kz)}{k^s}.\\n\\nThis function is complementary to the Clausen sine function\\n:func:`~mpmath.clsin`. In terms of the polylogarithm,\\n\\n.. math ::\\n\\n    \\\\mathrm{\\\\widetilde{Cl}}_s(z) =\\n        \\\\frac{1}{2}\\\\left(\\\\mathrm{Li}_s\\\\left(e^{iz}\\\\right) +\\n        \\\\mathrm{Li}_s\\\\left(e^{-iz}\\\\right)\\\\right)\\n\\n    = \\\\mathrm{Re}\\\\left[\\\\mathrm{Li}_s(e^{iz})\\\\right] \\\\quad (s, z \\\\in \\\\mathbb{R}).\\n\\n**Examples**\\n\\nEvaluation for arbitrarily chosen `s` and `z`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> s, z = 3, 4\\n    >>> clcos(s, z); nsum(lambda k: cos(z*k)/k**s, [1,inf])\\n    -0.6518926267198991308332759\\n    -0.6518926267198991308332759\\n\\nUsing `z + \\\\pi` instead of `z` gives an alternating series::\\n\\n    >>> s, z = 3, 0.5\\n    >>> clcos(s, z+pi)\\n    -0.8155530586502260817855618\\n    >>> nsum(lambda k: (-1)**k*cos(z*k)/k**s, [1,inf])\\n    -0.8155530586502260817855618\\n\\nWith `s = 1`, the sum can be expressed in closed form\\nusing elementary functions::\\n\\n    >>> z = 1 + sqrt(3)\\n    >>> clcos(1, z)\\n    -0.6720334373369714849797918\\n    >>> chop(-0.5*(log(1-exp(j*z))+log(1-exp(-j*z))))\\n    -0.6720334373369714849797918\\n    >>> -log(abs(2*sin(0.5*z)))    # Equivalent to above when z is real\\n    -0.6720334373369714849797918\\n    >>> nsum(lambda k: cos(k*z)/k, [1,inf])\\n    -0.6720334373369714849797918\\n\\nIt can also be expressed in closed form when `s` is an even integer.\\nFor example,\\n\\n    >>> clcos(2,z)\\n    -0.7805359025135583118863007\\n    >>> pi**2/6 - pi*z/2 + z**2/4\\n    -0.7805359025135583118863007\\n\\nThe case `s = 0` gives the renormalized sum of\\n`\\\\cos(z) + \\\\cos(2z) + \\\\cos(3z) + \\\\ldots` (which happens to be the same for\\nany value of `z`)::\\n\\n    >>> clcos(0, z)\\n    -0.5\\n    >>> nsum(lambda k: cos(k*z), [1,inf])\\n    -0.5\\n\\nAlso the sums\\n\\n.. math ::\\n\\n    \\\\cos(z) + 2\\\\cos(2z) + 3\\\\cos(3z) + \\\\ldots\\n\\nand\\n\\n.. math ::\\n\\n    \\\\cos(z) + 2^n \\\\cos(2z) + 3^n \\\\cos(3z) + \\\\ldots\\n\\nfor higher integer powers `n = -s` can be done in closed form. They are zero\\nwhen `n` is positive and even (`s` negative and even)::\\n\\n    >>> clcos(-1, z); 1/(2*cos(z)-2)\\n    -0.2607829375240542480694126\\n    -0.2607829375240542480694126\\n    >>> clcos(-3, z); (2+cos(z))*csc(z/2)**4/8\\n    0.1472635054979944390848006\\n    0.1472635054979944390848006\\n    >>> clcos(-2, z); clcos(-4, z); clcos(-6, z)\\n    0.0\\n    0.0\\n    0.0\\n\\nWith `z = \\\\pi`, the series reduces to that of the Riemann zeta function\\n(more generally, if `z = p \\\\pi/q`, it is a finite sum over Hurwitz zeta\\nfunction values)::\\n\\n    >>> clcos(2.5, 0); zeta(2.5)\\n    1.34148725725091717975677\\n    1.34148725725091717975677\\n    >>> clcos(2.5, pi); -altzeta(2.5)\\n    -0.8671998890121841381913472\\n    -0.8671998890121841381913472\\n\\nCall with ``pi=True`` to multiply `z` by `\\\\pi` exactly::\\n\\n    >>> clcos(-3, 2*pi)\\n    2.997921055881167659267063e+102\\n    >>> clcos(-3, 2, pi=True)\\n    0.008333333333333333333333333\\n\\nEvaluation for complex `s`, `z` in a nonconvergent case::\\n\\n    >>> s, z = -1-j, 1+2j\\n    >>> clcos(s, z)\\n    (0.9407430121562251476136807 + 0.715826296033590204557054j)\\n    >>> extraprec(20)(nsum)(lambda k: cos(k*z)/k**s, [1,inf])\\n    (0.9407430121562251476136807 + 0.715826296033590204557054j)\\n\\n\\\"\\\"\\\"\\n\\nwhitm = r\\\"\\\"\\\"\\nEvaluates the Whittaker function `M(k,m,z)`, which gives a solution\\nto the Whittaker differential equation\\n\\n.. math ::\\n\\n    \\\\frac{d^2f}{dz^2} + \\\\left(-\\\\frac{1}{4}+\\\\frac{k}{z}+\\n      \\\\frac{(\\\\frac{1}{4}-m^2)}{z^2}\\\\right) f = 0.\\n\\nA second solution is given by :func:`~mpmath.whitw`.\\n\\nThe Whittaker functions are defined in Abramowitz & Stegun, section 13.1.\\nThey are alternate forms of the confluent hypergeometric functions\\n`\\\\,_1F_1` and `U`:\\n\\n.. math ::\\n\\n    M(k,m,z) = e^{-\\\\frac{1}{2}z} z^{\\\\frac{1}{2}+m}\\n        \\\\,_1F_1(\\\\tfrac{1}{2}+m-k, 1+2m, z)\\n\\n    W(k,m,z) = e^{-\\\\frac{1}{2}z} z^{\\\\frac{1}{2}+m}\\n        U(\\\\tfrac{1}{2}+m-k, 1+2m, z).\\n\\n**Examples**\\n\\nEvaluation for arbitrary real and complex arguments is supported::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> whitm(1, 1, 1)\\n    0.7302596799460411820509668\\n    >>> whitm(1, 1, -1)\\n    (0.0 - 1.417977827655098025684246j)\\n    >>> whitm(j, j/2, 2+3j)\\n    (3.245477713363581112736478 - 0.822879187542699127327782j)\\n    >>> whitm(2, 3, 100000)\\n    4.303985255686378497193063e+21707\\n\\nEvaluation at zero::\\n\\n    >>> whitm(1,-1,0); whitm(1,-0.5,0); whitm(1,0,0)\\n    +inf\\n    nan\\n    0.0\\n\\nWe can verify that :func:`~mpmath.whitm` numerically satisfies the\\ndifferential equation for arbitrarily chosen values::\\n\\n    >>> k = mpf(0.25)\\n    >>> m = mpf(1.5)\\n    >>> f = lambda z: whitm(k,m,z)\\n    >>> for z in [-1, 2.5, 3, 1+2j]:\\n    ...     chop(diff(f,z,2) + (-0.25 + k/z + (0.25-m**2)/z**2)*f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\nAn integral involving both :func:`~mpmath.whitm` and :func:`~mpmath.whitw`,\\nverifying evaluation along the real axis::\\n\\n    >>> quad(lambda x: exp(-x)*whitm(3,2,x)*whitw(1,-2,x), [0,inf])\\n    3.438869842576800225207341\\n    >>> 128/(21*sqrt(pi))\\n    3.438869842576800225207341\\n\\n\\\"\\\"\\\"\\n\\nwhitw = r\\\"\\\"\\\"\\nEvaluates the Whittaker function `W(k,m,z)`, which gives a second\\nsolution to the Whittaker differential equation. (See :func:`~mpmath.whitm`.)\\n\\n**Examples**\\n\\nEvaluation for arbitrary real and complex arguments is supported::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> whitw(1, 1, 1)\\n    1.19532063107581155661012\\n    >>> whitw(1, 1, -1)\\n    (-0.9424875979222187313924639 - 0.2607738054097702293308689j)\\n    >>> whitw(j, j/2, 2+3j)\\n    (0.1782899315111033879430369 - 0.01609578360403649340169406j)\\n    >>> whitw(2, 3, 100000)\\n    1.887705114889527446891274e-21705\\n    >>> whitw(-1, -1, 100)\\n    1.905250692824046162462058e-24\\n\\nEvaluation at zero::\\n\\n    >>> for m in [-1, -0.5, 0, 0.5, 1]:\\n    ...     whitw(1, m, 0)\\n    ...\\n    +inf\\n    nan\\n    0.0\\n    nan\\n    +inf\\n\\nWe can verify that :func:`~mpmath.whitw` numerically satisfies the\\ndifferential equation for arbitrarily chosen values::\\n\\n    >>> k = mpf(0.25)\\n    >>> m = mpf(1.5)\\n    >>> f = lambda z: whitw(k,m,z)\\n    >>> for z in [-1, 2.5, 3, 1+2j]:\\n    ...     chop(diff(f,z,2) + (-0.25 + k/z + (0.25-m**2)/z**2)*f(z))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n    0.0\\n\\n\\\"\\\"\\\"\\n\\nber = r\\\"\\\"\\\"\\nComputes the Kelvin function ber, which for real arguments gives the real part\\nof the Bessel J function of a rotated argument\\n\\n.. math ::\\n\\n    J_n\\\\left(x e^{3\\\\pi i/4}\\\\right) = \\\\mathrm{ber}_n(x) + i \\\\mathrm{bei}_n(x).\\n\\nThe imaginary part is given by :func:`~mpmath.bei`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/ber.py\\n.. image :: /plots/ber.png\\n\\n**Examples**\\n\\nVerifying the defining relation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> n, x = 2, 3.5\\n    >>> ber(n,x)\\n    1.442338852571888752631129\\n    >>> bei(n,x)\\n    -0.948359035324558320217678\\n    >>> besselj(n, x*root(1,8,3))\\n    (1.442338852571888752631129 - 0.948359035324558320217678j)\\n\\nThe ber and bei functions are also defined by analytic continuation\\nfor complex arguments::\\n\\n    >>> ber(1+j, 2+3j)\\n    (4.675445984756614424069563 - 15.84901771719130765656316j)\\n    >>> bei(1+j, 2+3j)\\n    (15.83886679193707699364398 + 4.684053288183046528703611j)\\n\\n\\\"\\\"\\\"\\n\\nbei = r\\\"\\\"\\\"\\nComputes the Kelvin function bei, which for real arguments gives the\\nimaginary part of the Bessel J function of a rotated argument.\\nSee :func:`~mpmath.ber`.\\n\\\"\\\"\\\"\\n\\nker = r\\\"\\\"\\\"\\nComputes the Kelvin function ker, which for real arguments gives the real part\\nof the (rescaled) Bessel K function of a rotated argument\\n\\n.. math ::\\n\\n    e^{-\\\\pi i/2} K_n\\\\left(x e^{3\\\\pi i/4}\\\\right) = \\\\mathrm{ker}_n(x) + i \\\\mathrm{kei}_n(x).\\n\\nThe imaginary part is given by :func:`~mpmath.kei`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/ker.py\\n.. image :: /plots/ker.png\\n\\n**Examples**\\n\\nVerifying the defining relation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> n, x = 2, 4.5\\n    >>> ker(n,x)\\n    0.02542895201906369640249801\\n    >>> kei(n,x)\\n    -0.02074960467222823237055351\\n    >>> exp(-n*pi*j/2) * besselk(n, x*root(1,8,1))\\n    (0.02542895201906369640249801 - 0.02074960467222823237055351j)\\n\\nThe ker and kei functions are also defined by analytic continuation\\nfor complex arguments::\\n\\n    >>> ker(1+j, 3+4j)\\n    (1.586084268115490421090533 - 2.939717517906339193598719j)\\n    >>> kei(1+j, 3+4j)\\n    (-2.940403256319453402690132 - 1.585621643835618941044855j)\\n\\n\\\"\\\"\\\"\\n\\nkei = r\\\"\\\"\\\"\\nComputes the Kelvin function kei, which for real arguments gives the\\nimaginary part of the (rescaled) Bessel K function of a rotated argument.\\nSee :func:`~mpmath.ker`.\\n\\\"\\\"\\\"\\n\\nstruveh = r\\\"\\\"\\\"\\nGives the Struve function\\n\\n.. math ::\\n\\n    \\\\,\\\\mathbf{H}_n(z) =\\n    \\\\sum_{k=0}^\\\\infty \\\\frac{(-1)^k}{\\\\Gamma(k+\\\\frac{3}{2})\\n        \\\\Gamma(k+n+\\\\frac{3}{2})} {\\\\left({\\\\frac{z}{2}}\\\\right)}^{2k+n+1}\\n\\nwhich is a solution to the Struve differential equation\\n\\n.. math ::\\n\\n    z^2 f''(z) + z f'(z) + (z^2-n^2) f(z) = \\\\frac{2 z^{n+1}}{\\\\pi (2n-1)!!}.\\n\\n**Examples**\\n\\nEvaluation for arbitrary real and complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> struveh(0, 3.5)\\n    0.3608207733778295024977797\\n    >>> struveh(-1, 10)\\n    -0.255212719726956768034732\\n    >>> struveh(1, -100.5)\\n    0.5819566816797362287502246\\n    >>> struveh(2.5, 10000000000000)\\n    3153915652525200060.308937\\n    >>> struveh(2.5, -10000000000000)\\n    (0.0 - 3153915652525200060.308937j)\\n    >>> struveh(1+j, 1000000+4000000j)\\n    (-3.066421087689197632388731e+1737173 - 1.596619701076529803290973e+1737173j)\\n\\nA Struve function of half-integer order is elementary; for example:\\n\\n    >>> z = 3\\n    >>> struveh(0.5, 3)\\n    0.9167076867564138178671595\\n    >>> sqrt(2/(pi*z))*(1-cos(z))\\n    0.9167076867564138178671595\\n\\nNumerically verifying the differential equation::\\n\\n    >>> z = mpf(4.5)\\n    >>> n = 3\\n    >>> f = lambda z: struveh(n,z)\\n    >>> lhs = z**2*diff(f,z,2) + z*diff(f,z) + (z**2-n**2)*f(z)\\n    >>> rhs = 2*z**(n+1)/fac2(2*n-1)/pi\\n    >>> lhs\\n    17.40359302709875496632744\\n    >>> rhs\\n    17.40359302709875496632744\\n\\n\\\"\\\"\\\"\\n\\nstruvel = r\\\"\\\"\\\"\\nGives the modified Struve function\\n\\n.. math ::\\n\\n    \\\\,\\\\mathbf{L}_n(z) = -i e^{-n\\\\pi i/2} \\\\mathbf{H}_n(i z)\\n\\nwhich solves to the modified Struve differential equation\\n\\n.. math ::\\n\\n    z^2 f''(z) + z f'(z) - (z^2+n^2) f(z) = \\\\frac{2 z^{n+1}}{\\\\pi (2n-1)!!}.\\n\\n**Examples**\\n\\nEvaluation for arbitrary real and complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> struvel(0, 3.5)\\n    7.180846515103737996249972\\n    >>> struvel(-1, 10)\\n    2670.994904980850550721511\\n    >>> struvel(1, -100.5)\\n    1.757089288053346261497686e+42\\n    >>> struvel(2.5, 10000000000000)\\n    4.160893281017115450519948e+4342944819025\\n    >>> struvel(2.5, -10000000000000)\\n    (0.0 - 4.160893281017115450519948e+4342944819025j)\\n    >>> struvel(1+j, 700j)\\n    (-0.1721150049480079451246076 + 0.1240770953126831093464055j)\\n    >>> struvel(1+j, 1000000+4000000j)\\n    (-2.973341637511505389128708e+434290 - 5.164633059729968297147448e+434290j)\\n\\nNumerically verifying the differential equation::\\n\\n    >>> z = mpf(3.5)\\n    >>> n = 3\\n    >>> f = lambda z: struvel(n,z)\\n    >>> lhs = z**2*diff(f,z,2) + z*diff(f,z) - (z**2+n**2)*f(z)\\n    >>> rhs = 2*z**(n+1)/fac2(2*n-1)/pi\\n    >>> lhs\\n    6.368850306060678353018165\\n    >>> rhs\\n    6.368850306060678353018165\\n\\\"\\\"\\\"\\n\\nappellf1 = r\\\"\\\"\\\"\\nGives the Appell F1 hypergeometric function of two variables,\\n\\n.. math ::\\n\\n    F_1(a,b_1,b_2,c,x,y) = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n        \\\\frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}}\\n        \\\\frac{x^m y^n}{m! n!}.\\n\\nThis series is only generally convergent when `|x| < 1` and `|y| < 1`,\\nalthough :func:`~mpmath.appellf1` can evaluate an analytic continuation\\nwith respecto to either variable, and sometimes both.\\n\\n**Examples**\\n\\nEvaluation is supported for real and complex parameters::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> appellf1(1,0,0.5,1,0.5,0.25)\\n    1.154700538379251529018298\\n    >>> appellf1(1,1+j,0.5,1,0.5,0.5j)\\n    (1.138403860350148085179415 + 1.510544741058517621110615j)\\n\\nFor some integer parameters, the F1 series reduces to a polynomial::\\n\\n    >>> appellf1(2,-4,-3,1,2,5)\\n    -816.0\\n    >>> appellf1(-5,1,2,1,4,5)\\n    -20528.0\\n\\nThe analytic continuation with respect to either `x` or `y`,\\nand sometimes with respect to both, can be evaluated::\\n\\n    >>> appellf1(2,3,4,5,100,0.5)\\n    (0.0006231042714165329279738662 + 0.0000005769149277148425774499857j)\\n    >>> appellf1('1.1', '0.3', '0.2+2j', '0.4', '0.2', 1.5+3j)\\n    (-0.1782604566893954897128702 + 0.002472407104546216117161499j)\\n    >>> appellf1(1,2,3,4,10,12)\\n    -0.07122993830066776374929313\\n\\nFor certain arguments, F1 reduces to an ordinary hypergeometric function::\\n\\n    >>> appellf1(1,2,3,5,0.5,0.25)\\n    1.547902270302684019335555\\n    >>> 4*hyp2f1(1,2,5,'1/3')/3\\n    1.547902270302684019335555\\n    >>> appellf1(1,2,3,4,0,1.5)\\n    (-1.717202506168937502740238 - 2.792526803190927323077905j)\\n    >>> hyp2f1(1,3,4,1.5)\\n    (-1.717202506168937502740238 - 2.792526803190927323077905j)\\n\\nThe F1 function satisfies a system of partial differential equations::\\n\\n    >>> a,b1,b2,c,x,y = map(mpf, [1,0.5,0.25,1.125,0.25,-0.25])\\n    >>> F = lambda x,y: appellf1(a,b1,b2,c,x,y)\\n    >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) +\\n    ...      y*(1-x)*diff(F,(x,y),(1,1)) +\\n    ...      (c-(a+b1+1)*x)*diff(F,(x,y),(1,0)) -\\n    ...      b1*y*diff(F,(x,y),(0,1)) -\\n    ...      a*b1*F(x,y))\\n    0.0\\n    >>>\\n    >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) +\\n    ...      x*(1-y)*diff(F,(x,y),(1,1)) +\\n    ...      (c-(a+b2+1)*y)*diff(F,(x,y),(0,1)) -\\n    ...      b2*x*diff(F,(x,y),(1,0)) -\\n    ...      a*b2*F(x,y))\\n    0.0\\n\\nThe Appell F1 function allows for closed-form evaluation of various\\nintegrals, such as any integral of the form\\n`\\\\int x^r (x+a)^p (x+b)^q dx`::\\n\\n    >>> def integral(a,b,p,q,r,x1,x2):\\n    ...     a,b,p,q,r,x1,x2 = map(mpmathify, [a,b,p,q,r,x1,x2])\\n    ...     f = lambda x: x**r * (x+a)**p * (x+b)**q\\n    ...     def F(x):\\n    ...         v = x**(r+1)/(r+1) * (a+x)**p * (b+x)**q\\n    ...         v *= (1+x/a)**(-p)\\n    ...         v *= (1+x/b)**(-q)\\n    ...         v *= appellf1(r+1,-p,-q,2+r,-x/a,-x/b)\\n    ...         return v\\n    ...     print(\\\"Num. quad: %s\\\" % quad(f, [x1,x2]))\\n    ...     print(\\\"Appell F1: %s\\\" % (F(x2)-F(x1)))\\n    ...\\n    >>> integral('1/5','4/3','-2','3','1/2',0,1)\\n    Num. quad: 9.073335358785776206576981\\n    Appell F1: 9.073335358785776206576981\\n    >>> integral('3/2','4/3','-2','3','1/2',0,1)\\n    Num. quad: 1.092829171999626454344678\\n    Appell F1: 1.092829171999626454344678\\n    >>> integral('3/2','4/3','-2','3','1/2',12,25)\\n    Num. quad: 1106.323225040235116498927\\n    Appell F1: 1106.323225040235116498927\\n\\nAlso incomplete elliptic integrals fall into this category [1]::\\n\\n    >>> def E(z, m):\\n    ...     if (pi/2).ae(z):\\n    ...         return ellipe(m)\\n    ...     return 2*round(re(z)/pi)*ellipe(m) + mpf(-1)**round(re(z)/pi)*\\\\\\n    ...         sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2)\\n    ...\\n    >>> z, m = 1, 0.5\\n    >>> E(z,m); quad(lambda t: sqrt(1-m*sin(t)**2), [0,pi/4,3*pi/4,z])\\n    0.9273298836244400669659042\\n    0.9273298836244400669659042\\n    >>> z, m = 3, 2\\n    >>> E(z,m); quad(lambda t: sqrt(1-m*sin(t)**2), [0,pi/4,3*pi/4,z])\\n    (1.057495752337234229715836 + 1.198140234735592207439922j)\\n    (1.057495752337234229715836 + 1.198140234735592207439922j)\\n\\n**References**\\n\\n1. [WolframFunctions]_ http://functions.wolfram.com/EllipticIntegrals/EllipticE2/26/01/\\n2. [SrivastavaKarlsson]_\\n3. [CabralRosetti]_\\n4. [Vidunas]_\\n5. [Slater]_\\n\\n\\\"\\\"\\\"\\n\\nangerj = r\\\"\\\"\\\"\\nGives the Anger function\\n\\n.. math ::\\n\\n    \\\\mathbf{J}_{\\\\nu}(z) = \\\\frac{1}{\\\\pi}\\n        \\\\int_0^{\\\\pi} \\\\cos(\\\\nu t - z \\\\sin t) dt\\n\\nwhich is an entire function of both the parameter `\\\\nu` and\\nthe argument `z`. It solves the inhomogeneous Bessel differential\\nequation\\n\\n.. math ::\\n\\n    f''(z) + \\\\frac{1}{z}f'(z) + \\\\left(1-\\\\frac{\\\\nu^2}{z^2}\\\\right) f(z)\\n        = \\\\frac{(z-\\\\nu)}{\\\\pi z^2} \\\\sin(\\\\pi \\\\nu).\\n\\n**Examples**\\n\\nEvaluation for real and complex parameter and argument::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> angerj(2,3)\\n    0.4860912605858910769078311\\n    >>> angerj(-3+4j, 2+5j)\\n    (-5033.358320403384472395612 + 585.8011892476145118551756j)\\n    >>> angerj(3.25, 1e6j)\\n    (4.630743639715893346570743e+434290 - 1.117960409887505906848456e+434291j)\\n    >>> angerj(-1.5, 1e6)\\n    0.0002795719747073879393087011\\n\\nThe Anger function coincides with the Bessel J-function when `\\\\nu`\\nis an integer::\\n\\n    >>> angerj(1,3); besselj(1,3)\\n    0.3390589585259364589255146\\n    0.3390589585259364589255146\\n    >>> angerj(1.5,3); besselj(1.5,3)\\n    0.4088969848691080859328847\\n    0.4777182150870917715515015\\n\\nVerifying the differential equation::\\n\\n    >>> v,z = mpf(2.25), 0.75\\n    >>> f = lambda z: angerj(v,z)\\n    >>> diff(f,z,2) + diff(f,z)/z + (1-(v/z)**2)*f(z)\\n    -0.6002108774380707130367995\\n    >>> (z-v)/(pi*z**2) * sinpi(v)\\n    -0.6002108774380707130367995\\n\\nVerifying the integral representation::\\n\\n    >>> angerj(v,z)\\n    0.1145380759919333180900501\\n    >>> quad(lambda t: cos(v*t-z*sin(t))/pi, [0,pi])\\n    0.1145380759919333180900501\\n\\n**References**\\n\\n1. [DLMF]_ section 11.10: Anger-Weber Functions\\n\\\"\\\"\\\"\\n\\nwebere = r\\\"\\\"\\\"\\nGives the Weber function\\n\\n.. math ::\\n\\n    \\\\mathbf{E}_{\\\\nu}(z) = \\\\frac{1}{\\\\pi}\\n        \\\\int_0^{\\\\pi} \\\\sin(\\\\nu t - z \\\\sin t) dt\\n\\nwhich is an entire function of both the parameter `\\\\nu` and\\nthe argument `z`. It solves the inhomogeneous Bessel differential\\nequation\\n\\n.. math ::\\n\\n    f''(z) + \\\\frac{1}{z}f'(z) + \\\\left(1-\\\\frac{\\\\nu^2}{z^2}\\\\right) f(z)\\n        = -\\\\frac{1}{\\\\pi z^2} (z+\\\\nu+(z-\\\\nu)\\\\cos(\\\\pi \\\\nu)).\\n\\n**Examples**\\n\\nEvaluation for real and complex parameter and argument::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> webere(2,3)\\n    -0.1057668973099018425662646\\n    >>> webere(-3+4j, 2+5j)\\n    (-585.8081418209852019290498 - 5033.314488899926921597203j)\\n    >>> webere(3.25, 1e6j)\\n    (-1.117960409887505906848456e+434291 - 4.630743639715893346570743e+434290j)\\n    >>> webere(3.25, 1e6)\\n    -0.00002812518265894315604914453\\n\\nUp to addition of a rational function of `z`, the Weber function coincides\\nwith the Struve H-function when `\\\\nu` is an integer::\\n\\n    >>> webere(1,3); 2/pi-struveh(1,3)\\n    -0.3834897968188690177372881\\n    -0.3834897968188690177372881\\n    >>> webere(5,3); 26/(35*pi)-struveh(5,3)\\n    0.2009680659308154011878075\\n    0.2009680659308154011878075\\n\\nVerifying the differential equation::\\n\\n    >>> v,z = mpf(2.25), 0.75\\n    >>> f = lambda z: webere(v,z)\\n    >>> diff(f,z,2) + diff(f,z)/z + (1-(v/z)**2)*f(z)\\n    -1.097441848875479535164627\\n    >>> -(z+v+(z-v)*cospi(v))/(pi*z**2)\\n    -1.097441848875479535164627\\n\\nVerifying the integral representation::\\n\\n    >>> webere(v,z)\\n    0.1486507351534283744485421\\n    >>> quad(lambda t: sin(v*t-z*sin(t))/pi, [0,pi])\\n    0.1486507351534283744485421\\n\\n**References**\\n\\n1. [DLMF]_ section 11.10: Anger-Weber Functions\\n\\\"\\\"\\\"\\n\\nlommels1 = r\\\"\\\"\\\"\\nGives the Lommel function `s_{\\\\mu,\\\\nu}` or `s^{(1)}_{\\\\mu,\\\\nu}`\\n\\n.. math ::\\n\\n    s_{\\\\mu,\\\\nu}(z) = \\\\frac{z^{\\\\mu+1}}{(\\\\mu-\\\\nu+1)(\\\\mu+\\\\nu+1)}\\n        \\\\,_1F_2\\\\left(1; \\\\frac{\\\\mu-\\\\nu+3}{2}, \\\\frac{\\\\mu+\\\\nu+3}{2};\\n        -\\\\frac{z^2}{4} \\\\right)\\n\\nwhich solves the inhomogeneous Bessel equation\\n\\n.. math ::\\n\\n    z^2 f''(z) + z f'(z) + (z^2-\\\\nu^2) f(z) = z^{\\\\mu+1}.\\n\\nA second solution is given by :func:`~mpmath.lommels2`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/lommels1.py\\n.. image :: /plots/lommels1.png\\n\\n**Examples**\\n\\nAn integral representation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> u,v,z = 0.25, 0.125, mpf(0.75)\\n    >>> lommels1(u,v,z)\\n    0.4276243877565150372999126\\n    >>> (bessely(v,z)*quad(lambda t: t**u*besselj(v,t), [0,z]) - \\\\\\n    ...  besselj(v,z)*quad(lambda t: t**u*bessely(v,t), [0,z]))*(pi/2)\\n    0.4276243877565150372999126\\n\\nA special value::\\n\\n    >>> lommels1(v,v,z)\\n    0.5461221367746048054932553\\n    >>> gamma(v+0.5)*sqrt(pi)*power(2,v-1)*struveh(v,z)\\n    0.5461221367746048054932553\\n\\nVerifying the differential equation::\\n\\n    >>> f = lambda z: lommels1(u,v,z)\\n    >>> z**2*diff(f,z,2) + z*diff(f,z) + (z**2-v**2)*f(z)\\n    0.6979536443265746992059141\\n    >>> z**(u+1)\\n    0.6979536443265746992059141\\n\\n**References**\\n\\n1. [GradshteynRyzhik]_\\n2. [Weisstein]_ http://mathworld.wolfram.com/LommelFunction.html\\n\\\"\\\"\\\"\\n\\nlommels2 = r\\\"\\\"\\\"\\nGives the second Lommel function `S_{\\\\mu,\\\\nu}` or `s^{(2)}_{\\\\mu,\\\\nu}`\\n\\n.. math ::\\n\\n    S_{\\\\mu,\\\\nu}(z) = s_{\\\\mu,\\\\nu}(z) + 2^{\\\\mu-1}\\n        \\\\Gamma\\\\left(\\\\tfrac{1}{2}(\\\\mu-\\\\nu+1)\\\\right)\\n        \\\\Gamma\\\\left(\\\\tfrac{1}{2}(\\\\mu+\\\\nu+1)\\\\right) \\\\times\\n\\n        \\\\left[\\\\sin(\\\\tfrac{1}{2}(\\\\mu-\\\\nu)\\\\pi) J_{\\\\nu}(z) -\\n              \\\\cos(\\\\tfrac{1}{2}(\\\\mu-\\\\nu)\\\\pi) Y_{\\\\nu}(z)\\n        \\\\right]\\n\\nwhich solves the same differential equation as\\n:func:`~mpmath.lommels1`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/lommels2.py\\n.. image :: /plots/lommels2.png\\n\\n**Examples**\\n\\nFor large `|z|`, `S_{\\\\mu,\\\\nu} \\\\sim z^{\\\\mu-1}`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> lommels2(10,2,30000)\\n    1.968299831601008419949804e+40\\n    >>> power(30000,9)\\n    1.9683e+40\\n\\nA special value::\\n\\n    >>> u,v,z = 0.5, 0.125, mpf(0.75)\\n    >>> lommels2(v,v,z)\\n    0.9589683199624672099969765\\n    >>> (struveh(v,z)-bessely(v,z))*power(2,v-1)*sqrt(pi)*gamma(v+0.5)\\n    0.9589683199624672099969765\\n\\nVerifying the differential equation::\\n\\n    >>> f = lambda z: lommels2(u,v,z)\\n    >>> z**2*diff(f,z,2) + z*diff(f,z) + (z**2-v**2)*f(z)\\n    0.6495190528383289850727924\\n    >>> z**(u+1)\\n    0.6495190528383289850727924\\n\\n**References**\\n\\n1. [GradshteynRyzhik]_\\n2. [Weisstein]_ http://mathworld.wolfram.com/LommelFunction.html\\n\\\"\\\"\\\"\\n\\nappellf2 = r\\\"\\\"\\\"\\nGives the Appell F2 hypergeometric function of two variables\\n\\n.. math ::\\n\\n    F_2(a,b_1,b_2,c_1,c_2,x,y) = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n        \\\\frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c_1)_m (c_2)_n}\\n        \\\\frac{x^m y^n}{m! n!}.\\n\\nThe series is generally absolutely convergent for `|x| + |y| < 1`.\\n\\n**Examples**\\n\\nEvaluation for real and complex arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> appellf2(1,2,3,4,5,0.25,0.125)\\n    1.257417193533135344785602\\n    >>> appellf2(1,-3,-4,2,3,2,3)\\n    -42.8\\n    >>> appellf2(0.5,0.25,-0.25,2,3,0.25j,0.25)\\n    (0.9880539519421899867041719 + 0.01497616165031102661476978j)\\n    >>> chop(appellf2(1,1+j,1-j,3j,-3j,0.25,0.25))\\n    1.201311219287411337955192\\n    >>> appellf2(1,1,1,4,6,0.125,16)\\n    (-0.09455532250274744282125152 - 0.7647282253046207836769297j)\\n\\nA transformation formula::\\n\\n    >>> a,b1,b2,c1,c2,x,y = map(mpf, [1,2,0.5,0.25,1.625,-0.125,0.125])\\n    >>> appellf2(a,b1,b2,c1,c2,x,y)\\n    0.2299211717841180783309688\\n    >>> (1-x)**(-a)*appellf2(a,c1-b1,b2,c1,c2,x/(x-1),y/(1-x))\\n    0.2299211717841180783309688\\n\\nA system of partial differential equations satisfied by F2::\\n\\n    >>> a,b1,b2,c1,c2,x,y = map(mpf, [1,0.5,0.25,1.125,1.5,0.0625,-0.0625])\\n    >>> F = lambda x,y: appellf2(a,b1,b2,c1,c2,x,y)\\n    >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) -\\n    ...      x*y*diff(F,(x,y),(1,1)) +\\n    ...      (c1-(a+b1+1)*x)*diff(F,(x,y),(1,0)) -\\n    ...      b1*y*diff(F,(x,y),(0,1)) -\\n    ...      a*b1*F(x,y))\\n    0.0\\n    >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) -\\n    ...      x*y*diff(F,(x,y),(1,1)) +\\n    ...      (c2-(a+b2+1)*y)*diff(F,(x,y),(0,1)) -\\n    ...      b2*x*diff(F,(x,y),(1,0)) -\\n    ...      a*b2*F(x,y))\\n    0.0\\n\\n**References**\\n\\nSee references for :func:`~mpmath.appellf1`.\\n\\\"\\\"\\\"\\n\\nappellf3 = r\\\"\\\"\\\"\\nGives the Appell F3 hypergeometric function of two variables\\n\\n.. math ::\\n\\n    F_3(a_1,a_2,b_1,b_2,c,x,y) = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n        \\\\frac{(a_1)_m (a_2)_n (b_1)_m (b_2)_n}{(c)_{m+n}}\\n        \\\\frac{x^m y^n}{m! n!}.\\n\\nThe series is generally absolutely convergent for `|x| < 1, |y| < 1`.\\n\\n**Examples**\\n\\nEvaluation for various parameters and variables::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> appellf3(1,2,3,4,5,0.5,0.25)\\n    2.221557778107438938158705\\n    >>> appellf3(1,2,3,4,5,6,0); hyp2f1(1,3,5,6)\\n    (-0.5189554589089861284537389 - 0.1454441043328607980769742j)\\n    (-0.5189554589089861284537389 - 0.1454441043328607980769742j)\\n    >>> appellf3(1,-2,-3,1,1,4,6)\\n    -17.4\\n    >>> appellf3(1,2,-3,1,1,4,6)\\n    (17.7876136773677356641825 + 19.54768762233649126154534j)\\n    >>> appellf3(1,2,-3,1,1,6,4)\\n    (85.02054175067929402953645 + 148.4402528821177305173599j)\\n    >>> chop(appellf3(1+j,2,1-j,2,3,0.25,0.25))\\n    1.719992169545200286696007\\n\\nMany transformations and evaluations for special combinations\\nof the parameters are possible, e.g.:\\n\\n    >>> a,b,c,x,y = map(mpf, [0.5,0.25,0.125,0.125,-0.125])\\n    >>> appellf3(a,c-a,b,c-b,c,x,y)\\n    1.093432340896087107444363\\n    >>> (1-y)**(a+b-c)*hyp2f1(a,b,c,x+y-x*y)\\n    1.093432340896087107444363\\n    >>> x**2*appellf3(1,1,1,1,3,x,-x)\\n    0.01568646277445385390945083\\n    >>> polylog(2,x**2)\\n    0.01568646277445385390945083\\n    >>> a1,a2,b1,b2,c,x = map(mpf, [0.5,0.25,0.125,0.5,4.25,0.125])\\n    >>> appellf3(a1,a2,b1,b2,c,x,1)\\n    1.03947361709111140096947\\n    >>> gammaprod([c,c-a2-b2],[c-a2,c-b2])*hyp3f2(a1,b1,c-a2-b2,c-a2,c-b2,x)\\n    1.03947361709111140096947\\n\\nThe Appell F3 function satisfies a pair of partial\\ndifferential equations::\\n\\n    >>> a1,a2,b1,b2,c,x,y = map(mpf, [0.5,0.25,0.125,0.5,0.625,0.0625,-0.0625])\\n    >>> F = lambda x,y: appellf3(a1,a2,b1,b2,c,x,y)\\n    >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) +\\n    ...      y*diff(F,(x,y),(1,1)) +\\n    ...     (c-(a1+b1+1)*x)*diff(F,(x,y),(1,0)) -\\n    ...     a1*b1*F(x,y))\\n    0.0\\n    >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) +\\n    ...     x*diff(F,(x,y),(1,1)) +\\n    ...     (c-(a2+b2+1)*y)*diff(F,(x,y),(0,1)) -\\n    ...     a2*b2*F(x,y))\\n    0.0\\n\\n**References**\\n\\nSee references for :func:`~mpmath.appellf1`.\\n\\\"\\\"\\\"\\n\\nappellf4 = r\\\"\\\"\\\"\\nGives the Appell F4 hypergeometric function of two variables\\n\\n.. math ::\\n\\n    F_4(a,b,c_1,c_2,x,y) = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n        \\\\frac{(a)_{m+n} (b)_{m+n}}{(c_1)_m (c_2)_n}\\n        \\\\frac{x^m y^n}{m! n!}.\\n\\nThe series is generally absolutely convergent for\\n`\\\\sqrt{|x|} + \\\\sqrt{|y|} < 1`.\\n\\n**Examples**\\n\\nEvaluation for various parameters and arguments::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> appellf4(1,1,2,2,0.25,0.125)\\n    1.286182069079718313546608\\n    >>> appellf4(-2,-3,4,5,4,5)\\n    34.8\\n    >>> appellf4(5,4,2,3,0.25j,-0.125j)\\n    (-0.2585967215437846642163352 + 2.436102233553582711818743j)\\n\\nReduction to `\\\\,_2F_1` in a special case::\\n\\n    >>> a,b,c,x,y = map(mpf, [0.5,0.25,0.125,0.125,-0.125])\\n    >>> appellf4(a,b,c,a+b-c+1,x*(1-y),y*(1-x))\\n    1.129143488466850868248364\\n    >>> hyp2f1(a,b,c,x)*hyp2f1(a,b,a+b-c+1,y)\\n    1.129143488466850868248364\\n\\nA system of partial differential equations satisfied by F4::\\n\\n    >>> a,b,c1,c2,x,y = map(mpf, [1,0.5,0.25,1.125,0.0625,-0.0625])\\n    >>> F = lambda x,y: appellf4(a,b,c1,c2,x,y)\\n    >>> chop(x*(1-x)*diff(F,(x,y),(2,0)) -\\n    ...      y**2*diff(F,(x,y),(0,2)) -\\n    ...      2*x*y*diff(F,(x,y),(1,1)) +\\n    ...      (c1-(a+b+1)*x)*diff(F,(x,y),(1,0)) -\\n    ...      ((a+b+1)*y)*diff(F,(x,y),(0,1)) -\\n    ...      a*b*F(x,y))\\n    0.0\\n    >>> chop(y*(1-y)*diff(F,(x,y),(0,2)) -\\n    ...      x**2*diff(F,(x,y),(2,0)) -\\n    ...      2*x*y*diff(F,(x,y),(1,1)) +\\n    ...      (c2-(a+b+1)*y)*diff(F,(x,y),(0,1)) -\\n    ...      ((a+b+1)*x)*diff(F,(x,y),(1,0)) -\\n    ...      a*b*F(x,y))\\n    0.0\\n\\n**References**\\n\\nSee references for :func:`~mpmath.appellf1`.\\n\\\"\\\"\\\"\\n\\nzeta = r\\\"\\\"\\\"\\nComputes the Riemann zeta function\\n\\n.. math ::\\n\\n  \\\\zeta(s) = 1+\\\\frac{1}{2^s}+\\\\frac{1}{3^s}+\\\\frac{1}{4^s}+\\\\ldots\\n\\nor, with `a \\\\ne 1`, the more general Hurwitz zeta function\\n\\n.. math ::\\n\\n    \\\\zeta(s,a) = \\\\sum_{k=0}^\\\\infty \\\\frac{1}{(a+k)^s}.\\n\\nOptionally, ``zeta(s, a, n)`` computes the `n`-th derivative with\\nrespect to `s`,\\n\\n.. math ::\\n\\n    \\\\zeta^{(n)}(s,a) = (-1)^n \\\\sum_{k=0}^\\\\infty \\\\frac{\\\\log^n(a+k)}{(a+k)^s}.\\n\\nAlthough these series only converge for `\\\\Re(s) > 1`, the Riemann and Hurwitz\\nzeta functions are defined through analytic continuation for arbitrary\\ncomplex `s \\\\ne 1` (`s = 1` is a pole).\\n\\nThe implementation uses three algorithms: the Borwein algorithm for\\nthe Riemann zeta function when `s` is close to the real line;\\nthe Riemann-Siegel formula for the Riemann zeta function when `s` is\\nlarge imaginary, and Euler-Maclaurin summation in all other cases.\\nThe reflection formula for `\\\\Re(s) < 0` is implemented in some cases.\\nThe algorithm can be chosen with ``method = 'borwein'``,\\n``method='riemann-siegel'`` or ``method = 'euler-maclaurin'``.\\n\\nThe parameter `a` is usually a rational number `a = p/q`, and may be specified\\nas such by passing an integer tuple `(p, q)`. Evaluation is supported for\\narbitrary complex `a`, but may be slow and/or inaccurate when `\\\\Re(s) < 0` for\\nnonrational `a` or when computing derivatives.\\n\\n**Examples**\\n\\nSome values of the Riemann zeta function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> zeta(2); pi**2 / 6\\n    1.644934066848226436472415\\n    1.644934066848226436472415\\n    >>> zeta(0)\\n    -0.5\\n    >>> zeta(-1)\\n    -0.08333333333333333333333333\\n    >>> zeta(-2)\\n    0.0\\n\\nFor large positive `s`, `\\\\zeta(s)` rapidly approaches 1::\\n\\n    >>> zeta(50)\\n    1.000000000000000888178421\\n    >>> zeta(100)\\n    1.0\\n    >>> zeta(inf)\\n    1.0\\n    >>> 1-sum((zeta(k)-1)/k for k in range(2,85)); +euler\\n    0.5772156649015328606065121\\n    0.5772156649015328606065121\\n    >>> nsum(lambda k: zeta(k)-1, [2, inf])\\n    1.0\\n\\nEvaluation is supported for complex `s` and `a`:\\n\\n    >>> zeta(-3+4j)\\n    (-0.03373057338827757067584698 + 0.2774499251557093745297677j)\\n    >>> zeta(2+3j, -1+j)\\n    (389.6841230140842816370741 + 295.2674610150305334025962j)\\n\\nThe Riemann zeta function has so-called nontrivial zeros on\\nthe critical line `s = 1/2 + it`::\\n\\n    >>> findroot(zeta, 0.5+14j); zetazero(1)\\n    (0.5 + 14.13472514173469379045725j)\\n    (0.5 + 14.13472514173469379045725j)\\n    >>> findroot(zeta, 0.5+21j); zetazero(2)\\n    (0.5 + 21.02203963877155499262848j)\\n    (0.5 + 21.02203963877155499262848j)\\n    >>> findroot(zeta, 0.5+25j); zetazero(3)\\n    (0.5 + 25.01085758014568876321379j)\\n    (0.5 + 25.01085758014568876321379j)\\n    >>> chop(zeta(zetazero(10)))\\n    0.0\\n\\nEvaluation on and near the critical line is supported for large\\nheights `t` by means of the Riemann-Siegel formula (currently\\nfor `a = 1`, `n \\\\le 4`)::\\n\\n    >>> zeta(0.5+100000j)\\n    (1.073032014857753132114076 + 5.780848544363503984261041j)\\n    >>> zeta(0.75+1000000j)\\n    (0.9535316058375145020351559 + 0.9525945894834273060175651j)\\n    >>> zeta(0.5+10000000j)\\n    (11.45804061057709254500227 - 8.643437226836021723818215j)\\n    >>> zeta(0.5+100000000j, derivative=1)\\n    (51.12433106710194942681869 + 43.87221167872304520599418j)\\n    >>> zeta(0.5+100000000j, derivative=2)\\n    (-444.2760822795430400549229 - 896.3789978119185981665403j)\\n    >>> zeta(0.5+100000000j, derivative=3)\\n    (3230.72682687670422215339 + 14374.36950073615897616781j)\\n    >>> zeta(0.5+100000000j, derivative=4)\\n    (-11967.35573095046402130602 - 218945.7817789262839266148j)\\n    >>> zeta(1+10000000j)    # off the line\\n    (2.859846483332530337008882 + 0.491808047480981808903986j)\\n    >>> zeta(1+10000000j, derivative=1)\\n    (-4.333835494679647915673205 - 0.08405337962602933636096103j)\\n    >>> zeta(1+10000000j, derivative=4)\\n    (453.2764822702057701894278 - 581.963625832768189140995j)\\n\\nFor investigation of the zeta function zeros, the Riemann-Siegel\\nZ-function is often more convenient than working with the Riemann\\nzeta function directly (see :func:`~mpmath.siegelz`).\\n\\nSome values of the Hurwitz zeta function::\\n\\n    >>> zeta(2, 3); -5./4 + pi**2/6\\n    0.3949340668482264364724152\\n    0.3949340668482264364724152\\n    >>> zeta(2, (3,4)); pi**2 - 8*catalan\\n    2.541879647671606498397663\\n    2.541879647671606498397663\\n\\nFor positive integer values of `s`, the Hurwitz zeta function is\\nequivalent to a polygamma function (except for a normalizing factor)::\\n\\n    >>> zeta(4, (1,5)); psi(3, '1/5')/6\\n    625.5408324774542966919938\\n    625.5408324774542966919938\\n\\nEvaluation of derivatives::\\n\\n    >>> zeta(0, 3+4j, 1); loggamma(3+4j) - ln(2*pi)/2\\n    (-2.675565317808456852310934 + 4.742664438034657928194889j)\\n    (-2.675565317808456852310934 + 4.742664438034657928194889j)\\n    >>> zeta(2, 1, 20)\\n    2432902008176640000.000242\\n    >>> zeta(3+4j, 5.5+2j, 4)\\n    (-0.140075548947797130681075 - 0.3109263360275413251313634j)\\n    >>> zeta(0.5+100000j, 1, 4)\\n    (-10407.16081931495861539236 + 13777.78669862804508537384j)\\n    >>> zeta(-100+0.5j, (1,3), derivative=4)\\n    (4.007180821099823942702249e+79 + 4.916117957092593868321778e+78j)\\n\\nGenerating a Taylor series at `s = 2` using derivatives::\\n\\n    >>> for k in range(11): print(\\\"%s * (s-2)^%i\\\" % (zeta(2,1,k)/fac(k), k))\\n    ...\\n    1.644934066848226436472415 * (s-2)^0\\n    -0.9375482543158437537025741 * (s-2)^1\\n    0.9946401171494505117104293 * (s-2)^2\\n    -1.000024300473840810940657 * (s-2)^3\\n    1.000061933072352565457512 * (s-2)^4\\n    -1.000006869443931806408941 * (s-2)^5\\n    1.000000173233769531820592 * (s-2)^6\\n    -0.9999999569989868493432399 * (s-2)^7\\n    0.9999999937218844508684206 * (s-2)^8\\n    -0.9999999996355013916608284 * (s-2)^9\\n    1.000000000004610645020747 * (s-2)^10\\n\\nEvaluation at zero and for negative integer `s`::\\n\\n    >>> zeta(0, 10)\\n    -9.5\\n    >>> zeta(-2, (2,3)); mpf(1)/81\\n    0.01234567901234567901234568\\n    0.01234567901234567901234568\\n    >>> zeta(-3+4j, (5,4))\\n    (0.2899236037682695182085988 + 0.06561206166091757973112783j)\\n    >>> zeta(-3.25, 1/pi)\\n    -0.0005117269627574430494396877\\n    >>> zeta(-3.5, pi, 1)\\n    11.156360390440003294709\\n    >>> zeta(-100.5, (8,3))\\n    -4.68162300487989766727122e+77\\n    >>> zeta(-10.5, (-8,3))\\n    (-0.01521913704446246609237979 + 29907.72510874248161608216j)\\n    >>> zeta(-1000.5, (-8,3))\\n    (1.031911949062334538202567e+1770 + 1.519555750556794218804724e+426j)\\n    >>> zeta(-1+j, 3+4j)\\n    (-16.32988355630802510888631 - 22.17706465801374033261383j)\\n    >>> zeta(-1+j, 3+4j, 2)\\n    (32.48985276392056641594055 - 51.11604466157397267043655j)\\n    >>> diff(lambda s: zeta(s, 3+4j), -1+j, 2)\\n    (32.48985276392056641594055 - 51.11604466157397267043655j)\\n\\n**References**\\n\\n1. http://mathworld.wolfram.com/RiemannZetaFunction.html\\n\\n2. http://mathworld.wolfram.com/HurwitzZetaFunction.html\\n\\n3. [BorweinZeta]_\\n\\n\\\"\\\"\\\"\\n\\ndirichlet = r\\\"\\\"\\\"\\nEvaluates the Dirichlet L-function\\n\\n.. math ::\\n\\n    L(s,\\\\chi) = \\\\sum_{k=1}^\\\\infty \\\\frac{\\\\chi(k)}{k^s}.\\n\\nwhere `\\\\chi` is a periodic sequence of length `q` which should be supplied\\nin the form of a list `[\\\\chi(0), \\\\chi(1), \\\\ldots, \\\\chi(q-1)]`.\\nStrictly, `\\\\chi` should be a Dirichlet character, but any periodic\\nsequence will work.\\n\\nFor example, ``dirichlet(s, [1])`` gives the ordinary\\nRiemann zeta function and ``dirichlet(s, [-1,1])`` gives\\nthe alternating zeta function (Dirichlet eta function).\\n\\nAlso the derivative with respect to `s` (currently only a first\\nderivative) can be evaluated.\\n\\n**Examples**\\n\\nThe ordinary Riemann zeta function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> dirichlet(3, [1]); zeta(3)\\n    1.202056903159594285399738\\n    1.202056903159594285399738\\n    >>> dirichlet(1, [1])\\n    +inf\\n\\nThe alternating zeta function::\\n\\n    >>> dirichlet(1, [-1,1]); ln(2)\\n    0.6931471805599453094172321\\n    0.6931471805599453094172321\\n\\nThe following defines the Dirichlet beta function\\n`\\\\beta(s) = \\\\sum_{k=0}^\\\\infty \\\\frac{(-1)^k}{(2k+1)^s}` and verifies\\nseveral values of this function::\\n\\n    >>> B = lambda s, d=0: dirichlet(s, [0, 1, 0, -1], d)\\n    >>> B(0); 1./2\\n    0.5\\n    0.5\\n    >>> B(1); pi/4\\n    0.7853981633974483096156609\\n    0.7853981633974483096156609\\n    >>> B(2); +catalan\\n    0.9159655941772190150546035\\n    0.9159655941772190150546035\\n    >>> B(2,1); diff(B, 2)\\n    0.08158073611659279510291217\\n    0.08158073611659279510291217\\n    >>> B(-1,1); 2*catalan/pi\\n    0.5831218080616375602767689\\n    0.5831218080616375602767689\\n    >>> B(0,1); log(gamma(0.25)**2/(2*pi*sqrt(2)))\\n    0.3915943927068367764719453\\n    0.3915943927068367764719454\\n    >>> B(1,1); 0.25*pi*(euler+2*ln2+3*ln(pi)-4*ln(gamma(0.25)))\\n    0.1929013167969124293631898\\n    0.1929013167969124293631898\\n\\nA custom L-series of period 3::\\n\\n    >>> dirichlet(2, [2,0,1])\\n    0.7059715047839078092146831\\n    >>> 2*nsum(lambda k: (3*k)**-2, [1,inf]) + \\\\\\n    ...   nsum(lambda k: (3*k+2)**-2, [0,inf])\\n    0.7059715047839078092146831\\n\\n\\\"\\\"\\\"\\n\\ncoulombf = r\\\"\\\"\\\"\\nCalculates the regular Coulomb wave function\\n\\n.. math ::\\n\\n    F_l(\\\\eta,z) = C_l(\\\\eta) z^{l+1} e^{-iz} \\\\,_1F_1(l+1-i\\\\eta, 2l+2, 2iz)\\n\\nwhere the normalization constant `C_l(\\\\eta)` is as calculated by\\n:func:`~mpmath.coulombc`. This function solves the differential equation\\n\\n.. math ::\\n\\n    f''(z) + \\\\left(1-\\\\frac{2\\\\eta}{z}-\\\\frac{l(l+1)}{z^2}\\\\right) f(z) = 0.\\n\\nA second linearly independent solution is given by the irregular\\nCoulomb wave function `G_l(\\\\eta,z)` (see :func:`~mpmath.coulombg`)\\nand thus the general solution is\\n`f(z) = C_1 F_l(\\\\eta,z) + C_2 G_l(\\\\eta,z)` for arbitrary\\nconstants `C_1`, `C_2`.\\nPhysically, the Coulomb wave functions give the radial solution\\nto the Schrodinger equation for a point particle in a `1/z` potential; `z` is\\nthen the radius and `l`, `\\\\eta` are quantum numbers.\\n\\nThe Coulomb wave functions with real parameters are defined\\nin Abramowitz & Stegun, section 14. However, all parameters are permitted\\nto be complex in this implementation (see references).\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/coulombf.py\\n.. image :: /plots/coulombf.png\\n.. literalinclude :: /plots/coulombf_c.py\\n.. image :: /plots/coulombf_c.png\\n\\n**Examples**\\n\\nEvaluation is supported for arbitrary magnitudes of `z`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> coulombf(2, 1.5, 3.5)\\n    0.4080998961088761187426445\\n    >>> coulombf(-2, 1.5, 3.5)\\n    0.7103040849492536747533465\\n    >>> coulombf(2, 1.5, '1e-10')\\n    4.143324917492256448770769e-33\\n    >>> coulombf(2, 1.5, 1000)\\n    0.4482623140325567050716179\\n    >>> coulombf(2, 1.5, 10**10)\\n    -0.066804196437694360046619\\n\\nVerifying the differential equation::\\n\\n    >>> l, eta, z = 2, 3, mpf(2.75)\\n    >>> A, B = 1, 2\\n    >>> f = lambda z: A*coulombf(l,eta,z) + B*coulombg(l,eta,z)\\n    >>> chop(diff(f,z,2) + (1-2*eta/z - l*(l+1)/z**2)*f(z))\\n    0.0\\n\\nA Wronskian relation satisfied by the Coulomb wave functions::\\n\\n    >>> l = 2\\n    >>> eta = 1.5\\n    >>> F = lambda z: coulombf(l,eta,z)\\n    >>> G = lambda z: coulombg(l,eta,z)\\n    >>> for z in [3.5, -1, 2+3j]:\\n    ...     chop(diff(F,z)*G(z) - F(z)*diff(G,z))\\n    ...\\n    1.0\\n    1.0\\n    1.0\\n\\nAnother Wronskian relation::\\n\\n    >>> F = coulombf\\n    >>> G = coulombg\\n    >>> for z in [3.5, -1, 2+3j]:\\n    ...     chop(F(l-1,eta,z)*G(l,eta,z)-F(l,eta,z)*G(l-1,eta,z) - l/sqrt(l**2+eta**2))\\n    ...\\n    0.0\\n    0.0\\n    0.0\\n\\nAn integral identity connecting the regular and irregular wave functions::\\n\\n    >>> l, eta, z = 4+j, 2-j, 5+2j\\n    >>> coulombf(l,eta,z) + j*coulombg(l,eta,z)\\n    (0.7997977752284033239714479 + 0.9294486669502295512503127j)\\n    >>> g = lambda t: exp(-t)*t**(l-j*eta)*(t+2*j*z)**(l+j*eta)\\n    >>> j*exp(-j*z)*z**(-l)/fac(2*l+1)/coulombc(l,eta)*quad(g, [0,inf])\\n    (0.7997977752284033239714479 + 0.9294486669502295512503127j)\\n\\nSome test case with complex parameters, taken from Michel [2]::\\n\\n    >>> mp.dps = 15\\n    >>> coulombf(1+0.1j, 50+50j, 100.156)\\n    (-1.02107292320897e+15 - 2.83675545731519e+15j)\\n    >>> coulombg(1+0.1j, 50+50j, 100.156)\\n    (2.83675545731519e+15 - 1.02107292320897e+15j)\\n    >>> coulombf(1e-5j, 10+1e-5j, 0.1+1e-6j)\\n    (4.30566371247811e-14 - 9.03347835361657e-19j)\\n    >>> coulombg(1e-5j, 10+1e-5j, 0.1+1e-6j)\\n    (778709182061.134 + 18418936.2660553j)\\n\\nThe following reproduces a table in Abramowitz & Stegun, at twice\\nthe precision::\\n\\n    >>> mp.dps = 10\\n    >>> eta = 2; z = 5\\n    >>> for l in [5, 4, 3, 2, 1, 0]:\\n    ...     print(\\\"%s %s %s\\\" % (l, coulombf(l,eta,z),\\n    ...         diff(lambda z: coulombf(l,eta,z), z)))\\n    ...\\n    5 0.09079533488 0.1042553261\\n    4 0.2148205331 0.2029591779\\n    3 0.4313159311 0.320534053\\n    2 0.7212774133 0.3952408216\\n    1 0.9935056752 0.3708676452\\n    0 1.143337392 0.2937960375\\n\\n**References**\\n\\n1. I.J. Thompson & A.R. Barnett, \\\"Coulomb and Bessel Functions of Complex\\n   Arguments and Order\\\", J. Comp. Phys., vol 64, no. 2, June 1986.\\n\\n2. N. Michel, \\\"Precise Coulomb wave functions for a wide range of\\n   complex `l`, `\\\\eta` and `z`\\\", http://arxiv.org/abs/physics/0702051v1\\n\\n\\\"\\\"\\\"\\n\\ncoulombg = r\\\"\\\"\\\"\\nCalculates the irregular Coulomb wave function\\n\\n.. math ::\\n\\n    G_l(\\\\eta,z) = \\\\frac{F_l(\\\\eta,z) \\\\cos(\\\\chi) - F_{-l-1}(\\\\eta,z)}{\\\\sin(\\\\chi)}\\n\\nwhere `\\\\chi = \\\\sigma_l - \\\\sigma_{-l-1} - (l+1/2) \\\\pi`\\nand `\\\\sigma_l(\\\\eta) = (\\\\ln \\\\Gamma(1+l+i\\\\eta)-\\\\ln \\\\Gamma(1+l-i\\\\eta))/(2i)`.\\n\\nSee :func:`~mpmath.coulombf` for additional information.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/coulombg.py\\n.. image :: /plots/coulombg.png\\n.. literalinclude :: /plots/coulombg_c.py\\n.. image :: /plots/coulombg_c.png\\n\\n**Examples**\\n\\nEvaluation is supported for arbitrary magnitudes of `z`::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> coulombg(-2, 1.5, 3.5)\\n    1.380011900612186346255524\\n    >>> coulombg(2, 1.5, 3.5)\\n    1.919153700722748795245926\\n    >>> coulombg(-2, 1.5, '1e-10')\\n    201126715824.7329115106793\\n    >>> coulombg(-2, 1.5, 1000)\\n    0.1802071520691149410425512\\n    >>> coulombg(-2, 1.5, 10**10)\\n    0.652103020061678070929794\\n\\nThe following reproduces a table in Abramowitz & Stegun,\\nat twice the precision::\\n\\n    >>> mp.dps = 10\\n    >>> eta = 2; z = 5\\n    >>> for l in [1, 2, 3, 4, 5]:\\n    ...     print(\\\"%s %s %s\\\" % (l, coulombg(l,eta,z),\\n    ...         -diff(lambda z: coulombg(l,eta,z), z)))\\n    ...\\n    1 1.08148276 0.6028279961\\n    2 1.496877075 0.5661803178\\n    3 2.048694714 0.7959909551\\n    4 3.09408669 1.731802374\\n    5 5.629840456 4.549343289\\n\\nEvaluation close to the singularity at `z = 0`::\\n\\n    >>> mp.dps = 15\\n    >>> coulombg(0,10,1)\\n    3088184933.67358\\n    >>> coulombg(0,10,'1e-10')\\n    5554866000719.8\\n    >>> coulombg(0,10,'1e-100')\\n    5554866221524.1\\n\\nEvaluation with a half-integer value for `l`::\\n\\n    >>> coulombg(1.5, 1, 10)\\n    0.852320038297334\\n\\\"\\\"\\\"\\n\\ncoulombc = r\\\"\\\"\\\"\\nGives the normalizing Gamow constant for Coulomb wave functions,\\n\\n.. math ::\\n\\n    C_l(\\\\eta) = 2^l \\\\exp\\\\left(-\\\\pi \\\\eta/2 + [\\\\ln \\\\Gamma(1+l+i\\\\eta) +\\n        \\\\ln \\\\Gamma(1+l-i\\\\eta)]/2 - \\\\ln \\\\Gamma(2l+2)\\\\right),\\n\\nwhere the log gamma function with continuous imaginary part\\naway from the negative half axis (see :func:`~mpmath.loggamma`) is implied.\\n\\nThis function is used internally for the calculation of\\nCoulomb wave functions, and automatically cached to make multiple\\nevaluations with fixed `l`, `\\\\eta` fast.\\n\\\"\\\"\\\"\\n\\nellipfun = r\\\"\\\"\\\"\\nComputes any of the Jacobi elliptic functions, defined\\nin terms of Jacobi theta functions as\\n\\n.. math ::\\n\\n    \\\\mathrm{sn}(u,m) = \\\\frac{\\\\vartheta_3(0,q)}{\\\\vartheta_2(0,q)}\\n        \\\\frac{\\\\vartheta_1(t,q)}{\\\\vartheta_4(t,q)}\\n\\n    \\\\mathrm{cn}(u,m) = \\\\frac{\\\\vartheta_4(0,q)}{\\\\vartheta_2(0,q)}\\n        \\\\frac{\\\\vartheta_2(t,q)}{\\\\vartheta_4(t,q)}\\n\\n    \\\\mathrm{dn}(u,m) = \\\\frac{\\\\vartheta_4(0,q)}{\\\\vartheta_3(0,q)}\\n        \\\\frac{\\\\vartheta_3(t,q)}{\\\\vartheta_4(t,q)},\\n\\nor more generally computes a ratio of two such functions. Here\\n`t = u/\\\\vartheta_3(0,q)^2`, and `q = q(m)` denotes the nome (see\\n:func:`~mpmath.nome`). Optionally, you can specify the nome directly\\ninstead of `m` by passing ``q=<value>``, or you can directly\\nspecify the elliptic parameter `k` with ``k=<value>``.\\n\\nThe first argument should be a two-character string specifying the\\nfunction using any combination of ``'s'``, ``'c'``, ``'d'``, ``'n'``. These\\nletters respectively denote the basic functions\\n`\\\\mathrm{sn}(u,m)`, `\\\\mathrm{cn}(u,m)`, `\\\\mathrm{dn}(u,m)`, and `1`.\\nThe identifier specifies the ratio of two such functions.\\nFor example, ``'ns'`` identifies the function\\n\\n.. math ::\\n\\n    \\\\mathrm{ns}(u,m) = \\\\frac{1}{\\\\mathrm{sn}(u,m)}\\n\\nand ``'cd'`` identifies the function\\n\\n.. math ::\\n\\n    \\\\mathrm{cd}(u,m) = \\\\frac{\\\\mathrm{cn}(u,m)}{\\\\mathrm{dn}(u,m)}.\\n\\nIf called with only the first argument, a function object\\nevaluating the chosen function for given arguments is returned.\\n\\n**Examples**\\n\\nBasic evaluation::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> ellipfun('cd', 3.5, 0.5)\\n    -0.9891101840595543931308394\\n    >>> ellipfun('cd', 3.5, q=0.25)\\n    0.07111979240214668158441418\\n\\nThe sn-function is doubly periodic in the complex plane with periods\\n`4 K(m)` and `2 i K(1-m)` (see :func:`~mpmath.ellipk`)::\\n\\n    >>> sn = ellipfun('sn')\\n    >>> sn(2, 0.25)\\n    0.9628981775982774425751399\\n    >>> sn(2+4*ellipk(0.25), 0.25)\\n    0.9628981775982774425751399\\n    >>> chop(sn(2+2*j*ellipk(1-0.25), 0.25))\\n    0.9628981775982774425751399\\n\\nThe cn-function is doubly periodic with periods `4 K(m)` and `2 K(m) + 2 i K(1-m)`::\\n\\n    >>> cn = ellipfun('cn')\\n    >>> cn(2, 0.25)\\n    -0.2698649654510865792581416\\n    >>> cn(2+4*ellipk(0.25), 0.25)\\n    -0.2698649654510865792581416\\n    >>> chop(cn(2+2*ellipk(0.25)+2*j*ellipk(1-0.25), 0.25))\\n    -0.2698649654510865792581416\\n\\nThe dn-function is doubly periodic with periods `2 K(m)` and `4 i K(1-m)`::\\n\\n    >>> dn = ellipfun('dn')\\n    >>> dn(2, 0.25)\\n    0.8764740583123262286931578\\n    >>> dn(2+2*ellipk(0.25), 0.25)\\n    0.8764740583123262286931578\\n    >>> chop(dn(2+4*j*ellipk(1-0.25), 0.25))\\n    0.8764740583123262286931578\\n\\n\\\"\\\"\\\"\\n\\n\\njtheta = r\\\"\\\"\\\"\\nComputes the Jacobi theta function `\\\\vartheta_n(z, q)`, where\\n`n = 1, 2, 3, 4`, defined by the infinite series:\\n\\n.. math ::\\n\\n  \\\\vartheta_1(z,q) = 2 q^{1/4} \\\\sum_{n=0}^{\\\\infty}\\n    (-1)^n q^{n^2+n\\\\,} \\\\sin((2n+1)z)\\n\\n  \\\\vartheta_2(z,q) = 2 q^{1/4} \\\\sum_{n=0}^{\\\\infty}\\n    q^{n^{2\\\\,} + n} \\\\cos((2n+1)z)\\n\\n  \\\\vartheta_3(z,q) = 1 + 2 \\\\sum_{n=1}^{\\\\infty}\\n    q^{n^2\\\\,} \\\\cos(2 n z)\\n\\n  \\\\vartheta_4(z,q) = 1 + 2 \\\\sum_{n=1}^{\\\\infty}\\n    (-q)^{n^2\\\\,} \\\\cos(2 n z)\\n\\nThe theta functions are functions of two variables:\\n\\n* `z` is the *argument*, an arbitrary real or complex number\\n\\n* `q` is the *nome*, which must be a real or complex number\\n  in the unit disk (i.e. `|q| < 1`). For `|q| \\\\ll 1`, the\\n  series converge very quickly, so the Jacobi theta functions\\n  can efficiently be evaluated to high precision.\\n\\nThe compact notations `\\\\vartheta_n(q) = \\\\vartheta_n(0,q)`\\nand `\\\\vartheta_n = \\\\vartheta_n(0,q)` are also frequently\\nencountered. Finally, Jacobi theta functions are frequently\\nconsidered as functions of the half-period ratio `\\\\tau`\\nand then usually denoted by `\\\\vartheta_n(z|\\\\tau)`.\\n\\nOptionally, ``jtheta(n, z, q, derivative=d)`` with `d > 0` computes\\na `d`-th derivative with respect to `z`.\\n\\n**Examples and basic properties**\\n\\nConsidered as functions of `z`, the Jacobi theta functions may be\\nviewed as generalizations of the ordinary trigonometric functions\\ncos and sin. They are periodic functions::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> jtheta(1, 0.25, '0.2')\\n    0.2945120798627300045053104\\n    >>> jtheta(1, 0.25 + 2*pi, '0.2')\\n    0.2945120798627300045053104\\n\\nIndeed, the series defining the theta functions are essentially\\ntrigonometric Fourier series. The coefficients can be retrieved\\nusing :func:`~mpmath.fourier`::\\n\\n    >>> mp.dps = 10\\n    >>> nprint(fourier(lambda x: jtheta(2, x, 0.5), [-pi, pi], 4))\\n    ([0.0, 1.68179, 0.0, 0.420448, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0])\\n\\nThe Jacobi theta functions are also so-called quasiperiodic\\nfunctions of `z` and `\\\\tau`, meaning that for fixed `\\\\tau`,\\n`\\\\vartheta_n(z, q)` and `\\\\vartheta_n(z+\\\\pi \\\\tau, q)` are the same\\nexcept for an exponential factor::\\n\\n    >>> mp.dps = 25\\n    >>> tau = 3*j/10\\n    >>> q = exp(pi*j*tau)\\n    >>> z = 10\\n    >>> jtheta(4, z+tau*pi, q)\\n    (-0.682420280786034687520568 + 1.526683999721399103332021j)\\n    >>> -exp(-2*j*z)/q * jtheta(4, z, q)\\n    (-0.682420280786034687520568 + 1.526683999721399103332021j)\\n\\nThe Jacobi theta functions satisfy a huge number of other\\nfunctional equations, such as the following identity (valid for\\nany `q`)::\\n\\n    >>> q = mpf(3)/10\\n    >>> jtheta(3,0,q)**4\\n    6.823744089352763305137427\\n    >>> jtheta(2,0,q)**4 + jtheta(4,0,q)**4\\n    6.823744089352763305137427\\n\\nExtensive listings of identities satisfied by the Jacobi theta\\nfunctions can be found in standard reference works.\\n\\nThe Jacobi theta functions are related to the gamma function\\nfor special arguments::\\n\\n    >>> jtheta(3, 0, exp(-pi))\\n    1.086434811213308014575316\\n    >>> pi**(1/4.) / gamma(3/4.)\\n    1.086434811213308014575316\\n\\n:func:`~mpmath.jtheta` supports arbitrary precision evaluation and complex\\narguments::\\n\\n    >>> mp.dps = 50\\n    >>> jtheta(4, sqrt(2), 0.5)\\n    2.0549510717571539127004115835148878097035750653737\\n    >>> mp.dps = 25\\n    >>> jtheta(4, 1+2j, (1+j)/5)\\n    (7.180331760146805926356634 - 1.634292858119162417301683j)\\n\\nEvaluation of derivatives::\\n\\n    >>> mp.dps = 25\\n    >>> jtheta(1, 7, 0.25, 1); diff(lambda z: jtheta(1, z, 0.25), 7)\\n    1.209857192844475388637236\\n    1.209857192844475388637236\\n    >>> jtheta(1, 7, 0.25, 2); diff(lambda z: jtheta(1, z, 0.25), 7, 2)\\n    -0.2598718791650217206533052\\n    -0.2598718791650217206533052\\n    >>> jtheta(2, 7, 0.25, 1); diff(lambda z: jtheta(2, z, 0.25), 7)\\n    -1.150231437070259644461474\\n    -1.150231437070259644461474\\n    >>> jtheta(2, 7, 0.25, 2); diff(lambda z: jtheta(2, z, 0.25), 7, 2)\\n    -0.6226636990043777445898114\\n    -0.6226636990043777445898114\\n    >>> jtheta(3, 7, 0.25, 1); diff(lambda z: jtheta(3, z, 0.25), 7)\\n    -0.9990312046096634316587882\\n    -0.9990312046096634316587882\\n    >>> jtheta(3, 7, 0.25, 2); diff(lambda z: jtheta(3, z, 0.25), 7, 2)\\n    -0.1530388693066334936151174\\n    -0.1530388693066334936151174\\n    >>> jtheta(4, 7, 0.25, 1); diff(lambda z: jtheta(4, z, 0.25), 7)\\n    0.9820995967262793943571139\\n    0.9820995967262793943571139\\n    >>> jtheta(4, 7, 0.25, 2); diff(lambda z: jtheta(4, z, 0.25), 7, 2)\\n    0.3936902850291437081667755\\n    0.3936902850291437081667755\\n\\n**Possible issues**\\n\\nFor `|q| \\\\ge 1` or `\\\\Im(\\\\tau) \\\\le 0`, :func:`~mpmath.jtheta` raises\\n``ValueError``. This exception is also raised for `|q|` extremely\\nclose to 1 (or equivalently `\\\\tau` very close to 0), since the\\nseries would converge too slowly::\\n\\n    >>> jtheta(1, 10, 0.99999999 * exp(0.5*j))\\n    Traceback (most recent call last):\\n      ...\\n    ValueError: abs(q) > THETA_Q_LIM = 1.000000\\n\\n\\\"\\\"\\\"\\n\\neulernum = r\\\"\\\"\\\"\\nGives the `n`-th Euler number, defined as the `n`-th derivative of\\n`\\\\mathrm{sech}(t) = 1/\\\\cosh(t)` evaluated at `t = 0`. Equivalently, the\\nEuler numbers give the coefficients of the Taylor series\\n\\n.. math ::\\n\\n    \\\\mathrm{sech}(t) = \\\\sum_{n=0}^{\\\\infty} \\\\frac{E_n}{n!} t^n.\\n\\nThe Euler numbers are closely related to Bernoulli numbers\\nand Bernoulli polynomials. They can also be evaluated in terms of\\nEuler polynomials (see :func:`~mpmath.eulerpoly`) as `E_n = 2^n E_n(1/2)`.\\n\\n**Examples**\\n\\nComputing the first few Euler numbers and verifying that they\\nagree with the Taylor series::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> [eulernum(n) for n in range(11)]\\n    [1.0, 0.0, -1.0, 0.0, 5.0, 0.0, -61.0, 0.0, 1385.0, 0.0, -50521.0]\\n    >>> chop(diffs(sech, 0, 10))\\n    [1.0, 0.0, -1.0, 0.0, 5.0, 0.0, -61.0, 0.0, 1385.0, 0.0, -50521.0]\\n\\nEuler numbers grow very rapidly. :func:`~mpmath.eulernum` efficiently\\ncomputes numerical approximations for large indices::\\n\\n    >>> eulernum(50)\\n    -6.053285248188621896314384e+54\\n    >>> eulernum(1000)\\n    3.887561841253070615257336e+2371\\n    >>> eulernum(10**20)\\n    4.346791453661149089338186e+1936958564106659551331\\n\\nComparing with an asymptotic formula for the Euler numbers::\\n\\n    >>> n = 10**5\\n    >>> (-1)**(n//2) * 8 * sqrt(n/(2*pi)) * (2*n/(pi*e))**n\\n    3.69919063017432362805663e+436961\\n    >>> eulernum(n)\\n    3.699193712834466537941283e+436961\\n\\nPass ``exact=True`` to obtain exact values of Euler numbers as integers::\\n\\n    >>> print(eulernum(50, exact=True))\\n    -6053285248188621896314383785111649088103498225146815121\\n    >>> print(eulernum(200, exact=True) % 10**10)\\n    1925859625\\n    >>> eulernum(1001, exact=True)\\n    0\\n\\\"\\\"\\\"\\n\\neulerpoly = r\\\"\\\"\\\"\\nEvaluates the Euler polynomial `E_n(z)`, defined by the generating function\\nrepresentation\\n\\n.. math ::\\n\\n    \\\\frac{2e^{zt}}{e^t+1} = \\\\sum_{n=0}^\\\\infty E_n(z) \\\\frac{t^n}{n!}.\\n\\nThe Euler polynomials may also be represented in terms of\\nBernoulli polynomials (see :func:`~mpmath.bernpoly`) using various formulas, for\\nexample\\n\\n.. math ::\\n\\n    E_n(z) = \\\\frac{2}{n+1} \\\\left(\\n        B_n(z)-2^{n+1}B_n\\\\left(\\\\frac{z}{2}\\\\right)\\n    \\\\right).\\n\\nSpecial values include the Euler numbers `E_n = 2^n E_n(1/2)` (see\\n:func:`~mpmath.eulernum`).\\n\\n**Examples**\\n\\nComputing the coefficients of the first few Euler polynomials::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> for n in range(6):\\n    ...     chop(taylor(lambda z: eulerpoly(n,z), 0, n))\\n    ...\\n    [1.0]\\n    [-0.5, 1.0]\\n    [0.0, -1.0, 1.0]\\n    [0.25, 0.0, -1.5, 1.0]\\n    [0.0, 1.0, 0.0, -2.0, 1.0]\\n    [-0.5, 0.0, 2.5, 0.0, -2.5, 1.0]\\n\\nEvaluation for arbitrary `z`::\\n\\n    >>> eulerpoly(2,3)\\n    6.0\\n    >>> eulerpoly(5,4)\\n    423.5\\n    >>> eulerpoly(35, 11111111112)\\n    3.994957561486776072734601e+351\\n    >>> eulerpoly(4, 10+20j)\\n    (-47990.0 - 235980.0j)\\n    >>> eulerpoly(2, '-3.5e-5')\\n    0.000035001225\\n    >>> eulerpoly(3, 0.5)\\n    0.0\\n    >>> eulerpoly(55, -10**80)\\n    -1.0e+4400\\n    >>> eulerpoly(5, -inf)\\n    -inf\\n    >>> eulerpoly(6, -inf)\\n    +inf\\n\\nComputing Euler numbers::\\n\\n    >>> 2**26 * eulerpoly(26,0.5)\\n    -4087072509293123892361.0\\n    >>> eulernum(26)\\n    -4087072509293123892361.0\\n\\nEvaluation is accurate for large `n` and small `z`::\\n\\n    >>> eulerpoly(100, 0.5)\\n    2.29047999988194114177943e+108\\n    >>> eulerpoly(1000, 10.5)\\n    3.628120031122876847764566e+2070\\n    >>> eulerpoly(10000, 10.5)\\n    1.149364285543783412210773e+30688\\n\\\"\\\"\\\"\\n\\nspherharm = r\\\"\\\"\\\"\\nEvaluates the spherical harmonic `Y_l^m(\\\\theta,\\\\phi)`,\\n\\n.. math ::\\n\\n    Y_l^m(\\\\theta,\\\\phi) = \\\\sqrt{\\\\frac{2l+1}{4\\\\pi}\\\\frac{(l-m)!}{(l+m)!}}\\n        P_l^m(\\\\cos \\\\theta) e^{i m \\\\phi}\\n\\nwhere `P_l^m` is an associated Legendre function (see :func:`~mpmath.legenp`).\\n\\nHere `\\\\theta \\\\in [0, \\\\pi]` denotes the polar coordinate (ranging\\nfrom the north pole to the south pole) and `\\\\phi \\\\in [0, 2 \\\\pi]` denotes the\\nazimuthal coordinate on a sphere. Care should be used since many different\\nconventions for spherical coordinate variables are used.\\n\\nUsually spherical harmonics are considered for `l \\\\in \\\\mathbb{N}`,\\n`m \\\\in \\\\mathbb{Z}`, `|m| \\\\le l`. More generally, `l,m,\\\\theta,\\\\phi`\\nare permitted to be complex numbers.\\n\\n.. note ::\\n\\n    :func:`~mpmath.spherharm` returns a complex number, even if the value is\\n    purely real.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/spherharm40.py\\n\\n`Y_{4,0}`:\\n\\n.. image :: /plots/spherharm40.png\\n\\n`Y_{4,1}`:\\n\\n.. image :: /plots/spherharm41.png\\n\\n`Y_{4,2}`:\\n\\n.. image :: /plots/spherharm42.png\\n\\n`Y_{4,3}`:\\n\\n.. image :: /plots/spherharm43.png\\n\\n`Y_{4,4}`:\\n\\n.. image :: /plots/spherharm44.png\\n\\n**Examples**\\n\\nSome low-order spherical harmonics with reference values::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> theta = pi/4\\n    >>> phi = pi/3\\n    >>> spherharm(0,0,theta,phi); 0.5*sqrt(1/pi)*expj(0)\\n    (0.2820947917738781434740397 + 0.0j)\\n    (0.2820947917738781434740397 + 0.0j)\\n    >>> spherharm(1,-1,theta,phi); 0.5*sqrt(3/(2*pi))*expj(-phi)*sin(theta)\\n    (0.1221506279757299803965962 - 0.2115710938304086076055298j)\\n    (0.1221506279757299803965962 - 0.2115710938304086076055298j)\\n    >>> spherharm(1,0,theta,phi); 0.5*sqrt(3/pi)*cos(theta)*expj(0)\\n    (0.3454941494713354792652446 + 0.0j)\\n    (0.3454941494713354792652446 + 0.0j)\\n    >>> spherharm(1,1,theta,phi); -0.5*sqrt(3/(2*pi))*expj(phi)*sin(theta)\\n    (-0.1221506279757299803965962 - 0.2115710938304086076055298j)\\n    (-0.1221506279757299803965962 - 0.2115710938304086076055298j)\\n\\nWith the normalization convention used, the spherical harmonics are orthonormal\\non the unit sphere::\\n\\n    >>> sphere = [0,pi], [0,2*pi]\\n    >>> dS = lambda t,p: fp.sin(t)   # differential element\\n    >>> Y1 = lambda t,p: fp.spherharm(l1,m1,t,p)\\n    >>> Y2 = lambda t,p: fp.conj(fp.spherharm(l2,m2,t,p))\\n    >>> l1 = l2 = 3; m1 = m2 = 2\\n    >>> fp.chop(fp.quad(lambda t,p: Y1(t,p)*Y2(t,p)*dS(t,p), *sphere))\\n    1.0000000000000007\\n    >>> m2 = 1    # m1 != m2\\n    >>> print(fp.chop(fp.quad(lambda t,p: Y1(t,p)*Y2(t,p)*dS(t,p), *sphere)))\\n    0.0\\n\\nEvaluation is accurate for large orders::\\n\\n    >>> spherharm(1000,750,0.5,0.25)\\n    (3.776445785304252879026585e-102 - 5.82441278771834794493484e-102j)\\n\\nEvaluation works with complex parameter values::\\n\\n    >>> spherharm(1+j, 2j, 2+3j, -0.5j)\\n    (64.44922331113759992154992 + 1981.693919841408089681743j)\\n\\\"\\\"\\\"\\n\\nscorergi = r\\\"\\\"\\\"\\nEvaluates the Scorer function\\n\\n.. math ::\\n\\n    \\\\operatorname{Gi}(z) =\\n    \\\\operatorname{Ai}(z) \\\\int_0^z \\\\operatorname{Bi}(t) dt +\\n    \\\\operatorname{Bi}(z) \\\\int_z^{\\\\infty} \\\\operatorname{Ai}(t) dt\\n\\nwhich gives a particular solution to the inhomogeneous Airy\\ndifferential equation `f''(z) - z f(z) = 1/\\\\pi`. Another\\nparticular solution is given by the Scorer Hi-function\\n(:func:`~mpmath.scorerhi`). The two functions are related as\\n`\\\\operatorname{Gi}(z) + \\\\operatorname{Hi}(z) = \\\\operatorname{Bi}(z)`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/gi.py\\n.. image :: /plots/gi.png\\n.. literalinclude :: /plots/gi_c.py\\n.. image :: /plots/gi_c.png\\n\\n**Examples**\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> scorergi(0); 1/(power(3,'7/6')*gamma('2/3'))\\n    0.2049755424820002450503075\\n    0.2049755424820002450503075\\n    >>> diff(scorergi, 0); 1/(power(3,'5/6')*gamma('1/3'))\\n    0.1494294524512754526382746\\n    0.1494294524512754526382746\\n    >>> scorergi(+inf); scorergi(-inf)\\n    0.0\\n    0.0\\n    >>> scorergi(1)\\n    0.2352184398104379375986902\\n    >>> scorergi(-1)\\n    -0.1166722172960152826494198\\n\\nEvaluation for large arguments::\\n\\n    >>> scorergi(10)\\n    0.03189600510067958798062034\\n    >>> scorergi(100)\\n    0.003183105228162961476590531\\n    >>> scorergi(1000000)\\n    0.0000003183098861837906721743873\\n    >>> 1/(pi*1000000)\\n    0.0000003183098861837906715377675\\n    >>> scorergi(-1000)\\n    -0.08358288400262780392338014\\n    >>> scorergi(-100000)\\n    0.02886866118619660226809581\\n    >>> scorergi(50+10j)\\n    (0.0061214102799778578790984 - 0.001224335676457532180747917j)\\n    >>> scorergi(-50-10j)\\n    (5.236047850352252236372551e+29 - 3.08254224233701381482228e+29j)\\n    >>> scorergi(100000j)\\n    (-8.806659285336231052679025e+6474077 + 8.684731303500835514850962e+6474077j)\\n\\nVerifying the connection between Gi and Hi::\\n\\n    >>> z = 0.25\\n    >>> scorergi(z) + scorerhi(z)\\n    0.7287469039362150078694543\\n    >>> airybi(z)\\n    0.7287469039362150078694543\\n\\nVerifying the differential equation::\\n\\n    >>> for z in [-3.4, 0, 2.5, 1+2j]:\\n    ...     chop(diff(scorergi,z,2) - z*scorergi(z))\\n    ...\\n    -0.3183098861837906715377675\\n    -0.3183098861837906715377675\\n    -0.3183098861837906715377675\\n    -0.3183098861837906715377675\\n\\nVerifying the integral representation::\\n\\n    >>> z = 0.5\\n    >>> scorergi(z)\\n    0.2447210432765581976910539\\n    >>> Ai,Bi = airyai,airybi\\n    >>> Bi(z)*(Ai(inf,-1)-Ai(z,-1)) + Ai(z)*(Bi(z,-1)-Bi(0,-1))\\n    0.2447210432765581976910539\\n\\n**References**\\n\\n1. [DLMF]_ section 9.12: Scorer Functions\\n\\n\\\"\\\"\\\"\\n\\nscorerhi = r\\\"\\\"\\\"\\nEvaluates the second Scorer function\\n\\n.. math ::\\n\\n    \\\\operatorname{Hi}(z) =\\n    \\\\operatorname{Bi}(z) \\\\int_{-\\\\infty}^z \\\\operatorname{Ai}(t) dt -\\n    \\\\operatorname{Ai}(z) \\\\int_{-\\\\infty}^z \\\\operatorname{Bi}(t) dt\\n\\nwhich gives a particular solution to the inhomogeneous Airy\\ndifferential equation `f''(z) - z f(z) = 1/\\\\pi`. See also\\n:func:`~mpmath.scorergi`.\\n\\n**Plots**\\n\\n.. literalinclude :: /plots/hi.py\\n.. image :: /plots/hi.png\\n.. literalinclude :: /plots/hi_c.py\\n.. image :: /plots/hi_c.png\\n\\n**Examples**\\n\\nSome values and limits::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> scorerhi(0); 2/(power(3,'7/6')*gamma('2/3'))\\n    0.4099510849640004901006149\\n    0.4099510849640004901006149\\n    >>> diff(scorerhi,0); 2/(power(3,'5/6')*gamma('1/3'))\\n    0.2988589049025509052765491\\n    0.2988589049025509052765491\\n    >>> scorerhi(+inf); scorerhi(-inf)\\n    +inf\\n    0.0\\n    >>> scorerhi(1)\\n    0.9722051551424333218376886\\n    >>> scorerhi(-1)\\n    0.2206696067929598945381098\\n\\nEvaluation for large arguments::\\n\\n    >>> scorerhi(10)\\n    455641153.5163291358991077\\n    >>> scorerhi(100)\\n    6.041223996670201399005265e+288\\n    >>> scorerhi(1000000)\\n    7.138269638197858094311122e+289529652\\n    >>> scorerhi(-10)\\n    0.0317685352825022727415011\\n    >>> scorerhi(-100)\\n    0.003183092495767499864680483\\n    >>> scorerhi(100j)\\n    (-6.366197716545672122983857e-9 + 0.003183098861710582761688475j)\\n    >>> scorerhi(50+50j)\\n    (-5.322076267321435669290334e+63 + 1.478450291165243789749427e+65j)\\n    >>> scorerhi(-1000-1000j)\\n    (0.0001591549432510502796565538 - 0.000159154943091895334973109j)\\n\\nVerifying the differential equation::\\n\\n    >>> for z in [-3.4, 0, 2, 1+2j]:\\n    ...     chop(diff(scorerhi,z,2) - z*scorerhi(z))\\n    ...\\n    0.3183098861837906715377675\\n    0.3183098861837906715377675\\n    0.3183098861837906715377675\\n    0.3183098861837906715377675\\n\\nVerifying the integral representation::\\n\\n    >>> z = 0.5\\n    >>> scorerhi(z)\\n    0.6095559998265972956089949\\n    >>> Ai,Bi = airyai,airybi\\n    >>> Bi(z)*(Ai(z,-1)-Ai(-inf,-1)) - Ai(z)*(Bi(z,-1)-Bi(-inf,-1))\\n    0.6095559998265972956089949\\n\\n\\\"\\\"\\\"\\n\\n\\nstirling1 = r\\\"\\\"\\\"\\nGives the Stirling number of the first kind `s(n,k)`, defined by\\n\\n.. math ::\\n\\n    x(x-1)(x-2)\\\\cdots(x-n+1) = \\\\sum_{k=0}^n s(n,k) x^k.\\n\\nThe value is computed using an integer recurrence. The implementation\\nis not optimized for approximating large values quickly.\\n\\n**Examples**\\n\\nComparing with the generating function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> taylor(lambda x: ff(x, 5), 0, 5)\\n    [0.0, 24.0, -50.0, 35.0, -10.0, 1.0]\\n    >>> [stirling1(5, k) for k in range(6)]\\n    [0.0, 24.0, -50.0, 35.0, -10.0, 1.0]\\n\\nRecurrence relation::\\n\\n    >>> n, k = 5, 3\\n    >>> stirling1(n+1,k) + n*stirling1(n,k) - stirling1(n,k-1)\\n    0.0\\n\\nThe matrices of Stirling numbers of first and second kind are inverses\\nof each other::\\n\\n    >>> A = matrix(5, 5); B = matrix(5, 5)\\n    >>> for n in range(5):\\n    ...     for k in range(5):\\n    ...         A[n,k] = stirling1(n,k)\\n    ...         B[n,k] = stirling2(n,k)\\n    ...\\n    >>> A * B\\n    [1.0  0.0  0.0  0.0  0.0]\\n    [0.0  1.0  0.0  0.0  0.0]\\n    [0.0  0.0  1.0  0.0  0.0]\\n    [0.0  0.0  0.0  1.0  0.0]\\n    [0.0  0.0  0.0  0.0  1.0]\\n\\nPass ``exact=True`` to obtain exact values of Stirling numbers as integers::\\n\\n    >>> stirling1(42, 5)\\n    -2.864498971768501633736628e+50\\n    >>> print(stirling1(42, 5, exact=True))\\n    -286449897176850163373662803014001546235808317440000\\n\\n\\\"\\\"\\\"\\n\\nstirling2 = r\\\"\\\"\\\"\\nGives the Stirling number of the second kind `S(n,k)`, defined by\\n\\n.. math ::\\n\\n    x^n = \\\\sum_{k=0}^n S(n,k) x(x-1)(x-2)\\\\cdots(x-k+1)\\n\\nThe value is computed using integer arithmetic to evaluate a power sum.\\nThe implementation is not optimized for approximating large values quickly.\\n\\n**Examples**\\n\\nComparing with the generating function::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> taylor(lambda x: sum(stirling2(5,k) * ff(x,k) for k in range(6)), 0, 5)\\n    [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]\\n\\nRecurrence relation::\\n\\n    >>> n, k = 5, 3\\n    >>> stirling2(n+1,k) - k*stirling2(n,k) - stirling2(n,k-1)\\n    0.0\\n\\nPass ``exact=True`` to obtain exact values of Stirling numbers as integers::\\n\\n    >>> stirling2(52, 10)\\n    2.641822121003543906807485e+45\\n    >>> print(stirling2(52, 10, exact=True))\\n    2641822121003543906807485307053638921722527655\\n\\n\\n\\\"\\\"\\\"\\n\\nsquarew = r\\\"\\\"\\\"\\nComputes the square wave function using the definition:\\n\\n.. math::\\n    x(t) = A(-1)^{\\\\left\\\\lfloor{2t / P}\\\\right\\\\rfloor}\\n\\nwhere `P` is the period of the wave and `A` is the amplitude.\\n\\n**Examples**\\n\\nSquare wave with period = 2, amplitude = 1 ::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> squarew(0,1,2)\\n    1.0\\n    >>> squarew(0.5,1,2)\\n    1.0\\n    >>> squarew(1,1,2)\\n    -1.0\\n    >>> squarew(1.5,1,2)\\n    -1.0\\n    >>> squarew(2,1,2)\\n    1.0\\n\\\"\\\"\\\"\\n\\ntrianglew = r\\\"\\\"\\\"\\nComputes the triangle wave function using the definition:\\n\\n.. math::\\n    x(t) = 2A\\\\left(\\\\frac{1}{2}-\\\\left|1-2 \\\\operatorname{frac}\\\\left(\\\\frac{x}{P}+\\\\frac{1}{4}\\\\right)\\\\right|\\\\right)\\n\\nwhere :math:`\\\\operatorname{frac}\\\\left(\\\\frac{t}{T}\\\\right) = \\\\frac{t}{T}-\\\\left\\\\lfloor{\\\\frac{t}{T}}\\\\right\\\\rfloor`\\n, `P` is the period of the wave, and `A` is the amplitude.\\n\\n**Examples**\\n\\nTriangle wave with period = 2, amplitude = 1 ::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> trianglew(0,1,2)\\n    0.0\\n    >>> trianglew(0.25,1,2)\\n    0.5\\n    >>> trianglew(0.5,1,2)\\n    1.0\\n    >>> trianglew(1,1,2)\\n    0.0\\n    >>> trianglew(1.5,1,2)\\n    -1.0\\n    >>> trianglew(2,1,2)\\n    0.0\\n\\\"\\\"\\\"\\n\\nsawtoothw = r\\\"\\\"\\\"\\nComputes the sawtooth wave function using the definition:\\n\\n.. math::\\n    x(t) = A\\\\operatorname{frac}\\\\left(\\\\frac{t}{T}\\\\right)\\n\\nwhere :math:`\\\\operatorname{frac}\\\\left(\\\\frac{t}{T}\\\\right) = \\\\frac{t}{T}-\\\\left\\\\lfloor{\\\\frac{t}{T}}\\\\right\\\\rfloor`,\\n`P` is the period of the wave, and `A` is the amplitude.\\n\\n**Examples**\\n\\nSawtooth wave with period = 2, amplitude = 1 ::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> sawtoothw(0,1,2)\\n    0.0\\n    >>> sawtoothw(0.5,1,2)\\n    0.25\\n    >>> sawtoothw(1,1,2)\\n    0.5\\n    >>> sawtoothw(1.5,1,2)\\n    0.75\\n    >>> sawtoothw(2,1,2)\\n    0.0\\n\\\"\\\"\\\"\\n\\nunit_triangle = r\\\"\\\"\\\"\\nComputes the unit triangle using the definition:\\n\\n.. math::\\n    x(t) = A(-\\\\left| t \\\\right| + 1)\\n\\nwhere `A` is the amplitude.\\n\\n**Examples**\\n\\nUnit triangle with amplitude = 1 ::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> unit_triangle(-1,1)\\n    0.0\\n    >>> unit_triangle(-0.5,1)\\n    0.5\\n    >>> unit_triangle(0,1)\\n    1.0\\n    >>> unit_triangle(0.5,1)\\n    0.5\\n    >>> unit_triangle(1,1)\\n    0.0\\n\\\"\\\"\\\"\\n\\nsigmoid = r\\\"\\\"\\\"\\nComputes the sigmoid function using the definition:\\n\\n.. math::\\n    x(t) = \\\\frac{A}{1 + e^{-t}}\\n\\nwhere `A` is the amplitude.\\n\\n**Examples**\\n\\nSigmoid function with amplitude = 1 ::\\n\\n    >>> from mpmath import *\\n    >>> mp.dps = 25; mp.pretty = True\\n    >>> sigmoid(-1,1)\\n    0.2689414213699951207488408\\n    >>> sigmoid(-0.5,1)\\n    0.3775406687981454353610994\\n    >>> sigmoid(0,1)\\n    0.5\\n    >>> sigmoid(0.5,1)\\n    0.6224593312018545646389006\\n    >>> sigmoid(1,1)\\n    0.7310585786300048792511592\\n\\n\\\"\\\"\\\"\\n\\n\\n#from ctx_base import StandardBaseContext\\n\\nfrom .libmp.backend import basestring, exec_\\n\\nfrom .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,\\n    round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,\\n    ComplexResult, to_pickable, from_pickable, normalize,\\n    from_int, from_float, from_npfloat, from_Decimal, from_str, to_int, to_float, to_str,\\n    from_rational, from_man_exp,\\n    fone, fzero, finf, fninf, fnan,\\n    mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,\\n    mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,\\n    mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,\\n    mpf_hash, mpf_rand,\\n    mpf_sum,\\n    bitcount, to_fixed,\\n    mpc_to_str,\\n    mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,\\n    mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,\\n    mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,\\n    mpc_mpf_div,\\n    mpf_pow,\\n    mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,\\n    mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,\\n    mpf_glaisher, mpf_twinprime, mpf_mertens,\\n    int_types)\\n\\nfrom . import rational\\nfrom . import function_docs\\n\\nnew = object.__new__\\n\\nclass mpnumeric(object):\\n    \\\"\\\"\\\"Base class for mpf and mpc.\\\"\\\"\\\"\\n    __slots__ = []\\n    def __new__(cls, val):\\n        raise NotImplementedError\\n\\nclass _mpf(mpnumeric):\\n    \\\"\\\"\\\"\\n    An mpf instance holds a real-valued floating-point number. mpf:s\\n    work analogously to Python floats, but support arbitrary-precision\\n    arithmetic.\\n    \\\"\\\"\\\"\\n    __slots__ = ['_mpf_']\\n\\n    def __new__(cls, val=fzero, **kwargs):\\n        \\\"\\\"\\\"A new mpf can be created from a Python float, an int, a\\n        or a decimal string representing a number in floating-point\\n        format.\\\"\\\"\\\"\\n        prec, rounding = cls.context._prec_rounding\\n        if kwargs:\\n            prec = kwargs.get('prec', prec)\\n            if 'dps' in kwargs:\\n                prec = dps_to_prec(kwargs['dps'])\\n            rounding = kwargs.get('rounding', rounding)\\n        if type(val) is cls:\\n            sign, man, exp, bc = val._mpf_\\n            if (not man) and exp:\\n                return val\\n            v = new(cls)\\n            v._mpf_ = normalize(sign, man, exp, bc, prec, rounding)\\n            return v\\n        elif type(val) is tuple:\\n            if len(val) == 2:\\n                v = new(cls)\\n                v._mpf_ = from_man_exp(val[0], val[1], prec, rounding)\\n                return v\\n            if len(val) == 4:\\n                if val not in (finf, fninf, fnan):\\n                    sign, man, exp, bc = val\\n                    val = normalize(sign, MPZ(man), exp, bc, prec, rounding)\\n                v = new(cls)\\n                v._mpf_ = val\\n                return v\\n            raise ValueError\\n        else:\\n            v = new(cls)\\n            v._mpf_ = mpf_pos(cls.mpf_convert_arg(val, prec, rounding), prec, rounding)\\n            return v\\n\\n    @classmethod\\n    def mpf_convert_arg(cls, x, prec, rounding):\\n        if isinstance(x, int_types): return from_int(x)\\n        if isinstance(x, float): return from_float(x)\\n        if isinstance(x, basestring): return from_str(x, prec, rounding)\\n        if isinstance(x, cls.context.constant): return x.func(prec, rounding)\\n        if hasattr(x, '_mpf_'): return x._mpf_\\n        if hasattr(x, '_mpmath_'):\\n            t = cls.context.convert(x._mpmath_(prec, rounding))\\n            if hasattr(t, '_mpf_'):\\n                return t._mpf_\\n        if hasattr(x, '_mpi_'):\\n            a, b = x._mpi_\\n            if a == b:\\n                return a\\n            raise ValueError(\\\"can only create mpf from zero-width interval\\\")\\n        raise TypeError(\\\"cannot create mpf from \\\" + repr(x))\\n\\n    @classmethod\\n    def mpf_convert_rhs(cls, x):\\n        if isinstance(x, int_types): return from_int(x)\\n        if isinstance(x, float): return from_float(x)\\n        if isinstance(x, complex_types): return cls.context.mpc(x)\\n        if isinstance(x, rational.mpq):\\n            p, q = x._mpq_\\n            return from_rational(p, q, cls.context.prec)\\n        if hasattr(x, '_mpf_'): return x._mpf_\\n        if hasattr(x, '_mpmath_'):\\n            t = cls.context.convert(x._mpmath_(*cls.context._prec_rounding))\\n            if hasattr(t, '_mpf_'):\\n                return t._mpf_\\n            return t\\n        return NotImplemented\\n\\n    @classmethod\\n    def mpf_convert_lhs(cls, x):\\n        x = cls.mpf_convert_rhs(x)\\n        if type(x) is tuple:\\n            return cls.context.make_mpf(x)\\n        return x\\n\\n    man_exp = property(lambda self: self._mpf_[1:3])\\n    man = property(lambda self: self._mpf_[1])\\n    exp = property(lambda self: self._mpf_[2])\\n    bc = property(lambda self: self._mpf_[3])\\n\\n    real = property(lambda self: self)\\n    imag = property(lambda self: self.context.zero)\\n\\n    conjugate = lambda self: self\\n\\n    def __getstate__(self): return to_pickable(self._mpf_)\\n    def __setstate__(self, val): self._mpf_ = from_pickable(val)\\n\\n    def __repr__(s):\\n        if s.context.pretty:\\n            return str(s)\\n        return \\\"mpf('%s')\\\" % to_str(s._mpf_, s.context._repr_digits)\\n\\n    def __str__(s): return to_str(s._mpf_, s.context._str_digits)\\n    def __hash__(s): return mpf_hash(s._mpf_)\\n    def __int__(s): return int(to_int(s._mpf_))\\n    def __long__(s): return long(to_int(s._mpf_))\\n    def __float__(s): return to_float(s._mpf_, rnd=s.context._prec_rounding[1])\\n    def __complex__(s): return complex(float(s))\\n    def __nonzero__(s): return s._mpf_ != fzero\\n\\n    __bool__ = __nonzero__\\n\\n    def __abs__(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpf_ = mpf_abs(s._mpf_, prec, rounding)\\n        return v\\n\\n    def __pos__(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpf_ = mpf_pos(s._mpf_, prec, rounding)\\n        return v\\n\\n    def __neg__(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpf_ = mpf_neg(s._mpf_, prec, rounding)\\n        return v\\n\\n    def _cmp(s, t, func):\\n        if hasattr(t, '_mpf_'):\\n            t = t._mpf_\\n        else:\\n            t = s.mpf_convert_rhs(t)\\n            if t is NotImplemented:\\n                return t\\n        return func(s._mpf_, t)\\n\\n    def __cmp__(s, t): return s._cmp(t, mpf_cmp)\\n    def __lt__(s, t): return s._cmp(t, mpf_lt)\\n    def __gt__(s, t): return s._cmp(t, mpf_gt)\\n    def __le__(s, t): return s._cmp(t, mpf_le)\\n    def __ge__(s, t): return s._cmp(t, mpf_ge)\\n\\n    def __ne__(s, t):\\n        v = s.__eq__(t)\\n        if v is NotImplemented:\\n            return v\\n        return not v\\n\\n    def __rsub__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if type(t) in int_types:\\n            v = new(cls)\\n            v._mpf_ = mpf_sub(from_int(t), s._mpf_, prec, rounding)\\n            return v\\n        t = s.mpf_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t - s\\n\\n    def __rdiv__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if isinstance(t, int_types):\\n            v = new(cls)\\n            v._mpf_ = mpf_rdiv_int(t, s._mpf_, prec, rounding)\\n            return v\\n        t = s.mpf_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t / s\\n\\n    def __rpow__(s, t):\\n        t = s.mpf_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t ** s\\n\\n    def __rmod__(s, t):\\n        t = s.mpf_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t % s\\n\\n    def sqrt(s):\\n        return s.context.sqrt(s)\\n\\n    def ae(s, t, rel_eps=None, abs_eps=None):\\n        return s.context.almosteq(s, t, rel_eps, abs_eps)\\n\\n    def to_fixed(self, prec):\\n        return to_fixed(self._mpf_, prec)\\n\\n    def __round__(self, *args):\\n        return round(float(self), *args)\\n\\nmpf_binary_op = \\\"\\\"\\\"\\ndef %NAME%(self, other):\\n    mpf, new, (prec, rounding) = self._ctxdata\\n    sval = self._mpf_\\n    if hasattr(other, '_mpf_'):\\n        tval = other._mpf_\\n        %WITH_MPF%\\n    ttype = type(other)\\n    if ttype in int_types:\\n        %WITH_INT%\\n    elif ttype is float:\\n        tval = from_float(other)\\n        %WITH_MPF%\\n    elif hasattr(other, '_mpc_'):\\n        tval = other._mpc_\\n        mpc = type(other)\\n        %WITH_MPC%\\n    elif ttype is complex:\\n        tval = from_float(other.real), from_float(other.imag)\\n        mpc = self.context.mpc\\n        %WITH_MPC%\\n    if isinstance(other, mpnumeric):\\n        return NotImplemented\\n    try:\\n        other = mpf.context.convert(other, strings=False)\\n    except TypeError:\\n        return NotImplemented\\n    return self.%NAME%(other)\\n\\\"\\\"\\\"\\n\\nreturn_mpf = \\\"; obj = new(mpf); obj._mpf_ = val; return obj\\\"\\nreturn_mpc = \\\"; obj = new(mpc); obj._mpc_ = val; return obj\\\"\\n\\nmpf_pow_same = \\\"\\\"\\\"\\n        try:\\n            val = mpf_pow(sval, tval, prec, rounding) %s\\n        except ComplexResult:\\n            if mpf.context.trap_complex:\\n                raise\\n            mpc = mpf.context.mpc\\n            val = mpc_pow((sval, fzero), (tval, fzero), prec, rounding) %s\\n\\\"\\\"\\\" % (return_mpf, return_mpc)\\n\\ndef binary_op(name, with_mpf='', with_int='', with_mpc=''):\\n    code = mpf_binary_op\\n    code = code.replace(\\\"%WITH_INT%\\\", with_int)\\n    code = code.replace(\\\"%WITH_MPC%\\\", with_mpc)\\n    code = code.replace(\\\"%WITH_MPF%\\\", with_mpf)\\n    code = code.replace(\\\"%NAME%\\\", name)\\n    np = {}\\n    exec_(code, globals(), np)\\n    return np[name]\\n\\n_mpf.__eq__ = binary_op('__eq__',\\n    'return mpf_eq(sval, tval)',\\n    'return mpf_eq(sval, from_int(other))',\\n    'return (tval[1] == fzero) and mpf_eq(tval[0], sval)')\\n\\n_mpf.__add__ = binary_op('__add__',\\n    'val = mpf_add(sval, tval, prec, rounding)' + return_mpf,\\n    'val = mpf_add(sval, from_int(other), prec, rounding)' + return_mpf,\\n    'val = mpc_add_mpf(tval, sval, prec, rounding)' + return_mpc)\\n\\n_mpf.__sub__ = binary_op('__sub__',\\n    'val = mpf_sub(sval, tval, prec, rounding)' + return_mpf,\\n    'val = mpf_sub(sval, from_int(other), prec, rounding)' + return_mpf,\\n    'val = mpc_sub((sval, fzero), tval, prec, rounding)' + return_mpc)\\n\\n_mpf.__mul__ = binary_op('__mul__',\\n    'val = mpf_mul(sval, tval, prec, rounding)' + return_mpf,\\n    'val = mpf_mul_int(sval, other, prec, rounding)' + return_mpf,\\n    'val = mpc_mul_mpf(tval, sval, prec, rounding)' + return_mpc)\\n\\n_mpf.__div__ = binary_op('__div__',\\n    'val = mpf_div(sval, tval, prec, rounding)' + return_mpf,\\n    'val = mpf_div(sval, from_int(other), prec, rounding)' + return_mpf,\\n    'val = mpc_mpf_div(sval, tval, prec, rounding)' + return_mpc)\\n\\n_mpf.__mod__ = binary_op('__mod__',\\n    'val = mpf_mod(sval, tval, prec, rounding)' + return_mpf,\\n    'val = mpf_mod(sval, from_int(other), prec, rounding)' + return_mpf,\\n    'raise NotImplementedError(\\\"complex modulo\\\")')\\n\\n_mpf.__pow__ = binary_op('__pow__',\\n    mpf_pow_same,\\n    'val = mpf_pow_int(sval, other, prec, rounding)' + return_mpf,\\n    'val = mpc_pow((sval, fzero), tval, prec, rounding)' + return_mpc)\\n\\n_mpf.__radd__ = _mpf.__add__\\n_mpf.__rmul__ = _mpf.__mul__\\n_mpf.__truediv__ = _mpf.__div__\\n_mpf.__rtruediv__ = _mpf.__rdiv__\\n\\n\\nclass _constant(_mpf):\\n    \\\"\\\"\\\"Represents a mathematical constant with dynamic precision.\\n    When printed or used in an arithmetic operation, a constant\\n    is converted to a regular mpf at the working precision. A\\n    regular mpf can also be obtained using the operation +x.\\\"\\\"\\\"\\n\\n    def __new__(cls, func, name, docname=''):\\n        a = object.__new__(cls)\\n        a.name = name\\n        a.func = func\\n        a.__doc__ = getattr(function_docs, docname, '')\\n        return a\\n\\n    def __call__(self, prec=None, dps=None, rounding=None):\\n        prec2, rounding2 = self.context._prec_rounding\\n        if not prec: prec = prec2\\n        if not rounding: rounding = rounding2\\n        if dps: prec = dps_to_prec(dps)\\n        return self.context.make_mpf(self.func(prec, rounding))\\n\\n    @property\\n    def _mpf_(self):\\n        prec, rounding = self.context._prec_rounding\\n        return self.func(prec, rounding)\\n\\n    def __repr__(self):\\n        return \\\"<%s: %s~>\\\" % (self.name, self.context.nstr(self(dps=15)))\\n\\n\\nclass _mpc(mpnumeric):\\n    \\\"\\\"\\\"\\n    An mpc represents a complex number using a pair of mpf:s (one\\n    for the real part and another for the imaginary part.) The mpc\\n    class behaves fairly similarly to Python's complex type.\\n    \\\"\\\"\\\"\\n\\n    __slots__ = ['_mpc_']\\n\\n    def __new__(cls, real=0, imag=0):\\n        s = object.__new__(cls)\\n        if isinstance(real, complex_types):\\n            real, imag = real.real, real.imag\\n        elif hasattr(real, '_mpc_'):\\n            s._mpc_ = real._mpc_\\n            return s\\n        real = cls.context.mpf(real)\\n        imag = cls.context.mpf(imag)\\n        s._mpc_ = (real._mpf_, imag._mpf_)\\n        return s\\n\\n    real = property(lambda self: self.context.make_mpf(self._mpc_[0]))\\n    imag = property(lambda self: self.context.make_mpf(self._mpc_[1]))\\n\\n    def __getstate__(self):\\n        return to_pickable(self._mpc_[0]), to_pickable(self._mpc_[1])\\n\\n    def __setstate__(self, val):\\n        self._mpc_ = from_pickable(val[0]), from_pickable(val[1])\\n\\n    def __repr__(s):\\n        if s.context.pretty:\\n            return str(s)\\n        r = repr(s.real)[4:-1]\\n        i = repr(s.imag)[4:-1]\\n        return \\\"%s(real=%s, imag=%s)\\\" % (type(s).__name__, r, i)\\n\\n    def __str__(s):\\n        return \\\"(%s)\\\" % mpc_to_str(s._mpc_, s.context._str_digits)\\n\\n    def __complex__(s):\\n        return mpc_to_complex(s._mpc_, rnd=s.context._prec_rounding[1])\\n\\n    def __pos__(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpc_ = mpc_pos(s._mpc_, prec, rounding)\\n        return v\\n\\n    def __abs__(s):\\n        prec, rounding = s.context._prec_rounding\\n        v = new(s.context.mpf)\\n        v._mpf_ = mpc_abs(s._mpc_, prec, rounding)\\n        return v\\n\\n    def __neg__(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpc_ = mpc_neg(s._mpc_, prec, rounding)\\n        return v\\n\\n    def conjugate(s):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        v = new(cls)\\n        v._mpc_ = mpc_conjugate(s._mpc_, prec, rounding)\\n        return v\\n\\n    def __nonzero__(s):\\n        return mpc_is_nonzero(s._mpc_)\\n\\n    __bool__ = __nonzero__\\n\\n    def __hash__(s):\\n        return mpc_hash(s._mpc_)\\n\\n    @classmethod\\n    def mpc_convert_lhs(cls, x):\\n        try:\\n            y = cls.context.convert(x)\\n            return y\\n        except TypeError:\\n            return NotImplemented\\n\\n    def __eq__(s, t):\\n        if not hasattr(t, '_mpc_'):\\n            if isinstance(t, str):\\n                return False\\n            t = s.mpc_convert_lhs(t)\\n            if t is NotImplemented:\\n                return t\\n        return s.real == t.real and s.imag == t.imag\\n\\n    def __ne__(s, t):\\n        b = s.__eq__(t)\\n        if b is NotImplemented:\\n            return b\\n        return not b\\n\\n    def _compare(*args):\\n        raise TypeError(\\\"no ordering relation is defined for complex numbers\\\")\\n\\n    __gt__ = _compare\\n    __le__ = _compare\\n    __gt__ = _compare\\n    __ge__ = _compare\\n\\n    def __add__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if not hasattr(t, '_mpc_'):\\n            t = s.mpc_convert_lhs(t)\\n            if t is NotImplemented:\\n                return t\\n            if hasattr(t, '_mpf_'):\\n                v = new(cls)\\n                v._mpc_ = mpc_add_mpf(s._mpc_, t._mpf_, prec, rounding)\\n                return v\\n        v = new(cls)\\n        v._mpc_ = mpc_add(s._mpc_, t._mpc_, prec, rounding)\\n        return v\\n\\n    def __sub__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if not hasattr(t, '_mpc_'):\\n            t = s.mpc_convert_lhs(t)\\n            if t is NotImplemented:\\n                return t\\n            if hasattr(t, '_mpf_'):\\n                v = new(cls)\\n                v._mpc_ = mpc_sub_mpf(s._mpc_, t._mpf_, prec, rounding)\\n                return v\\n        v = new(cls)\\n        v._mpc_ = mpc_sub(s._mpc_, t._mpc_, prec, rounding)\\n        return v\\n\\n    def __mul__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if not hasattr(t, '_mpc_'):\\n            if isinstance(t, int_types):\\n                v = new(cls)\\n                v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding)\\n                return v\\n            t = s.mpc_convert_lhs(t)\\n            if t is NotImplemented:\\n                return t\\n            if hasattr(t, '_mpf_'):\\n                v = new(cls)\\n                v._mpc_ = mpc_mul_mpf(s._mpc_, t._mpf_, prec, rounding)\\n                return v\\n            t = s.mpc_convert_lhs(t)\\n        v = new(cls)\\n        v._mpc_ = mpc_mul(s._mpc_, t._mpc_, prec, rounding)\\n        return v\\n\\n    def __div__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if not hasattr(t, '_mpc_'):\\n            t = s.mpc_convert_lhs(t)\\n            if t is NotImplemented:\\n                return t\\n            if hasattr(t, '_mpf_'):\\n                v = new(cls)\\n                v._mpc_ = mpc_div_mpf(s._mpc_, t._mpf_, prec, rounding)\\n                return v\\n        v = new(cls)\\n        v._mpc_ = mpc_div(s._mpc_, t._mpc_, prec, rounding)\\n        return v\\n\\n    def __pow__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if isinstance(t, int_types):\\n            v = new(cls)\\n            v._mpc_ = mpc_pow_int(s._mpc_, t, prec, rounding)\\n            return v\\n        t = s.mpc_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        v = new(cls)\\n        if hasattr(t, '_mpf_'):\\n            v._mpc_ = mpc_pow_mpf(s._mpc_, t._mpf_, prec, rounding)\\n        else:\\n            v._mpc_ = mpc_pow(s._mpc_, t._mpc_, prec, rounding)\\n        return v\\n\\n    __radd__ = __add__\\n\\n    def __rsub__(s, t):\\n        t = s.mpc_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t - s\\n\\n    def __rmul__(s, t):\\n        cls, new, (prec, rounding) = s._ctxdata\\n        if isinstance(t, int_types):\\n            v = new(cls)\\n            v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding)\\n            return v\\n        t = s.mpc_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t * s\\n\\n    def __rdiv__(s, t):\\n        t = s.mpc_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t / s\\n\\n    def __rpow__(s, t):\\n        t = s.mpc_convert_lhs(t)\\n        if t is NotImplemented:\\n            return t\\n        return t ** s\\n\\n    __truediv__ = __div__\\n    __rtruediv__ = __rdiv__\\n\\n    def ae(s, t, rel_eps=None, abs_eps=None):\\n        return s.context.almosteq(s, t, rel_eps, abs_eps)\\n\\n\\ncomplex_types = (complex, _mpc)\\n\\n\\nclass PythonMPContext(object):\\n\\n    def __init__(ctx):\\n        ctx._prec_rounding = [53, round_nearest]\\n        ctx.mpf = type('mpf', (_mpf,), {})\\n        ctx.mpc = type('mpc', (_mpc,), {})\\n        ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding]\\n        ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding]\\n        ctx.mpf.context = ctx\\n        ctx.mpc.context = ctx\\n        ctx.constant = type('constant', (_constant,), {})\\n        ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding]\\n        ctx.constant.context = ctx\\n\\n    def make_mpf(ctx, v):\\n        a = new(ctx.mpf)\\n        a._mpf_ = v\\n        return a\\n\\n    def make_mpc(ctx, v):\\n        a = new(ctx.mpc)\\n        a._mpc_ = v\\n        return a\\n\\n    def default(ctx):\\n        ctx._prec = ctx._prec_rounding[0] = 53\\n        ctx._dps = 15\\n        ctx.trap_complex = False\\n\\n    def _set_prec(ctx, n):\\n        ctx._prec = ctx._prec_rounding[0] = max(1, int(n))\\n        ctx._dps = prec_to_dps(n)\\n\\n    def _set_dps(ctx, n):\\n        ctx._prec = ctx._prec_rounding[0] = dps_to_prec(n)\\n        ctx._dps = max(1, int(n))\\n\\n    prec = property(lambda ctx: ctx._prec, _set_prec)\\n    dps = property(lambda ctx: ctx._dps, _set_dps)\\n\\n    def convert(ctx, x, strings=True):\\n        \\\"\\\"\\\"\\n        Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``,\\n        ``mpc``, ``int``, ``float``, ``complex``, the conversion\\n        will be performed losslessly.\\n\\n        If *x* is a string, the result will be rounded to the present\\n        working precision. Strings representing fractions or complex\\n        numbers are permitted.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> mpmathify(3.5)\\n            mpf('3.5')\\n            >>> mpmathify('2.1')\\n            mpf('2.1000000000000001')\\n            >>> mpmathify('3/4')\\n            mpf('0.75')\\n            >>> mpmathify('2+3j')\\n            mpc(real='2.0', imag='3.0')\\n\\n        \\\"\\\"\\\"\\n        if type(x) in ctx.types: return x\\n        if isinstance(x, int_types): return ctx.make_mpf(from_int(x))\\n        if isinstance(x, float): return ctx.make_mpf(from_float(x))\\n        if isinstance(x, complex):\\n            return ctx.make_mpc((from_float(x.real), from_float(x.imag)))\\n        if type(x).__module__ == 'numpy': return ctx.npconvert(x)\\n        if isinstance(x, numbers.Rational): # e.g. Fraction\\n            try: x = rational.mpq(int(x.numerator), int(x.denominator))\\n            except: pass\\n        prec, rounding = ctx._prec_rounding\\n        if isinstance(x, rational.mpq):\\n            p, q = x._mpq_\\n            return ctx.make_mpf(from_rational(p, q, prec))\\n        if strings and isinstance(x, basestring):\\n            try:\\n                _mpf_ = from_str(x, prec, rounding)\\n                return ctx.make_mpf(_mpf_)\\n            except ValueError:\\n                pass\\n        if hasattr(x, '_mpf_'): return ctx.make_mpf(x._mpf_)\\n        if hasattr(x, '_mpc_'): return ctx.make_mpc(x._mpc_)\\n        if hasattr(x, '_mpmath_'):\\n            return ctx.convert(x._mpmath_(prec, rounding))\\n        if type(x).__module__ == 'decimal':\\n            try: return ctx.make_mpf(from_Decimal(x, prec, rounding))\\n            except: pass\\n        return ctx._convert_fallback(x, strings)\\n\\n    def npconvert(ctx, x):\\n        \\\"\\\"\\\"\\n        Converts *x* to an ``mpf`` or ``mpc``. *x* should be a numpy\\n        scalar.\\n        \\\"\\\"\\\"\\n        import numpy as np\\n        if isinstance(x, np.integer): return ctx.make_mpf(from_int(int(x)))\\n        if isinstance(x, np.floating): return ctx.make_mpf(from_npfloat(x))\\n        if isinstance(x, np.complexfloating):\\n            return ctx.make_mpc((from_npfloat(x.real), from_npfloat(x.imag)))\\n        raise TypeError(\\\"cannot create mpf from \\\" + repr(x))\\n\\n    def isnan(ctx, x):\\n        \\\"\\\"\\\"\\n        Return *True* if *x* is a NaN (not-a-number), or for a complex\\n        number, whether either the real or complex part is NaN;\\n        otherwise return *False*::\\n\\n            >>> from mpmath import *\\n            >>> isnan(3.14)\\n            False\\n            >>> isnan(nan)\\n            True\\n            >>> isnan(mpc(3.14,2.72))\\n            False\\n            >>> isnan(mpc(3.14,nan))\\n            True\\n\\n        \\\"\\\"\\\"\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            return x._mpf_ == fnan\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            return fnan in x._mpc_\\n        if isinstance(x, int_types) or isinstance(x, rational.mpq):\\n            return False\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):\\n            return ctx.isnan(x)\\n        raise TypeError(\\\"isnan() needs a number as input\\\")\\n\\n    def isinf(ctx, x):\\n        \\\"\\\"\\\"\\n        Return *True* if the absolute value of *x* is infinite;\\n        otherwise return *False*::\\n\\n            >>> from mpmath import *\\n            >>> isinf(inf)\\n            True\\n            >>> isinf(-inf)\\n            True\\n            >>> isinf(3)\\n            False\\n            >>> isinf(3+4j)\\n            False\\n            >>> isinf(mpc(3,inf))\\n            True\\n            >>> isinf(mpc(inf,3))\\n            True\\n\\n        \\\"\\\"\\\"\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            return x._mpf_ in (finf, fninf)\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            re, im = x._mpc_\\n            return re in (finf, fninf) or im in (finf, fninf)\\n        if isinstance(x, int_types) or isinstance(x, rational.mpq):\\n            return False\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):\\n            return ctx.isinf(x)\\n        raise TypeError(\\\"isinf() needs a number as input\\\")\\n\\n    def isnormal(ctx, x):\\n        \\\"\\\"\\\"\\n        Determine whether *x* is \\\"normal\\\" in the sense of floating-point\\n        representation; that is, return *False* if *x* is zero, an\\n        infinity or NaN; otherwise return *True*. By extension, a\\n        complex number *x* is considered \\\"normal\\\" if its magnitude is\\n        normal::\\n\\n            >>> from mpmath import *\\n            >>> isnormal(3)\\n            True\\n            >>> isnormal(0)\\n            False\\n            >>> isnormal(inf); isnormal(-inf); isnormal(nan)\\n            False\\n            False\\n            False\\n            >>> isnormal(0+0j)\\n            False\\n            >>> isnormal(0+3j)\\n            True\\n            >>> isnormal(mpc(2,nan))\\n            False\\n        \\\"\\\"\\\"\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            return bool(x._mpf_[1])\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            re, im = x._mpc_\\n            re_normal = bool(re[1])\\n            im_normal = bool(im[1])\\n            if re == fzero: return im_normal\\n            if im == fzero: return re_normal\\n            return re_normal and im_normal\\n        if isinstance(x, int_types) or isinstance(x, rational.mpq):\\n            return bool(x)\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):\\n            return ctx.isnormal(x)\\n        raise TypeError(\\\"isnormal() needs a number as input\\\")\\n\\n    def isint(ctx, x, gaussian=False):\\n        \\\"\\\"\\\"\\n        Return *True* if *x* is integer-valued; otherwise return\\n        *False*::\\n\\n            >>> from mpmath import *\\n            >>> isint(3)\\n            True\\n            >>> isint(mpf(3))\\n            True\\n            >>> isint(3.2)\\n            False\\n            >>> isint(inf)\\n            False\\n\\n        Optionally, Gaussian integers can be checked for::\\n\\n            >>> isint(3+0j)\\n            True\\n            >>> isint(3+2j)\\n            False\\n            >>> isint(3+2j, gaussian=True)\\n            True\\n\\n        \\\"\\\"\\\"\\n        if isinstance(x, int_types):\\n            return True\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            sign, man, exp, bc = xval = x._mpf_\\n            return bool((man and exp >= 0) or xval == fzero)\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            re, im = x._mpc_\\n            rsign, rman, rexp, rbc = re\\n            isign, iman, iexp, ibc = im\\n            re_isint = (rman and rexp >= 0) or re == fzero\\n            if gaussian:\\n                im_isint = (iman and iexp >= 0) or im == fzero\\n                return re_isint and im_isint\\n            return re_isint and im == fzero\\n        if isinstance(x, rational.mpq):\\n            p, q = x._mpq_\\n            return p % q == 0\\n        x = ctx.convert(x)\\n        if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):\\n            return ctx.isint(x, gaussian)\\n        raise TypeError(\\\"isint() needs a number as input\\\")\\n\\n    def fsum(ctx, terms, absolute=False, squared=False):\\n        \\\"\\\"\\\"\\n        Calculates a sum containing a finite number of terms (for infinite\\n        series, see :func:`~mpmath.nsum`). The terms will be converted to\\n        mpmath numbers. For len(terms) > 2, this function is generally\\n        faster and produces more accurate results than the builtin\\n        Python function :func:`sum`.\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> fsum([1, 2, 0.5, 7])\\n            mpf('10.5')\\n\\n        With squared=True each term is squared, and with absolute=True\\n        the absolute value of each term is used.\\n        \\\"\\\"\\\"\\n        prec, rnd = ctx._prec_rounding\\n        real = []\\n        imag = []\\n        for term in terms:\\n            reval = imval = 0\\n            if hasattr(term, \\\"_mpf_\\\"):\\n                reval = term._mpf_\\n            elif hasattr(term, \\\"_mpc_\\\"):\\n                reval, imval = term._mpc_\\n            else:\\n                term = ctx.convert(term)\\n                if hasattr(term, \\\"_mpf_\\\"):\\n                    reval = term._mpf_\\n                elif hasattr(term, \\\"_mpc_\\\"):\\n                    reval, imval = term._mpc_\\n                else:\\n                    raise NotImplementedError\\n            if imval:\\n                if squared:\\n                    if absolute:\\n                        real.append(mpf_mul(reval,reval))\\n                        real.append(mpf_mul(imval,imval))\\n                    else:\\n                        reval, imval = mpc_pow_int((reval,imval),2,prec+10)\\n                        real.append(reval)\\n                        imag.append(imval)\\n                elif absolute:\\n                    real.append(mpc_abs((reval,imval), prec))\\n                else:\\n                    real.append(reval)\\n                    imag.append(imval)\\n            else:\\n                if squared:\\n                    reval = mpf_mul(reval, reval)\\n                elif absolute:\\n                    reval = mpf_abs(reval)\\n                real.append(reval)\\n        s = mpf_sum(real, prec, rnd, absolute)\\n        if imag:\\n            s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd)))\\n        else:\\n            s = ctx.make_mpf(s)\\n        return s\\n\\n    def fdot(ctx, A, B=None, conjugate=False):\\n        r\\\"\\\"\\\"\\n        Computes the dot product of the iterables `A` and `B`,\\n\\n        .. math ::\\n\\n            \\\\sum_{k=0} A_k B_k.\\n\\n        Alternatively, :func:`~mpmath.fdot` accepts a single iterable of pairs.\\n        In other words, ``fdot(A,B)`` and ``fdot(zip(A,B))`` are equivalent.\\n        The elements are automatically converted to mpmath numbers.\\n\\n        With ``conjugate=True``, the elements in the second vector\\n        will be conjugated:\\n\\n        .. math ::\\n\\n            \\\\sum_{k=0} A_k \\\\overline{B_k}\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> A = [2, 1.5, 3]\\n            >>> B = [1, -1, 2]\\n            >>> fdot(A, B)\\n            mpf('6.5')\\n            >>> list(zip(A, B))\\n            [(2, 1), (1.5, -1), (3, 2)]\\n            >>> fdot(_)\\n            mpf('6.5')\\n            >>> A = [2, 1.5, 3j]\\n            >>> B = [1+j, 3, -1-j]\\n            >>> fdot(A, B)\\n            mpc(real='9.5', imag='-1.0')\\n            >>> fdot(A, B, conjugate=True)\\n            mpc(real='3.5', imag='-5.0')\\n\\n        \\\"\\\"\\\"\\n        if B is not None:\\n            A = zip(A, B)\\n        prec, rnd = ctx._prec_rounding\\n        real = []\\n        imag = []\\n        hasattr_ = hasattr\\n        types = (ctx.mpf, ctx.mpc)\\n        for a, b in A:\\n            if type(a) not in types: a = ctx.convert(a)\\n            if type(b) not in types: b = ctx.convert(b)\\n            a_real = hasattr_(a, \\\"_mpf_\\\")\\n            b_real = hasattr_(b, \\\"_mpf_\\\")\\n            if a_real and b_real:\\n                real.append(mpf_mul(a._mpf_, b._mpf_))\\n                continue\\n            a_complex = hasattr_(a, \\\"_mpc_\\\")\\n            b_complex = hasattr_(b, \\\"_mpc_\\\")\\n            if a_real and b_complex:\\n                aval = a._mpf_\\n                bre, bim = b._mpc_\\n                if conjugate:\\n                    bim = mpf_neg(bim)\\n                real.append(mpf_mul(aval, bre))\\n                imag.append(mpf_mul(aval, bim))\\n            elif b_real and a_complex:\\n                are, aim = a._mpc_\\n                bval = b._mpf_\\n                real.append(mpf_mul(are, bval))\\n                imag.append(mpf_mul(aim, bval))\\n            elif a_complex and b_complex:\\n                #re, im = mpc_mul(a._mpc_, b._mpc_, prec+20)\\n                are, aim = a._mpc_\\n                bre, bim = b._mpc_\\n                if conjugate:\\n                    bim = mpf_neg(bim)\\n                real.append(mpf_mul(are, bre))\\n                real.append(mpf_neg(mpf_mul(aim, bim)))\\n                imag.append(mpf_mul(are, bim))\\n                imag.append(mpf_mul(aim, bre))\\n            else:\\n                raise NotImplementedError\\n        s = mpf_sum(real, prec, rnd)\\n        if imag:\\n            s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd)))\\n        else:\\n            s = ctx.make_mpf(s)\\n        return s\\n\\n    def _wrap_libmp_function(ctx, mpf_f, mpc_f=None, mpi_f=None, doc=\\\"<no doc>\\\"):\\n        \\\"\\\"\\\"\\n        Given a low-level mpf_ function, and optionally similar functions\\n        for mpc_ and mpi_, defines the function as a context method.\\n\\n        It is assumed that the return type is the same as that of\\n        the input; the exception is that propagation from mpf to mpc is possible\\n        by raising ComplexResult.\\n\\n        \\\"\\\"\\\"\\n        def f(x, **kwargs):\\n            if type(x) not in ctx.types:\\n                x = ctx.convert(x)\\n            prec, rounding = ctx._prec_rounding\\n            if kwargs:\\n                prec = kwargs.get('prec', prec)\\n                if 'dps' in kwargs:\\n                    prec = dps_to_prec(kwargs['dps'])\\n                rounding = kwargs.get('rounding', rounding)\\n            if hasattr(x, '_mpf_'):\\n                try:\\n                    return ctx.make_mpf(mpf_f(x._mpf_, prec, rounding))\\n                except ComplexResult:\\n                    # Handle propagation to complex\\n                    if ctx.trap_complex:\\n                        raise\\n                    return ctx.make_mpc(mpc_f((x._mpf_, fzero), prec, rounding))\\n            elif hasattr(x, '_mpc_'):\\n                return ctx.make_mpc(mpc_f(x._mpc_, prec, rounding))\\n            raise NotImplementedError(\\\"%s of a %s\\\" % (name, type(x)))\\n        name = mpf_f.__name__[4:]\\n        f.__doc__ = function_docs.__dict__.get(name, \\\"Computes the %s of x\\\" % doc)\\n        return f\\n\\n    # Called by SpecialFunctions.__init__()\\n    @classmethod\\n    def _wrap_specfun(cls, name, f, wrap):\\n        if wrap:\\n            def f_wrapped(ctx, *args, **kwargs):\\n                convert = ctx.convert\\n                args = [convert(a) for a in args]\\n                prec = ctx.prec\\n                try:\\n                    ctx.prec += 10\\n                    retval = f(ctx, *args, **kwargs)\\n                finally:\\n                    ctx.prec = prec\\n                return +retval\\n        else:\\n            f_wrapped = f\\n        f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__)\\n        setattr(cls, name, f_wrapped)\\n\\n    def _convert_param(ctx, x):\\n        if hasattr(x, \\\"_mpc_\\\"):\\n            v, im = x._mpc_\\n            if im != fzero:\\n                return x, 'C'\\n        elif hasattr(x, \\\"_mpf_\\\"):\\n            v = x._mpf_\\n        else:\\n            if type(x) in int_types:\\n                return int(x), 'Z'\\n            p = None\\n            if isinstance(x, tuple):\\n                p, q = x\\n            elif hasattr(x, '_mpq_'):\\n                p, q = x._mpq_\\n            elif isinstance(x, basestring) and '/' in x:\\n                p, q = x.split('/')\\n                p = int(p)\\n                q = int(q)\\n            if p is not None:\\n                if not p % q:\\n                    return p // q, 'Z'\\n                return ctx.mpq(p,q), 'Q'\\n            x = ctx.convert(x)\\n            if hasattr(x, \\\"_mpc_\\\"):\\n                v, im = x._mpc_\\n                if im != fzero:\\n                    return x, 'C'\\n            elif hasattr(x, \\\"_mpf_\\\"):\\n                v = x._mpf_\\n            else:\\n                return x, 'U'\\n        sign, man, exp, bc = v\\n        if man:\\n            if exp >= -4:\\n                if sign:\\n                    man = -man\\n                if exp >= 0:\\n                    return int(man) << exp, 'Z'\\n                if exp >= -4:\\n                    p, q = int(man), (1<<(-exp))\\n                    return ctx.mpq(p,q), 'Q'\\n            x = ctx.make_mpf(v)\\n            return x, 'R'\\n        elif not exp:\\n            return 0, 'Z'\\n        else:\\n            return x, 'U'\\n\\n    def _mpf_mag(ctx, x):\\n        sign, man, exp, bc = x\\n        if man:\\n            return exp+bc\\n        if x == fzero:\\n            return ctx.ninf\\n        if x == finf or x == fninf:\\n            return ctx.inf\\n        return ctx.nan\\n\\n    def mag(ctx, x):\\n        \\\"\\\"\\\"\\n        Quick logarithmic magnitude estimate of a number. Returns an\\n        integer or infinity `m` such that `|x| <= 2^m`. It is not\\n        guaranteed that `m` is an optimal bound, but it will never\\n        be too large by more than 2 (and probably not more than 1).\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.pretty = True\\n            >>> mag(10), mag(10.0), mag(mpf(10)), int(ceil(log(10,2)))\\n            (4, 4, 4, 4)\\n            >>> mag(10j), mag(10+10j)\\n            (4, 5)\\n            >>> mag(0.01), int(ceil(log(0.01,2)))\\n            (-6, -6)\\n            >>> mag(0), mag(inf), mag(-inf), mag(nan)\\n            (-inf, +inf, +inf, nan)\\n\\n        \\\"\\\"\\\"\\n        if hasattr(x, \\\"_mpf_\\\"):\\n            return ctx._mpf_mag(x._mpf_)\\n        elif hasattr(x, \\\"_mpc_\\\"):\\n            r, i = x._mpc_\\n            if r == fzero:\\n                return ctx._mpf_mag(i)\\n            if i == fzero:\\n                return ctx._mpf_mag(r)\\n            return 1+max(ctx._mpf_mag(r), ctx._mpf_mag(i))\\n        elif isinstance(x, int_types):\\n            if x:\\n                return bitcount(abs(x))\\n            return ctx.ninf\\n        elif isinstance(x, rational.mpq):\\n            p, q = x._mpq_\\n            if p:\\n                return 1 + bitcount(abs(p)) - bitcount(q)\\n            return ctx.ninf\\n        else:\\n            x = ctx.convert(x)\\n            if hasattr(x, \\\"_mpf_\\\") or hasattr(x, \\\"_mpc_\\\"):\\n                return ctx.mag(x)\\n            else:\\n                raise TypeError(\\\"requires an mpf/mpc\\\")\\n\\n\\n# Register with \\\"numbers\\\" ABC\\n#     We do not subclass, hence we do not use the @abstractmethod checks. While\\n#     this is less invasive it may turn out that we do not actually support\\n#     parts of the expected interfaces.  See\\n#     http://docs.python.org/2/library/numbers.html for list of abstract\\n#     methods.\\ntry:\\n    import numbers\\n    numbers.Complex.register(_mpc)\\n    numbers.Real.register(_mpf)\\nexcept ImportError:\\n    pass\\n\\n\\nfrom operator import gt, lt\\n\\nfrom .libmp.backend import xrange\\n\\nfrom .functions.functions import SpecialFunctions\\nfrom .functions.rszeta import RSCache\\nfrom .calculus.quadrature import QuadratureMethods\\nfrom .calculus.inverselaplace import LaplaceTransformInversionMethods\\nfrom .calculus.calculus import CalculusMethods\\nfrom .calculus.optimization import OptimizationMethods\\nfrom .calculus.odes import ODEMethods\\nfrom .matrices.matrices import MatrixMethods\\nfrom .matrices.calculus import MatrixCalculusMethods\\nfrom .matrices.linalg import LinearAlgebraMethods\\nfrom .matrices.eigen import Eigen\\nfrom .identification import IdentificationMethods\\nfrom .visualization import VisualizationMethods\\n\\nfrom . import libmp\\n\\nclass Context(object):\\n    pass\\n\\nclass StandardBaseContext(Context,\\n    SpecialFunctions,\\n    RSCache,\\n    QuadratureMethods,\\n    LaplaceTransformInversionMethods,\\n    CalculusMethods,\\n    MatrixMethods,\\n    MatrixCalculusMethods,\\n    LinearAlgebraMethods,\\n    Eigen,\\n    IdentificationMethods,\\n    OptimizationMethods,\\n    ODEMethods,\\n    VisualizationMethods):\\n\\n    NoConvergence = libmp.NoConvergence\\n    ComplexResult = libmp.ComplexResult\\n\\n    def __init__(ctx):\\n        ctx._aliases = {}\\n        # Call those that need preinitialization (e.g. for wrappers)\\n        SpecialFunctions.__init__(ctx)\\n        RSCache.__init__(ctx)\\n        QuadratureMethods.__init__(ctx)\\n        LaplaceTransformInversionMethods.__init__(ctx)\\n        CalculusMethods.__init__(ctx)\\n        MatrixMethods.__init__(ctx)\\n\\n    def _init_aliases(ctx):\\n        for alias, value in ctx._aliases.items():\\n            try:\\n                setattr(ctx, alias, getattr(ctx, value))\\n            except AttributeError:\\n                pass\\n\\n    _fixed_precision = False\\n\\n    # XXX\\n    verbose = False\\n\\n    def warn(ctx, msg):\\n        print(\\\"Warning:\\\", msg)\\n\\n    def bad_domain(ctx, msg):\\n        raise ValueError(msg)\\n\\n    def _re(ctx, x):\\n        if hasattr(x, \\\"real\\\"):\\n            return x.real\\n        return x\\n\\n    def _im(ctx, x):\\n        if hasattr(x, \\\"imag\\\"):\\n            return x.imag\\n        return ctx.zero\\n\\n    def _as_points(ctx, x):\\n        return x\\n\\n    def fneg(ctx, x, **kwargs):\\n        return -ctx.convert(x)\\n\\n    def fadd(ctx, x, y, **kwargs):\\n        return ctx.convert(x)+ctx.convert(y)\\n\\n    def fsub(ctx, x, y, **kwargs):\\n        return ctx.convert(x)-ctx.convert(y)\\n\\n    def fmul(ctx, x, y, **kwargs):\\n        return ctx.convert(x)*ctx.convert(y)\\n\\n    def fdiv(ctx, x, y, **kwargs):\\n        return ctx.convert(x)/ctx.convert(y)\\n\\n    def fsum(ctx, args, absolute=False, squared=False):\\n        if absolute:\\n            if squared:\\n                return sum((abs(x)**2 for x in args), ctx.zero)\\n            return sum((abs(x) for x in args), ctx.zero)\\n        if squared:\\n            return sum((x**2 for x in args), ctx.zero)\\n        return sum(args, ctx.zero)\\n\\n    def fdot(ctx, xs, ys=None, conjugate=False):\\n        if ys is not None:\\n            xs = zip(xs, ys)\\n        if conjugate:\\n            cf = ctx.conj\\n            return sum((x*cf(y) for (x,y) in xs), ctx.zero)\\n        else:\\n            return sum((x*y for (x,y) in xs), ctx.zero)\\n\\n    def fprod(ctx, args):\\n        prod = ctx.one\\n        for arg in args:\\n            prod *= arg\\n        return prod\\n\\n    def nprint(ctx, x, n=6, **kwargs):\\n        \\\"\\\"\\\"\\n        Equivalent to ``print(nstr(x, n))``.\\n        \\\"\\\"\\\"\\n        print(ctx.nstr(x, n, **kwargs))\\n\\n    def chop(ctx, x, tol=None):\\n        \\\"\\\"\\\"\\n        Chops off small real or imaginary parts, or converts\\n        numbers close to zero to exact zeros. The input can be a\\n        single number or an iterable::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> chop(5+1e-10j, tol=1e-9)\\n            mpf('5.0')\\n            >>> nprint(chop([1.0, 1e-20, 3+1e-18j, -4, 2]))\\n            [1.0, 0.0, 3.0, -4.0, 2.0]\\n\\n        The tolerance defaults to ``100*eps``.\\n        \\\"\\\"\\\"\\n        if tol is None:\\n            tol = 100*ctx.eps\\n        try:\\n            x = ctx.convert(x)\\n            absx = abs(x)\\n            if abs(x) < tol:\\n                return ctx.zero\\n            if ctx._is_complex_type(x):\\n                #part_tol = min(tol, absx*tol)\\n                part_tol = max(tol, absx*tol)\\n                if abs(x.imag) < part_tol:\\n                    return x.real\\n                if abs(x.real) < part_tol:\\n                    return ctx.mpc(0, x.imag)\\n        except TypeError:\\n            if isinstance(x, ctx.matrix):\\n                return x.apply(lambda a: ctx.chop(a, tol))\\n            if hasattr(x, \\\"__iter__\\\"):\\n                return [ctx.chop(a, tol) for a in x]\\n        return x\\n\\n    def almosteq(ctx, s, t, rel_eps=None, abs_eps=None):\\n        r\\\"\\\"\\\"\\n        Determine whether the difference between `s` and `t` is smaller\\n        than a given epsilon, either relatively or absolutely.\\n\\n        Both a maximum relative difference and a maximum difference\\n        ('epsilons') may be specified. The absolute difference is\\n        defined as `|s-t|` and the relative difference is defined\\n        as `|s-t|/\\\\max(|s|, |t|)`.\\n\\n        If only one epsilon is given, both are set to the same value.\\n        If none is given, both epsilons are set to `2^{-p+m}` where\\n        `p` is the current working precision and `m` is a small\\n        integer. The default setting typically allows :func:`~mpmath.almosteq`\\n        to be used to check for mathematical equality\\n        in the presence of small rounding errors.\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15\\n            >>> almosteq(3.141592653589793, 3.141592653589790)\\n            True\\n            >>> almosteq(3.141592653589793, 3.141592653589700)\\n            False\\n            >>> almosteq(3.141592653589793, 3.141592653589700, 1e-10)\\n            True\\n            >>> almosteq(1e-20, 2e-20)\\n            True\\n            >>> almosteq(1e-20, 2e-20, rel_eps=0, abs_eps=0)\\n            False\\n\\n        \\\"\\\"\\\"\\n        t = ctx.convert(t)\\n        if abs_eps is None and rel_eps is None:\\n            rel_eps = abs_eps = ctx.ldexp(1, -ctx.prec+4)\\n        if abs_eps is None:\\n            abs_eps = rel_eps\\n        elif rel_eps is None:\\n            rel_eps = abs_eps\\n        diff = abs(s-t)\\n        if diff <= abs_eps:\\n            return True\\n        abss = abs(s)\\n        abst = abs(t)\\n        if abss < abst:\\n            err = diff/abst\\n        else:\\n            err = diff/abss\\n        return err <= rel_eps\\n\\n    def arange(ctx, *args):\\n        r\\\"\\\"\\\"\\n        This is a generalized version of Python's :func:`~mpmath.range` function\\n        that accepts fractional endpoints and step sizes and\\n        returns a list of ``mpf`` instances. Like :func:`~mpmath.range`,\\n        :func:`~mpmath.arange` can be called with 1, 2 or 3 arguments:\\n\\n        ``arange(b)``\\n            `[0, 1, 2, \\\\ldots, x]`\\n        ``arange(a, b)``\\n            `[a, a+1, a+2, \\\\ldots, x]`\\n        ``arange(a, b, h)``\\n            `[a, a+h, a+h, \\\\ldots, x]`\\n\\n        where `b-1 \\\\le x < b` (in the third case, `b-h \\\\le x < b`).\\n\\n        Like Python's :func:`~mpmath.range`, the endpoint is not included. To\\n        produce ranges where the endpoint is included, :func:`~mpmath.linspace`\\n        is more convenient.\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> arange(4)\\n            [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0')]\\n            >>> arange(1, 2, 0.25)\\n            [mpf('1.0'), mpf('1.25'), mpf('1.5'), mpf('1.75')]\\n            >>> arange(1, -1, -0.75)\\n            [mpf('1.0'), mpf('0.25'), mpf('-0.5')]\\n\\n        \\\"\\\"\\\"\\n        if not len(args) <= 3:\\n            raise TypeError('arange expected at most 3 arguments, got %i'\\n                            % len(args))\\n        if not len(args) >= 1:\\n            raise TypeError('arange expected at least 1 argument, got %i'\\n                            % len(args))\\n        # set default\\n        a = 0\\n        dt = 1\\n        # interpret arguments\\n        if len(args) == 1:\\n            b = args[0]\\n        elif len(args) >= 2:\\n            a = args[0]\\n            b = args[1]\\n        if len(args) == 3:\\n            dt = args[2]\\n        a, b, dt = ctx.mpf(a), ctx.mpf(b), ctx.mpf(dt)\\n        assert a + dt != a, 'dt is too small and would cause an infinite loop'\\n        # adapt code for sign of dt\\n        if a > b:\\n            if dt > 0:\\n                return []\\n            op = gt\\n        else:\\n            if dt < 0:\\n                return []\\n            op = lt\\n        # create list\\n        result = []\\n        i = 0\\n        t = a\\n        while 1:\\n            t = a + dt*i\\n            i += 1\\n            if op(t, b):\\n                result.append(t)\\n            else:\\n                break\\n        return result\\n\\n    def linspace(ctx, *args, **kwargs):\\n        \\\"\\\"\\\"\\n        ``linspace(a, b, n)`` returns a list of `n` evenly spaced\\n        samples from `a` to `b`. The syntax ``linspace(mpi(a,b), n)``\\n        is also valid.\\n\\n        This function is often more convenient than :func:`~mpmath.arange`\\n        for partitioning an interval into subintervals, since\\n        the endpoint is included::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> linspace(1, 4, 4)\\n            [mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')]\\n\\n        You may also provide the keyword argument ``endpoint=False``::\\n\\n            >>> linspace(1, 4, 4, endpoint=False)\\n            [mpf('1.0'), mpf('1.75'), mpf('2.5'), mpf('3.25')]\\n\\n        \\\"\\\"\\\"\\n        if len(args) == 3:\\n            a = ctx.mpf(args[0])\\n            b = ctx.mpf(args[1])\\n            n = int(args[2])\\n        elif len(args) == 2:\\n            assert hasattr(args[0], '_mpi_')\\n            a = args[0].a\\n            b = args[0].b\\n            n = int(args[1])\\n        else:\\n            raise TypeError('linspace expected 2 or 3 arguments, got %i' \\\\\\n                            % len(args))\\n        if n < 1:\\n            raise ValueError('n must be greater than 0')\\n        if not 'endpoint' in kwargs or kwargs['endpoint']:\\n            if n == 1:\\n                return [ctx.mpf(a)]\\n            step = (b - a) / ctx.mpf(n - 1)\\n            y = [i*step + a for i in xrange(n)]\\n            y[-1] = b\\n        else:\\n            step = (b - a) / ctx.mpf(n)\\n            y = [i*step + a for i in xrange(n)]\\n        return y\\n\\n    def cos_sin(ctx, z, **kwargs):\\n        return ctx.cos(z, **kwargs), ctx.sin(z, **kwargs)\\n\\n    def cospi_sinpi(ctx, z, **kwargs):\\n        return ctx.cospi(z, **kwargs), ctx.sinpi(z, **kwargs)\\n\\n    def _default_hyper_maxprec(ctx, p):\\n        return int(1000 * p**0.25 + 4*p)\\n\\n    _gcd = staticmethod(libmp.gcd)\\n    list_primes = staticmethod(libmp.list_primes)\\n    isprime = staticmethod(libmp.isprime)\\n    bernfrac = staticmethod(libmp.bernfrac)\\n    moebius = staticmethod(libmp.moebius)\\n    _ifac = staticmethod(libmp.ifac)\\n    _eulernum = staticmethod(libmp.eulernum)\\n    _stirling1 = staticmethod(libmp.stirling1)\\n    _stirling2 = staticmethod(libmp.stirling2)\\n\\n    def sum_accurately(ctx, terms, check_step=1):\\n        prec = ctx.prec\\n        try:\\n            extraprec = 10\\n            while 1:\\n                ctx.prec = prec + extraprec + 5\\n                max_mag = ctx.ninf\\n                s = ctx.zero\\n                k = 0\\n                for term in terms():\\n                    s += term\\n                    if (not k % check_step) and term:\\n                        term_mag = ctx.mag(term)\\n                        max_mag = max(max_mag, term_mag)\\n                        sum_mag = ctx.mag(s)\\n                        if sum_mag - term_mag > ctx.prec:\\n                            break\\n                    k += 1\\n                cancellation = max_mag - sum_mag\\n                if cancellation != cancellation:\\n                    break\\n                if cancellation < extraprec or ctx._fixed_precision:\\n                    break\\n                extraprec += min(ctx.prec, cancellation)\\n            return s\\n        finally:\\n            ctx.prec = prec\\n\\n    def mul_accurately(ctx, factors, check_step=1):\\n        prec = ctx.prec\\n        try:\\n            extraprec = 10\\n            while 1:\\n                ctx.prec = prec + extraprec + 5\\n                max_mag = ctx.ninf\\n                one = ctx.one\\n                s = one\\n                k = 0\\n                for factor in factors():\\n                    s *= factor\\n                    term = factor - one\\n                    if (not k % check_step):\\n                        term_mag = ctx.mag(term)\\n                        max_mag = max(max_mag, term_mag)\\n                        sum_mag = ctx.mag(s-one)\\n                        #if sum_mag - term_mag > ctx.prec:\\n                        #    break\\n                        if -term_mag > ctx.prec:\\n                            break\\n                    k += 1\\n                cancellation = max_mag - sum_mag\\n                if cancellation != cancellation:\\n                    break\\n                if cancellation < extraprec or ctx._fixed_precision:\\n                    break\\n                extraprec += min(ctx.prec, cancellation)\\n            return s\\n        finally:\\n            ctx.prec = prec\\n\\n    def power(ctx, x, y):\\n        r\\\"\\\"\\\"Converts `x` and `y` to mpmath numbers and evaluates\\n        `x^y = \\\\exp(y \\\\log(x))`::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 30; mp.pretty = True\\n            >>> power(2, 0.5)\\n            1.41421356237309504880168872421\\n\\n        This shows the leading few digits of a large Mersenne prime\\n        (performing the exact calculation ``2**43112609-1`` and\\n        displaying the result in Python would be very slow)::\\n\\n            >>> power(2, 43112609)-1\\n            3.16470269330255923143453723949e+12978188\\n        \\\"\\\"\\\"\\n        return ctx.convert(x) ** ctx.convert(y)\\n\\n    def _zeta_int(ctx, n):\\n        return ctx.zeta(n)\\n\\n    def maxcalls(ctx, f, N):\\n        \\\"\\\"\\\"\\n        Return a wrapped copy of *f* that raises ``NoConvergence`` when *f*\\n        has been called more than *N* times::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15\\n            >>> f = maxcalls(sin, 10)\\n            >>> print(sum(f(n) for n in range(10)))\\n            1.95520948210738\\n            >>> f(10) # doctest: +IGNORE_EXCEPTION_DETAIL\\n            Traceback (most recent call last):\\n              ...\\n            NoConvergence: maxcalls: function evaluated 10 times\\n\\n        \\\"\\\"\\\"\\n        counter = [0]\\n        def f_maxcalls_wrapped(*args, **kwargs):\\n            counter[0] += 1\\n            if counter[0] > N:\\n                raise ctx.NoConvergence(\\\"maxcalls: function evaluated %i times\\\" % N)\\n            return f(*args, **kwargs)\\n        return f_maxcalls_wrapped\\n\\n    def memoize(ctx, f):\\n        \\\"\\\"\\\"\\n        Return a wrapped copy of *f* that caches computed values, i.e.\\n        a memoized copy of *f*. Values are only reused if the cached precision\\n        is equal to or higher than the working precision::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> f = memoize(maxcalls(sin, 1))\\n            >>> f(2)\\n            0.909297426825682\\n            >>> f(2)\\n            0.909297426825682\\n            >>> mp.dps = 25\\n            >>> f(2) # doctest: +IGNORE_EXCEPTION_DETAIL\\n            Traceback (most recent call last):\\n              ...\\n            NoConvergence: maxcalls: function evaluated 1 times\\n\\n        \\\"\\\"\\\"\\n        f_cache = {}\\n        def f_cached(*args, **kwargs):\\n            if kwargs:\\n                key = args, tuple(kwargs.items())\\n            else:\\n                key = args\\n            prec = ctx.prec\\n            if key in f_cache:\\n                cprec, cvalue = f_cache[key]\\n                if cprec >= prec:\\n                    return +cvalue\\n            value = f(*args, **kwargs)\\n            f_cache[key] = (prec, value)\\n            return value\\n        f_cached.__name__ = f.__name__\\n        f_cached.__doc__ = f.__doc__\\n        return f_cached\\n\\n\\n__version__ = '1.3.0'\\n\\nfrom .usertools import monitor, timing\\n\\nfrom .ctx_fp import FPContext\\nfrom .ctx_mp import MPContext\\nfrom .ctx_iv import MPIntervalContext\\n\\nfp = FPContext()\\nmp = MPContext()\\niv = MPIntervalContext()\\n\\nfp._mp = mp\\nmp._mp = mp\\niv._mp = mp\\nmp._fp = fp\\nfp._fp = fp\\nmp._iv = iv\\nfp._iv = iv\\niv._iv = iv\\n\\n# XXX: extremely bad pickle hack\\nfrom . import ctx_mp as _ctx_mp\\n_ctx_mp._mpf_module.mpf = mp.mpf\\n_ctx_mp._mpf_module.mpc = mp.mpc\\n\\nmake_mpf = mp.make_mpf\\nmake_mpc = mp.make_mpc\\n\\nextraprec = mp.extraprec\\nextradps = mp.extradps\\nworkprec = mp.workprec\\nworkdps = mp.workdps\\nautoprec = mp.autoprec\\nmaxcalls = mp.maxcalls\\nmemoize = mp.memoize\\n\\nmag = mp.mag\\n\\nbernfrac = mp.bernfrac\\n\\nqfrom = mp.qfrom\\nmfrom = mp.mfrom\\nkfrom = mp.kfrom\\ntaufrom = mp.taufrom\\nqbarfrom = mp.qbarfrom\\nellipfun = mp.ellipfun\\njtheta = mp.jtheta\\nkleinj = mp.kleinj\\neta = mp.eta\\n\\nqp = mp.qp\\nqhyper = mp.qhyper\\nqgamma = mp.qgamma\\nqfac = mp.qfac\\n\\nnint_distance = mp.nint_distance\\n\\nplot = mp.plot\\ncplot = mp.cplot\\nsplot = mp.splot\\n\\nodefun = mp.odefun\\n\\njacobian = mp.jacobian\\nfindroot = mp.findroot\\nmultiplicity = mp.multiplicity\\n\\nisinf = mp.isinf\\nisnan = mp.isnan\\nisnormal = mp.isnormal\\nisint = mp.isint\\nisfinite = mp.isfinite\\nalmosteq = mp.almosteq\\nnan = mp.nan\\nrand = mp.rand\\n\\nabsmin = mp.absmin\\nabsmax = mp.absmax\\n\\nfraction = mp.fraction\\n\\nlinspace = mp.linspace\\narange = mp.arange\\n\\nmpmathify = convert = mp.convert\\nmpc = mp.mpc\\n\\nmpi = iv._mpi\\n\\nnstr = mp.nstr\\nnprint = mp.nprint\\nchop = mp.chop\\n\\nfneg = mp.fneg\\nfadd = mp.fadd\\nfsub = mp.fsub\\nfmul = mp.fmul\\nfdiv = mp.fdiv\\nfprod = mp.fprod\\n\\nquad = mp.quad\\nquadgl = mp.quadgl\\nquadts = mp.quadts\\nquadosc = mp.quadosc\\nquadsubdiv = mp.quadsubdiv\\n\\ninvertlaplace = mp.invertlaplace\\ninvlaptalbot = mp.invlaptalbot\\ninvlapstehfest = mp.invlapstehfest\\ninvlapdehoog = mp.invlapdehoog\\n\\npslq = mp.pslq\\nidentify = mp.identify\\nfindpoly = mp.findpoly\\n\\nrichardson = mp.richardson\\nshanks = mp.shanks\\nlevin = mp.levin\\ncohen_alt = mp.cohen_alt\\nnsum = mp.nsum\\nnprod = mp.nprod\\ndifference = mp.difference\\ndiff = mp.diff\\ndiffs = mp.diffs\\ndiffs_prod = mp.diffs_prod\\ndiffs_exp = mp.diffs_exp\\ndiffun = mp.diffun\\ndifferint = mp.differint\\ntaylor = mp.taylor\\npade = mp.pade\\npolyval = mp.polyval\\npolyroots = mp.polyroots\\nfourier = mp.fourier\\nfourierval = mp.fourierval\\nsumem = mp.sumem\\nsumap = mp.sumap\\nchebyfit = mp.chebyfit\\nlimit = mp.limit\\n\\nmatrix = mp.matrix\\neye = mp.eye\\ndiag = mp.diag\\nzeros = mp.zeros\\nones = mp.ones\\nhilbert = mp.hilbert\\nrandmatrix = mp.randmatrix\\nswap_row = mp.swap_row\\nextend = mp.extend\\nnorm = mp.norm\\nmnorm = mp.mnorm\\n\\nlu_solve = mp.lu_solve\\nlu = mp.lu\\nqr = mp.qr\\nunitvector = mp.unitvector\\ninverse = mp.inverse\\nresidual = mp.residual\\nqr_solve = mp.qr_solve\\ncholesky = mp.cholesky\\ncholesky_solve = mp.cholesky_solve\\ndet = mp.det\\ncond = mp.cond\\nhessenberg = mp.hessenberg\\nschur = mp.schur\\neig = mp.eig\\neig_sort = mp.eig_sort\\neigsy = mp.eigsy\\neighe = mp.eighe\\neigh = mp.eigh\\nsvd_r = mp.svd_r\\nsvd_c = mp.svd_c\\nsvd = mp.svd\\ngauss_quadrature = mp.gauss_quadrature\\n\\nexpm = mp.expm\\nsqrtm = mp.sqrtm\\npowm = mp.powm\\nlogm = mp.logm\\nsinm = mp.sinm\\ncosm = mp.cosm\\n\\nmpf = mp.mpf\\nj = mp.j\\nexp = mp.exp\\nexpj = mp.expj\\nexpjpi = mp.expjpi\\nln = mp.ln\\nim = mp.im\\nre = mp.re\\ninf = mp.inf\\nninf = mp.ninf\\nsign = mp.sign\\n\\neps = mp.eps\\npi = mp.pi\\nln2 = mp.ln2\\nln10 = mp.ln10\\nphi = mp.phi\\ne = mp.e\\neuler = mp.euler\\ncatalan = mp.catalan\\nkhinchin = mp.khinchin\\nglaisher = mp.glaisher\\napery = mp.apery\\ndegree = mp.degree\\ntwinprime = mp.twinprime\\nmertens = mp.mertens\\n\\nldexp = mp.ldexp\\nfrexp = mp.frexp\\n\\nfsum = mp.fsum\\nfdot = mp.fdot\\n\\nsqrt = mp.sqrt\\ncbrt = mp.cbrt\\nexp = mp.exp\\nln = mp.ln\\nlog = mp.log\\nlog10 = mp.log10\\npower = mp.power\\ncos = mp.cos\\nsin = mp.sin\\ntan = mp.tan\\ncosh = mp.cosh\\nsinh = mp.sinh\\ntanh = mp.tanh\\nacos = mp.acos\\nasin = mp.asin\\natan = mp.atan\\nasinh = mp.asinh\\nacosh = mp.acosh\\natanh = mp.atanh\\nsec = mp.sec\\ncsc = mp.csc\\ncot = mp.cot\\nsech = mp.sech\\ncsch = mp.csch\\ncoth = mp.coth\\nasec = mp.asec\\nacsc = mp.acsc\\nacot = mp.acot\\nasech = mp.asech\\nacsch = mp.acsch\\nacoth = mp.acoth\\ncospi = mp.cospi\\nsinpi = mp.sinpi\\nsinc = mp.sinc\\nsincpi = mp.sincpi\\ncos_sin = mp.cos_sin\\ncospi_sinpi = mp.cospi_sinpi\\nfabs = mp.fabs\\nre = mp.re\\nim = mp.im\\nconj = mp.conj\\nfloor = mp.floor\\nceil = mp.ceil\\nnint = mp.nint\\nfrac = mp.frac\\nroot = mp.root\\nnthroot = mp.nthroot\\nhypot = mp.hypot\\nfmod = mp.fmod\\nldexp = mp.ldexp\\nfrexp = mp.frexp\\nsign = mp.sign\\narg = mp.arg\\nphase = mp.phase\\npolar = mp.polar\\nrect = mp.rect\\ndegrees = mp.degrees\\nradians = mp.radians\\natan2 = mp.atan2\\nfib = mp.fib\\nfibonacci = mp.fibonacci\\nlambertw = mp.lambertw\\nzeta = mp.zeta\\naltzeta = mp.altzeta\\ngamma = mp.gamma\\nrgamma = mp.rgamma\\nfactorial = mp.factorial\\nfac = mp.fac\\nfac2 = mp.fac2\\nbeta = mp.beta\\nbetainc = mp.betainc\\npsi = mp.psi\\n#psi0 = mp.psi0\\n#psi1 = mp.psi1\\n#psi2 = mp.psi2\\n#psi3 = mp.psi3\\npolygamma = mp.polygamma\\ndigamma = mp.digamma\\n#trigamma = mp.trigamma\\n#tetragamma = mp.tetragamma\\n#pentagamma = mp.pentagamma\\nharmonic = mp.harmonic\\nbernoulli = mp.bernoulli\\nbernfrac = mp.bernfrac\\nstieltjes = mp.stieltjes\\nhurwitz = mp.hurwitz\\ndirichlet = mp.dirichlet\\nbernpoly = mp.bernpoly\\neulerpoly = mp.eulerpoly\\neulernum = mp.eulernum\\npolylog = mp.polylog\\nclsin = mp.clsin\\nclcos = mp.clcos\\ngammainc = mp.gammainc\\ngammaprod = mp.gammaprod\\nbinomial = mp.binomial\\nrf = mp.rf\\nff = mp.ff\\nhyper = mp.hyper\\nhyp0f1 = mp.hyp0f1\\nhyp1f1 = mp.hyp1f1\\nhyp1f2 = mp.hyp1f2\\nhyp2f1 = mp.hyp2f1\\nhyp2f2 = mp.hyp2f2\\nhyp2f0 = mp.hyp2f0\\nhyp2f3 = mp.hyp2f3\\nhyp3f2 = mp.hyp3f2\\nhyperu = mp.hyperu\\nhypercomb = mp.hypercomb\\nmeijerg = mp.meijerg\\nappellf1 = mp.appellf1\\nappellf2 = mp.appellf2\\nappellf3 = mp.appellf3\\nappellf4 = mp.appellf4\\nhyper2d = mp.hyper2d\\nbihyper = mp.bihyper\\nerf = mp.erf\\nerfc = mp.erfc\\nerfi = mp.erfi\\nerfinv = mp.erfinv\\nnpdf = mp.npdf\\nncdf = mp.ncdf\\nexpint = mp.expint\\ne1 = mp.e1\\nei = mp.ei\\nli = mp.li\\nci = mp.ci\\nsi = mp.si\\nchi = mp.chi\\nshi = mp.shi\\nfresnels = mp.fresnels\\nfresnelc = mp.fresnelc\\nairyai = mp.airyai\\nairybi = mp.airybi\\nairyaizero = mp.airyaizero\\nairybizero = mp.airybizero\\nscorergi = mp.scorergi\\nscorerhi = mp.scorerhi\\nellipk = mp.ellipk\\nellipe = mp.ellipe\\nellipf = mp.ellipf\\nellippi = mp.ellippi\\nelliprc = mp.elliprc\\nelliprj = mp.elliprj\\nelliprf = mp.elliprf\\nelliprd = mp.elliprd\\nelliprg = mp.elliprg\\nagm = mp.agm\\njacobi = mp.jacobi\\nchebyt = mp.chebyt\\nchebyu = mp.chebyu\\nlegendre = mp.legendre\\nlegenp = mp.legenp\\nlegenq = mp.legenq\\nhermite = mp.hermite\\npcfd = mp.pcfd\\npcfu = mp.pcfu\\npcfv = mp.pcfv\\npcfw = mp.pcfw\\ngegenbauer = mp.gegenbauer\\nlaguerre = mp.laguerre\\nspherharm = mp.spherharm\\nbesselj = mp.besselj\\nj0 = mp.j0\\nj1 = mp.j1\\nbesseli = mp.besseli\\nbessely = mp.bessely\\nbesselk = mp.besselk\\nbesseljzero = mp.besseljzero\\nbesselyzero = mp.besselyzero\\nhankel1 = mp.hankel1\\nhankel2 = mp.hankel2\\nstruveh = mp.struveh\\nstruvel = mp.struvel\\nangerj = mp.angerj\\nwebere = mp.webere\\nlommels1 = mp.lommels1\\nlommels2 = mp.lommels2\\nwhitm = mp.whitm\\nwhitw = mp.whitw\\nber = mp.ber\\nbei = mp.bei\\nker = mp.ker\\nkei = mp.kei\\ncoulombc = mp.coulombc\\ncoulombf = mp.coulombf\\ncoulombg = mp.coulombg\\nbarnesg = mp.barnesg\\nsuperfac = mp.superfac\\nhyperfac = mp.hyperfac\\nloggamma = mp.loggamma\\nsiegeltheta = mp.siegeltheta\\nsiegelz = mp.siegelz\\ngrampoint = mp.grampoint\\nzetazero = mp.zetazero\\nriemannr = mp.riemannr\\nprimepi = mp.primepi\\nprimepi2 = mp.primepi2\\nprimezeta = mp.primezeta\\nbell = mp.bell\\npolyexp = mp.polyexp\\nexpm1 = mp.expm1\\nlog1p = mp.log1p\\npowm1 = mp.powm1\\nunitroots = mp.unitroots\\ncyclotomic = mp.cyclotomic\\nmangoldt = mp.mangoldt\\nsecondzeta = mp.secondzeta\\nnzeros = mp.nzeros\\nbacklunds = mp.backlunds\\nlerchphi = mp.lerchphi\\nstirling1 = mp.stirling1\\nstirling2 = mp.stirling2\\nsquarew = mp.squarew\\ntrianglew = mp.trianglew\\nsawtoothw = mp.sawtoothw\\nunit_triangle = mp.unit_triangle\\nsigmoid = mp.sigmoid\\n\\n# be careful when changing this name, don't use test*!\\ndef runtests():\\n    \\\"\\\"\\\"\\n    Run all mpmath tests and print output.\\n    \\\"\\\"\\\"\\n    import os.path\\n    from inspect import getsourcefile\\n    from .tests import runtests as tests\\n    testdir = os.path.dirname(os.path.abspath(getsourcefile(tests)))\\n    importdir = os.path.abspath(testdir + '/../..')\\n    tests.testit(importdir, testdir)\\n\\ndef doctests(filter=[]):\\n    import sys\\n    from timeit import default_timer as clock\\n    for i, arg in enumerate(sys.argv):\\n        if '__init__.py' in arg:\\n            filter = [sn for sn in sys.argv[i+1:] if not sn.startswith(\\\"-\\\")]\\n            break\\n    import doctest\\n    globs = globals().copy()\\n    for obj in globs: #sorted(globs.keys()):\\n        if filter:\\n            if not sum([pat in obj for pat in filter]):\\n                continue\\n        sys.stdout.write(str(obj) + \\\" \\\")\\n        sys.stdout.flush()\\n        t1 = clock()\\n        doctest.run_docstring_examples(globs[obj], {}, verbose=(\\\"-v\\\" in sys.argv))\\n        t2 = clock()\\n        print(round(t2-t1, 3))\\n\\nif __name__ == '__main__':\\n    doctests()\\n\\n\\n\\\"\\\"\\\"\\nLinear algebra\\n--------------\\n\\nLinear equations\\n................\\n\\nBasic linear algebra is implemented; you can for example solve the linear\\nequation system::\\n\\n      x + 2*y = -10\\n    3*x + 4*y =  10\\n\\nusing ``lu_solve``::\\n\\n    >>> from mpmath import *\\n    >>> mp.pretty = False\\n    >>> A = matrix([[1, 2], [3, 4]])\\n    >>> b = matrix([-10, 10])\\n    >>> x = lu_solve(A, b)\\n    >>> x\\n    matrix(\\n    [['30.0'],\\n     ['-20.0']])\\n\\nIf you don't trust the result, use ``residual`` to calculate the residual ||A*x-b||::\\n\\n    >>> residual(A, x, b)\\n    matrix(\\n    [['3.46944695195361e-18'],\\n     ['3.46944695195361e-18']])\\n    >>> str(eps)\\n    '2.22044604925031e-16'\\n\\nAs you can see, the solution is quite accurate. The error is caused by the\\ninaccuracy of the internal floating point arithmetic. Though, it's even smaller\\nthan the current machine epsilon, which basically means you can trust the\\nresult.\\n\\nIf you need more speed, use NumPy, or ``fp.lu_solve`` for a floating-point computation.\\n\\n    >>> fp.lu_solve(A, b)   # doctest: +ELLIPSIS\\n    matrix(...)\\n\\n``lu_solve`` accepts overdetermined systems. It is usually not possible to solve\\nsuch systems, so the residual is minimized instead. Internally this is done\\nusing Cholesky decomposition to compute a least squares approximation. This means\\nthat that ``lu_solve`` will square the errors. If you can't afford this, use\\n``qr_solve`` instead. It is twice as slow but more accurate, and it calculates\\nthe residual automatically.\\n\\n\\nMatrix factorization\\n....................\\n\\nThe function ``lu`` computes an explicit LU factorization of a matrix::\\n\\n    >>> P, L, U = lu(matrix([[0,2,3],[4,5,6],[7,8,9]]))\\n    >>> print(P)\\n    [0.0  0.0  1.0]\\n    [1.0  0.0  0.0]\\n    [0.0  1.0  0.0]\\n    >>> print(L)\\n    [              1.0                0.0  0.0]\\n    [              0.0                1.0  0.0]\\n    [0.571428571428571  0.214285714285714  1.0]\\n    >>> print(U)\\n    [7.0  8.0                9.0]\\n    [0.0  2.0                3.0]\\n    [0.0  0.0  0.214285714285714]\\n    >>> print(P.T*L*U)\\n    [0.0  2.0  3.0]\\n    [4.0  5.0  6.0]\\n    [7.0  8.0  9.0]\\n\\nInterval matrices\\n-----------------\\n\\nMatrices may contain interval elements. This allows one to perform\\nbasic linear algebra operations such as matrix multiplication\\nand equation solving with rigorous error bounds::\\n\\n    >>> a = iv.matrix([['0.1','0.3','1.0'],\\n    ...             ['7.1','5.5','4.8'],\\n    ...             ['3.2','4.4','5.6']])\\n    >>>\\n    >>> b = iv.matrix(['4','0.6','0.5'])\\n    >>> c = iv.lu_solve(a, b)\\n    >>> print(c)\\n    [   [5.2582327113062568605927528666, 5.25823271130625686059275702219]]\\n    [[-13.1550493962678375411635581388, -13.1550493962678375411635540152]]\\n    [  [7.42069154774972557628979076189, 7.42069154774972557628979190734]]\\n    >>> print(a*c)\\n    [  [3.99999999999999999999999844904, 4.00000000000000000000000155096]]\\n    [[0.599999999999999999999968898009, 0.600000000000000000000031763736]]\\n    [[0.499999999999999999999979320485, 0.500000000000000000000020679515]]\\n\\\"\\\"\\\"\\n\\n# TODO:\\n# *implement high-level qr()\\n# *test unitvector\\n# *iterative solving\\n\\nfrom copy import copy\\n\\nfrom ..libmp.backend import xrange\\n\\nclass LinearAlgebraMethods(object):\\n\\n    def LU_decomp(ctx, A, overwrite=False, use_cache=True):\\n        \\\"\\\"\\\"\\n        LU-factorization of a n*n matrix using the Gauss algorithm.\\n        Returns L and U in one matrix and the pivot indices.\\n\\n        Use overwrite to specify whether A will be overwritten with L and U.\\n        \\\"\\\"\\\"\\n        if not A.rows == A.cols:\\n            raise ValueError('need n*n matrix')\\n        # get from cache if possible\\n        if use_cache and isinstance(A, ctx.matrix) and A._LU:\\n            return A._LU\\n        if not overwrite:\\n            orig = A\\n            A = A.copy()\\n        tol = ctx.absmin(ctx.mnorm(A,1) * ctx.eps) # each pivot element has to be bigger\\n        n = A.rows\\n        p = [None]*(n - 1)\\n        for j in xrange(n - 1):\\n            # pivoting, choose max(abs(reciprocal row sum)*abs(pivot element))\\n            biggest = 0\\n            for k in xrange(j, n):\\n                s = ctx.fsum([ctx.absmin(A[k,l]) for l in xrange(j, n)])\\n                if ctx.absmin(s) <= tol:\\n                    raise ZeroDivisionError('matrix is numerically singular')\\n                current = 1/s * ctx.absmin(A[k,j])\\n                if current > biggest: # TODO: what if equal?\\n                    biggest = current\\n                    p[j] = k\\n            # swap rows according to p\\n            ctx.swap_row(A, j, p[j])\\n            if ctx.absmin(A[j,j]) <= tol:\\n                raise ZeroDivisionError('matrix is numerically singular')\\n            # calculate elimination factors and add rows\\n            for i in xrange(j + 1, n):\\n                A[i,j] /= A[j,j]\\n                for k in xrange(j + 1, n):\\n                    A[i,k] -= A[i,j]*A[j,k]\\n        if ctx.absmin(A[n - 1,n - 1]) <= tol:\\n            raise ZeroDivisionError('matrix is numerically singular')\\n        # cache decomposition\\n        if not overwrite and isinstance(orig, ctx.matrix):\\n            orig._LU = (A, p)\\n        return A, p\\n\\n    def L_solve(ctx, L, b, p=None):\\n        \\\"\\\"\\\"\\n        Solve the lower part of a LU factorized matrix for y.\\n        \\\"\\\"\\\"\\n        if L.rows != L.cols:\\n            raise RuntimeError(\\\"need n*n matrix\\\")\\n        n = L.rows\\n        if len(b) != n:\\n            raise ValueError(\\\"Value should be equal to n\\\")\\n        b = copy(b)\\n        if p: # swap b according to p\\n            for k in xrange(0, len(p)):\\n                ctx.swap_row(b, k, p[k])\\n        # solve\\n        for i in xrange(1, n):\\n            for j in xrange(i):\\n                b[i] -= L[i,j] * b[j]\\n        return b\\n\\n    def U_solve(ctx, U, y):\\n        \\\"\\\"\\\"\\n        Solve the upper part of a LU factorized matrix for x.\\n        \\\"\\\"\\\"\\n        if U.rows != U.cols:\\n            raise RuntimeError(\\\"need n*n matrix\\\")\\n        n = U.rows\\n        if len(y) != n:\\n            raise ValueError(\\\"Value should be equal to n\\\")\\n        x = copy(y)\\n        for i in xrange(n - 1, -1, -1):\\n            for j in xrange(i + 1, n):\\n                x[i] -= U[i,j] * x[j]\\n            x[i] /= U[i,i]\\n        return x\\n\\n    def lu_solve(ctx, A, b, **kwargs):\\n        \\\"\\\"\\\"\\n        Ax = b => x\\n\\n        Solve a determined or overdetermined linear equations system.\\n        Fast LU decomposition is used, which is less accurate than QR decomposition\\n        (especially for overdetermined systems), but it's twice as efficient.\\n        Use qr_solve if you want more precision or have to solve a very ill-\\n        conditioned system.\\n\\n        If you specify real=True, it does not check for overdeterminded complex\\n        systems.\\n        \\\"\\\"\\\"\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            # do not overwrite A nor b\\n            A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()\\n            if A.rows < A.cols:\\n                raise ValueError('cannot solve underdetermined system')\\n            if A.rows > A.cols:\\n                # use least-squares method if overdetermined\\n                # (this increases errors)\\n                AH = A.H\\n                A = AH * A\\n                b = AH * b\\n                if (kwargs.get('real', False) or\\n                    not sum(type(i) is ctx.mpc for i in A)):\\n                    # TODO: necessary to check also b?\\n                    x = ctx.cholesky_solve(A, b)\\n                else:\\n                    x = ctx.lu_solve(A, b)\\n            else:\\n                # LU factorization\\n                A, p = ctx.LU_decomp(A)\\n                b = ctx.L_solve(A, b, p)\\n                x = ctx.U_solve(A, b)\\n        finally:\\n            ctx.prec = prec\\n        return x\\n\\n    def improve_solution(ctx, A, x, b, maxsteps=1):\\n        \\\"\\\"\\\"\\n        Improve a solution to a linear equation system iteratively.\\n\\n        This re-uses the LU decomposition and is thus cheap.\\n        Usually 3 up to 4 iterations are giving the maximal improvement.\\n        \\\"\\\"\\\"\\n        if A.rows != A.cols:\\n            raise RuntimeError(\\\"need n*n matrix\\\") # TODO: really?\\n        for _ in xrange(maxsteps):\\n            r = ctx.residual(A, x, b)\\n            if ctx.norm(r, 2) < 10*ctx.eps:\\n                break\\n            # this uses cached LU decomposition and is thus cheap\\n            dx = ctx.lu_solve(A, -r)\\n            x += dx\\n        return x\\n\\n    def lu(ctx, A):\\n        \\\"\\\"\\\"\\n        A -> P, L, U\\n\\n        LU factorisation of a square matrix A. L is the lower, U the upper part.\\n        P is the permutation matrix indicating the row swaps.\\n\\n        P*A = L*U\\n\\n        If you need efficiency, use the low-level method LU_decomp instead, it's\\n        much more memory efficient.\\n        \\\"\\\"\\\"\\n        # get factorization\\n        A, p = ctx.LU_decomp(A)\\n        n = A.rows\\n        L = ctx.matrix(n)\\n        U = ctx.matrix(n)\\n        for i in xrange(n):\\n            for j in xrange(n):\\n                if i > j:\\n                    L[i,j] = A[i,j]\\n                elif i == j:\\n                    L[i,j] = 1\\n                    U[i,j] = A[i,j]\\n                else:\\n                    U[i,j] = A[i,j]\\n        # calculate permutation matrix\\n        P = ctx.eye(n)\\n        for k in xrange(len(p)):\\n            ctx.swap_row(P, k, p[k])\\n        return P, L, U\\n\\n    def unitvector(ctx, n, i):\\n        \\\"\\\"\\\"\\n        Return the i-th n-dimensional unit vector.\\n        \\\"\\\"\\\"\\n        assert 0 < i <= n, 'this unit vector does not exist'\\n        return [ctx.zero]*(i-1) + [ctx.one] + [ctx.zero]*(n-i)\\n\\n    def inverse(ctx, A, **kwargs):\\n        \\\"\\\"\\\"\\n        Calculate the inverse of a matrix.\\n\\n        If you want to solve an equation system Ax = b, it's recommended to use\\n        solve(A, b) instead, it's about 3 times more efficient.\\n        \\\"\\\"\\\"\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            # do not overwrite A\\n            A = ctx.matrix(A, **kwargs).copy()\\n            n = A.rows\\n            # get LU factorisation\\n            A, p = ctx.LU_decomp(A)\\n            cols = []\\n            # calculate unit vectors and solve corresponding system to get columns\\n            for i in xrange(1, n + 1):\\n                e = ctx.unitvector(n, i)\\n                y = ctx.L_solve(A, e, p)\\n                cols.append(ctx.U_solve(A, y))\\n            # convert columns to matrix\\n            inv = []\\n            for i in xrange(n):\\n                row = []\\n                for j in xrange(n):\\n                    row.append(cols[j][i])\\n                inv.append(row)\\n            result = ctx.matrix(inv, **kwargs)\\n        finally:\\n            ctx.prec = prec\\n        return result\\n\\n    def householder(ctx, A):\\n        \\\"\\\"\\\"\\n        (A|b) -> H, p, x, res\\n\\n        (A|b) is the coefficient matrix with left hand side of an optionally\\n        overdetermined linear equation system.\\n        H and p contain all information about the transformation matrices.\\n        x is the solution, res the residual.\\n        \\\"\\\"\\\"\\n        if not isinstance(A, ctx.matrix):\\n            raise TypeError(\\\"A should be a type of ctx.matrix\\\")\\n        m = A.rows\\n        n = A.cols\\n        if m < n - 1:\\n            raise RuntimeError(\\\"Columns should not be less than rows\\\")\\n        # calculate Householder matrix\\n        p = []\\n        for j in xrange(0, n - 1):\\n            s = ctx.fsum(abs(A[i,j])**2 for i in xrange(j, m))\\n            if not abs(s) > ctx.eps:\\n                raise ValueError('matrix is numerically singular')\\n            p.append(-ctx.sign(ctx.re(A[j,j])) * ctx.sqrt(s))\\n            kappa = ctx.one / (s - p[j] * A[j,j])\\n            A[j,j] -= p[j]\\n            for k in xrange(j+1, n):\\n                y = ctx.fsum(ctx.conj(A[i,j]) * A[i,k] for i in xrange(j, m)) * kappa\\n                for i in xrange(j, m):\\n                    A[i,k] -= A[i,j] * y\\n        # solve Rx = c1\\n        x = [A[i,n - 1] for i in xrange(n - 1)]\\n        for i in xrange(n - 2, -1, -1):\\n            x[i] -= ctx.fsum(A[i,j] * x[j] for j in xrange(i + 1, n - 1))\\n            x[i] /= p[i]\\n        # calculate residual\\n        if not m == n - 1:\\n            r = [A[m-1-i, n-1] for i in xrange(m - n + 1)]\\n        else:\\n            # determined system, residual should be 0\\n            r = [0]*m # maybe a bad idea, changing r[i] will change all elements\\n        return A, p, x, r\\n\\n    #def qr(ctx, A):\\n    #    \\\"\\\"\\\"\\n    #    A -> Q, R\\n    #\\n    #    QR factorisation of a square matrix A using Householder decomposition.\\n    #    Q is orthogonal, this leads to very few numerical errors.\\n    #\\n    #    A = Q*R\\n    #    \\\"\\\"\\\"\\n    #    H, p, x, res = householder(A)\\n    # TODO: implement this\\n\\n    def residual(ctx, A, x, b, **kwargs):\\n        \\\"\\\"\\\"\\n        Calculate the residual of a solution to a linear equation system.\\n\\n        r = A*x - b for A*x = b\\n        \\\"\\\"\\\"\\n        oldprec = ctx.prec\\n        try:\\n            ctx.prec *= 2\\n            A, x, b = ctx.matrix(A, **kwargs), ctx.matrix(x, **kwargs), ctx.matrix(b, **kwargs)\\n            return A*x - b\\n        finally:\\n            ctx.prec = oldprec\\n\\n    def qr_solve(ctx, A, b, norm=None, **kwargs):\\n        \\\"\\\"\\\"\\n        Ax = b => x, ||Ax - b||\\n\\n        Solve a determined or overdetermined linear equations system and\\n        calculate the norm of the residual (error).\\n        QR decomposition using Householder factorization is applied, which gives very\\n        accurate results even for ill-conditioned matrices. qr_solve is twice as\\n        efficient.\\n        \\\"\\\"\\\"\\n        if norm is None:\\n            norm = ctx.norm\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            # do not overwrite A nor b\\n            A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()\\n            if A.rows < A.cols:\\n                raise ValueError('cannot solve underdetermined system')\\n            H, p, x, r = ctx.householder(ctx.extend(A, b))\\n            res = ctx.norm(r)\\n            # calculate residual \\\"manually\\\" for determined systems\\n            if res == 0:\\n                res = ctx.norm(ctx.residual(A, x, b))\\n            return ctx.matrix(x, **kwargs), res\\n        finally:\\n            ctx.prec = prec\\n\\n    def cholesky(ctx, A, tol=None):\\n        r\\\"\\\"\\\"\\n        Cholesky decomposition of a symmetric positive-definite matrix `A`.\\n        Returns a lower triangular matrix `L` such that `A = L \\\\times L^T`.\\n        More generally, for a complex Hermitian positive-definite matrix,\\n        a Cholesky decomposition satisfying `A = L \\\\times L^H` is returned.\\n\\n        The Cholesky decomposition can be used to solve linear equation\\n        systems twice as efficiently as LU decomposition, or to\\n        test whether `A` is positive-definite.\\n\\n        The optional parameter ``tol`` determines the tolerance for\\n        verifying positive-definiteness.\\n\\n        **Examples**\\n\\n        Cholesky decomposition of a positive-definite symmetric matrix::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 25; mp.pretty = True\\n            >>> A = eye(3) + hilbert(3)\\n            >>> nprint(A)\\n            [     2.0      0.5  0.333333]\\n            [     0.5  1.33333      0.25]\\n            [0.333333     0.25       1.2]\\n            >>> L = cholesky(A)\\n            >>> nprint(L)\\n            [ 1.41421      0.0      0.0]\\n            [0.353553  1.09924      0.0]\\n            [0.235702  0.15162  1.05899]\\n            >>> chop(A - L*L.T)\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n\\n        Cholesky decomposition of a Hermitian matrix::\\n\\n            >>> A = eye(3) + matrix([[0,0.25j,-0.5j],[-0.25j,0,0],[0.5j,0,0]])\\n            >>> L = cholesky(A)\\n            >>> nprint(L)\\n            [          1.0                0.0                0.0]\\n            [(0.0 - 0.25j)  (0.968246 + 0.0j)                0.0]\\n            [ (0.0 + 0.5j)  (0.129099 + 0.0j)  (0.856349 + 0.0j)]\\n            >>> chop(A - L*L.H)\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n\\n        Attempted Cholesky decomposition of a matrix that is not positive\\n        definite::\\n\\n            >>> A = -eye(3) + hilbert(3)\\n            >>> L = cholesky(A)\\n            Traceback (most recent call last):\\n              ...\\n            ValueError: matrix is not positive-definite\\n\\n        **References**\\n\\n        1. [Wikipedia]_ http://en.wikipedia.org/wiki/Cholesky_decomposition\\n\\n        \\\"\\\"\\\"\\n        if not isinstance(A, ctx.matrix):\\n            raise RuntimeError(\\\"A should be a type of ctx.matrix\\\")\\n        if not A.rows == A.cols:\\n            raise ValueError('need n*n matrix')\\n        if tol is None:\\n            tol = +ctx.eps\\n        n = A.rows\\n        L = ctx.matrix(n)\\n        for j in xrange(n):\\n            c = ctx.re(A[j,j])\\n            if abs(c-A[j,j]) > tol:\\n                raise ValueError('matrix is not Hermitian')\\n            s = c - ctx.fsum((L[j,k] for k in xrange(j)),\\n                absolute=True, squared=True)\\n            if s < tol:\\n                raise ValueError('matrix is not positive-definite')\\n            L[j,j] = ctx.sqrt(s)\\n            for i in xrange(j, n):\\n                it1 = (L[i,k] for k in xrange(j))\\n                it2 = (L[j,k] for k in xrange(j))\\n                t = ctx.fdot(it1, it2, conjugate=True)\\n                L[i,j] = (A[i,j] - t) / L[j,j]\\n        return L\\n\\n    def cholesky_solve(ctx, A, b, **kwargs):\\n        \\\"\\\"\\\"\\n        Ax = b => x\\n\\n        Solve a symmetric positive-definite linear equation system.\\n        This is twice as efficient as lu_solve.\\n\\n        Typical use cases:\\n        * A.T*A\\n        * Hessian matrix\\n        * differential equations\\n        \\\"\\\"\\\"\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            # do not overwrite A nor b\\n            A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()\\n            if A.rows !=  A.cols:\\n                raise ValueError('can only solve determined system')\\n            # Cholesky factorization\\n            L = ctx.cholesky(A)\\n            # solve\\n            n = L.rows\\n            if len(b) != n:\\n                raise ValueError(\\\"Value should be equal to n\\\")\\n            for i in xrange(n):\\n                b[i] -= ctx.fsum(L[i,j] * b[j] for j in xrange(i))\\n                b[i] /= L[i,i]\\n            x = ctx.U_solve(L.T, b)\\n            return x\\n        finally:\\n            ctx.prec = prec\\n\\n    def det(ctx, A):\\n        \\\"\\\"\\\"\\n        Calculate the determinant of a matrix.\\n        \\\"\\\"\\\"\\n        prec = ctx.prec\\n        try:\\n            # do not overwrite A\\n            A = ctx.matrix(A).copy()\\n            # use LU factorization to calculate determinant\\n            try:\\n                R, p = ctx.LU_decomp(A)\\n            except ZeroDivisionError:\\n                return 0\\n            z = 1\\n            for i, e in enumerate(p):\\n                if i != e:\\n                    z *= -1\\n            for i in xrange(A.rows):\\n                z *= R[i,i]\\n            return z\\n        finally:\\n            ctx.prec = prec\\n\\n    def cond(ctx, A, norm=None):\\n        \\\"\\\"\\\"\\n        Calculate the condition number of a matrix using a specified matrix norm.\\n\\n        The condition number estimates the sensitivity of a matrix to errors.\\n        Example: small input errors for ill-conditioned coefficient matrices\\n        alter the solution of the system dramatically.\\n\\n        For ill-conditioned matrices it's recommended to use qr_solve() instead\\n        of lu_solve(). This does not help with input errors however, it just avoids\\n        to add additional errors.\\n\\n        Definition:    cond(A) = ||A|| * ||A**-1||\\n        \\\"\\\"\\\"\\n        if norm is None:\\n            norm = lambda x: ctx.mnorm(x,1)\\n        return norm(A) * norm(ctx.inverse(A))\\n\\n    def lu_solve_mat(ctx, a, b):\\n        \\\"\\\"\\\"Solve a * x = b  where a and b are matrices.\\\"\\\"\\\"\\n        r = ctx.matrix(a.rows, b.cols)\\n        for i in range(b.cols):\\n            c = ctx.lu_solve(a, b.column(i))\\n            for j in range(len(c)):\\n                r[j, i] = c[j]\\n        return r\\n\\n    def qr(ctx, A, mode = 'full', edps = 10):\\n        \\\"\\\"\\\"\\n        Compute a QR factorization $A = QR$ where\\n        A is an m x n matrix of real or complex numbers where m >= n\\n\\n        mode has following meanings:\\n        (1) mode = 'raw' returns two matrixes (A, tau) in the\\n            internal format used by LAPACK\\n        (2) mode = 'skinny' returns the leading n columns of Q\\n            and n rows of R\\n        (3) Any other value returns the leading m columns of Q\\n            and m rows of R\\n\\n        edps is the increase in mp precision used for calculations\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15\\n            >>> mp.pretty = True\\n            >>> A = matrix([[1, 2], [3, 4], [1, 1]])\\n            >>> Q, R = qr(A)\\n            >>> Q\\n            [-0.301511344577764   0.861640436855329   0.408248290463863]\\n            [-0.904534033733291  -0.123091490979333  -0.408248290463863]\\n            [-0.301511344577764  -0.492365963917331   0.816496580927726]\\n            >>> R\\n            [-3.3166247903554  -4.52267016866645]\\n            [             0.0  0.738548945875996]\\n            [             0.0                0.0]\\n            >>> Q * R\\n            [1.0  2.0]\\n            [3.0  4.0]\\n            [1.0  1.0]\\n            >>> chop(Q.T * Q)\\n            [1.0  0.0  0.0]\\n            [0.0  1.0  0.0]\\n            [0.0  0.0  1.0]\\n            >>> B = matrix([[1+0j, 2-3j], [3+j, 4+5j]])\\n            >>> Q, R = qr(B)\\n            >>> nprint(Q)\\n            [     (-0.301511 + 0.0j)   (0.0695795 - 0.95092j)]\\n            [(-0.904534 - 0.301511j)  (-0.115966 + 0.278318j)]\\n            >>> nprint(R)\\n            [(-3.31662 + 0.0j)  (-5.72872 - 2.41209j)]\\n            [              0.0       (3.91965 + 0.0j)]\\n            >>> Q * R\\n            [(1.0 + 0.0j)  (2.0 - 3.0j)]\\n            [(3.0 + 1.0j)  (4.0 + 5.0j)]\\n            >>> chop(Q.T * Q.conjugate())\\n            [1.0  0.0]\\n            [0.0  1.0]\\n\\n        \\\"\\\"\\\"\\n\\n        # check values before continuing\\n        assert isinstance(A, ctx.matrix)\\n        m = A.rows\\n        n = A.cols\\n        assert n >= 0\\n        assert m >= n\\n        assert edps >= 0\\n\\n        # check for complex data type\\n        cmplx = any(type(x) is ctx.mpc for x in A)\\n\\n        # temporarily increase the precision and initialize\\n        with ctx.extradps(edps):\\n            tau = ctx.matrix(n,1)\\n            A = A.copy()\\n\\n            # ---------------\\n            # FACTOR MATRIX A\\n            # ---------------\\n            if cmplx:\\n                one = ctx.mpc('1.0', '0.0')\\n                zero = ctx.mpc('0.0', '0.0')\\n                rzero = ctx.mpf('0.0')\\n\\n                # main loop to factor A (complex)\\n                for j in xrange(0, n):\\n                    alpha = A[j,j]\\n                    alphr = ctx.re(alpha)\\n                    alphi = ctx.im(alpha)\\n\\n                    if (m-j) >= 2:\\n                        xnorm = ctx.fsum( A[i,j]*ctx.conj(A[i,j]) for i in xrange(j+1, m) )\\n                        xnorm = ctx.re( ctx.sqrt(xnorm) )\\n                    else:\\n                        xnorm = rzero\\n\\n                    if (xnorm == rzero) and (alphi == rzero):\\n                        tau[j] = zero\\n                        continue\\n\\n                    if alphr < rzero:\\n                        beta = ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)\\n                    else:\\n                        beta = -ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)\\n\\n                    tau[j] = ctx.mpc( (beta - alphr) / beta, -alphi / beta )\\n                    t = -ctx.conj(tau[j])\\n                    za = one / (alpha - beta)\\n\\n                    for i in xrange(j+1, m):\\n                        A[i,j] *= za\\n\\n                    A[j,j] = one\\n                    for k in xrange(j+1, n):\\n                        y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j, m))\\n                        temp = t * ctx.conj(y)\\n                        for i in xrange(j, m):\\n                            A[i,k] += A[i,j] * temp\\n\\n                    A[j,j] = ctx.mpc(beta, '0.0')\\n            else:\\n                one = ctx.mpf('1.0')\\n                zero = ctx.mpf('0.0')\\n\\n                # main loop to factor A (real)\\n                for j in xrange(0, n):\\n                    alpha = A[j,j]\\n\\n                    if (m-j) > 2:\\n                        xnorm = ctx.fsum( (A[i,j])**2 for i in xrange(j+1, m) )\\n                        xnorm = ctx.sqrt(xnorm)\\n                    elif (m-j) == 2:\\n                        xnorm = abs( A[m-1,j] )\\n                    else:\\n                        xnorm = zero\\n\\n                    if xnorm == zero:\\n                        tau[j] = zero\\n                        continue\\n\\n                    if alpha < zero:\\n                        beta = ctx.sqrt(alpha**2 + xnorm**2)\\n                    else:\\n                        beta = -ctx.sqrt(alpha**2 + xnorm**2)\\n\\n                    tau[j] = (beta - alpha) / beta\\n                    t = -tau[j]\\n                    da = one / (alpha - beta)\\n\\n                    for i in xrange(j+1, m):\\n                        A[i,j] *= da\\n\\n                    A[j,j] = one\\n                    for k in xrange(j+1, n):\\n                        y = ctx.fsum( A[i,j] * A[i,k] for i in xrange(j, m) )\\n                        temp = t * y\\n                        for i in xrange(j,m):\\n                            A[i,k] += A[i,j] * temp\\n\\n                    A[j,j] = beta\\n\\n            # return factorization in same internal format as LAPACK\\n            if (mode == 'raw') or (mode == 'RAW'):\\n                return A, tau\\n\\n            # ----------------------------------\\n            # FORM Q USING BACKWARD ACCUMULATION\\n            # ----------------------------------\\n\\n            # form R before the values are overwritten\\n            R = A.copy()\\n            for j in xrange(0, n):\\n                for i in xrange(j+1, m):\\n                    R[i,j] = zero\\n\\n            # set the value of p (number of columns of Q to return)\\n            p = m\\n            if (mode == 'skinny') or (mode == 'SKINNY'):\\n                p = n\\n\\n            # add columns to A if needed and initialize\\n            A.cols += (p-n)\\n            for j in xrange(0, p):\\n                A[j,j] = one\\n                for i in xrange(0, j):\\n                    A[i,j] = zero\\n\\n            # main loop to form Q\\n            for j in xrange(n-1, -1, -1):\\n                t = -tau[j]\\n                A[j,j] += t\\n\\n                for k in xrange(j+1, p):\\n                    if cmplx:\\n                        y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j+1, m))\\n                        temp = t * ctx.conj(y)\\n                    else:\\n                        y = ctx.fsum(A[i,j] * A[i,k] for i in xrange(j+1, m))\\n                        temp = t * y\\n                    A[j,k] = temp\\n                    for i in xrange(j+1, m):\\n                        A[i,k] += A[i,j] * temp\\n\\n                for i in xrange(j+1, m):\\n                    A[i, j] *= t\\n\\n            return A, R[0:p,0:n]\\n\\n        # ------------------\\n        # END OF FUNCTION QR\\n        # ------------------\\n\\n\\n#!/usr/bin/python\\n# -*- coding: utf-8 -*-\\n\\n##################################################################################################\\n#     module for the eigenvalue problem\\n#       Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)\\n#\\n# todo:\\n#  - implement balancing\\n#  - agressive early deflation\\n#\\n##################################################################################################\\n\\n\\\"\\\"\\\"\\nThe eigenvalue problem\\n----------------------\\n\\nThis file contains routines for the eigenvalue problem.\\n\\nhigh level routines:\\n\\n  hessenberg : reduction of a real or complex square matrix to upper Hessenberg form\\n  schur : reduction of a real or complex square matrix to upper Schur form\\n  eig : eigenvalues and eigenvectors of a real or complex square matrix\\n\\nlow level routines:\\n\\n  hessenberg_reduce_0 : reduction of a real or complex square matrix to upper Hessenberg form\\n  hessenberg_reduce_1 : auxiliary routine to hessenberg_reduce_0\\n  qr_step : a single implicitly shifted QR step for an upper Hessenberg matrix\\n  hessenberg_qr : Schur decomposition of an upper Hessenberg matrix\\n  eig_tr_r : right eigenvectors of an upper triangular matrix\\n  eig_tr_l : left  eigenvectors of an upper triangular matrix\\n\\\"\\\"\\\"\\n\\nfrom ..libmp.backend import xrange\\n\\nclass Eigen(object):\\n    pass\\n\\ndef defun(f):\\n    setattr(Eigen, f.__name__, f)\\n    return f\\n\\ndef hessenberg_reduce_0(ctx, A, T):\\n    \\\"\\\"\\\"\\n    This routine computes the (upper) Hessenberg decomposition of a square matrix A.\\n    Given A, an unitary matrix Q is calculated such that\\n\\n               Q' A Q = H              and             Q' Q = Q Q' = 1\\n\\n    where H is an upper Hessenberg matrix, meaning that it only contains zeros\\n    below the first subdiagonal. Here ' denotes the hermitian transpose (i.e.\\n    transposition and conjugation).\\n\\n    parameters:\\n      A         (input/output) On input, A contains the square matrix A of\\n                dimension (n,n). On output, A contains a compressed representation\\n                of Q and H.\\n      T         (output) An array of length n containing the first elements of\\n                the Householder reflectors.\\n    \\\"\\\"\\\"\\n\\n    # internally we work with householder reflections from the right.\\n    # let u be a row vector (i.e. u[i]=A[i,:i]). then\\n    # Q is build up by reflectors of the type (1-v'v) where v is a suitable\\n    # modification of u. these reflectors are applyed to A from the right.\\n    # because we work with reflectors from the right we have to start with\\n    # the bottom row of A and work then upwards (this corresponds to\\n    # some kind of RQ decomposition).\\n    # the first part of the vectors v (i.e. A[i,:(i-1)]) are stored as row vectors\\n    # in the lower left part of A (excluding the diagonal and subdiagonal).\\n    # the last entry of v is stored in T.\\n    # the upper right part of A (including diagonal and subdiagonal) becomes H.\\n\\n\\n    n = A.rows\\n    if n <= 2: return\\n\\n    for i in xrange(n-1, 1, -1):\\n\\n        # scale the vector\\n\\n        scale = 0\\n        for k in xrange(0, i):\\n            scale += abs(ctx.re(A[i,k])) + abs(ctx.im(A[i,k]))\\n\\n        scale_inv = 0\\n        if scale != 0:\\n            scale_inv = 1 / scale\\n\\n        if scale == 0 or ctx.isinf(scale_inv):\\n            # sadly there are floating point numbers not equal to zero whose reciprocal is infinity\\n            T[i] = 0\\n            A[i,i-1] = 0\\n            continue\\n\\n        # calculate parameters for housholder transformation\\n\\n        H = 0\\n        for k in xrange(0, i):\\n            A[i,k] *= scale_inv\\n            rr = ctx.re(A[i,k])\\n            ii = ctx.im(A[i,k])\\n            H += rr * rr + ii * ii\\n\\n        F = A[i,i-1]\\n        f = abs(F)\\n        G = ctx.sqrt(H)\\n        A[i,i-1] = - G * scale\\n\\n        if f == 0:\\n            T[i] = G\\n        else:\\n            ff = F / f\\n            T[i] = F + G * ff\\n            A[i,i-1] *= ff\\n\\n        H += G * f\\n        H = 1 / ctx.sqrt(H)\\n\\n        T[i] *= H\\n        for k in xrange(0, i - 1):\\n            A[i,k] *= H\\n\\n        for j in xrange(0, i):\\n            # apply housholder transformation (from right)\\n\\n            G = ctx.conj(T[i]) * A[j,i-1]\\n            for k in xrange(0, i-1):\\n                G += ctx.conj(A[i,k]) * A[j,k]\\n\\n            A[j,i-1] -= G * T[i]\\n            for k in xrange(0, i-1):\\n                A[j,k] -= G * A[i,k]\\n\\n        for j in xrange(0, n):\\n            # apply housholder transformation (from left)\\n\\n            G = T[i] * A[i-1,j]\\n            for k in xrange(0, i-1):\\n                G += A[i,k] * A[k,j]\\n\\n            A[i-1,j] -= G * ctx.conj(T[i])\\n            for k in xrange(0, i-1):\\n                A[k,j] -= G * ctx.conj(A[i,k])\\n\\n\\n\\ndef hessenberg_reduce_1(ctx, A, T):\\n    \\\"\\\"\\\"\\n    This routine forms the unitary matrix Q described in hessenberg_reduce_0.\\n\\n    parameters:\\n      A    (input/output) On input, A is the same matrix as delivered by\\n           hessenberg_reduce_0. On output, A is set to Q.\\n\\n      T    (input) On input, T is the same array as delivered by hessenberg_reduce_0.\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    if n == 1:\\n        A[0,0] = 1\\n        return\\n\\n    A[0,0] = A[1,1] = 1\\n    A[0,1] = A[1,0] = 0\\n\\n    for i in xrange(2, n):\\n        if T[i] != 0:\\n\\n            for j in xrange(0, i):\\n                G = T[i] * A[i-1,j]\\n                for k in xrange(0, i-1):\\n                    G += A[i,k] * A[k,j]\\n\\n                A[i-1,j] -= G * ctx.conj(T[i])\\n                for k in xrange(0, i-1):\\n                    A[k,j] -= G * ctx.conj(A[i,k])\\n\\n        A[i,i] = 1\\n        for j in xrange(0, i):\\n            A[j,i] = A[i,j] = 0\\n\\n\\n\\n@defun\\ndef hessenberg(ctx, A, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine computes the Hessenberg decomposition of a square matrix A.\\n    Given A, an unitary matrix Q is determined such that\\n\\n          Q' A Q = H                and               Q' Q = Q Q' = 1\\n\\n    where H is an upper right Hessenberg matrix. Here ' denotes the hermitian\\n    transpose (i.e. transposition and conjugation).\\n\\n    input:\\n      A            : a real or complex square matrix\\n      overwrite_a  : if true, allows modification of A which may improve\\n                     performance. if false, A is not modified.\\n\\n    output:\\n      Q : an unitary matrix\\n      H : an upper right Hessenberg matrix\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])\\n      >>> Q, H = mp.hessenberg(A)\\n      >>> mp.nprint(H, 3) # doctest:+SKIP\\n      [  3.15  2.23  4.44]\\n      [-0.769  4.85  3.05]\\n      [   0.0  3.61   7.0]\\n      >>> print(mp.chop(A - Q * H * Q.transpose_conj()))\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n\\n    return value:   (Q, H)\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    if n == 1:\\n        return (ctx.matrix([[1]]), A)\\n\\n    if not overwrite_a:\\n        A = A.copy()\\n\\n    T = ctx.matrix(n, 1)\\n\\n    hessenberg_reduce_0(ctx, A, T)\\n    Q = A.copy()\\n    hessenberg_reduce_1(ctx, Q, T)\\n\\n    for x in xrange(n):\\n        for y in xrange(x+2, n):\\n            A[y,x] = 0\\n\\n    return Q, A\\n\\n\\n###########################################################################\\n\\n\\ndef qr_step(ctx, n0, n1, A, Q, shift):\\n    \\\"\\\"\\\"\\n    This subroutine executes a single implicitly shifted QR step applied to an\\n    upper Hessenberg matrix A. Given A and shift as input, first an QR\\n    decomposition is calculated:\\n\\n      Q R = A - shift * 1 .\\n\\n    The output is then following matrix:\\n\\n      R Q + shift * 1\\n\\n    parameters:\\n      n0, n1    (input) Two integers which specify the submatrix A[n0:n1,n0:n1]\\n                on which this subroutine operators. The subdiagonal elements\\n                to the left and below this submatrix must be deflated (i.e. zero).\\n                following restriction is imposed: n1>=n0+2\\n      A         (input/output) On input, A is an upper Hessenberg matrix.\\n                On output, A is replaced by \\\"R Q + shift * 1\\\"\\n      Q         (input/output) The parameter Q is multiplied by the unitary matrix\\n                Q arising from the QR decomposition. Q can also be false, in which\\n                case the unitary matrix Q is not computated.\\n      shift     (input) a complex number specifying the shift. idealy close to an\\n                eigenvalue of the bottemmost part of the submatrix A[n0:n1,n0:n1].\\n\\n    references:\\n      Stoer, Bulirsch - Introduction to Numerical Analysis.\\n      Kresser : Numerical Methods for General and Structured Eigenvalue Problems\\n    \\\"\\\"\\\"\\n\\n    # implicitly shifted and bulge chasing is explained at p.398/399 in \\\"Stoer, Bulirsch - Introduction to Numerical Analysis\\\"\\n    # for bulge chasing see also \\\"Watkins - The Matrix Eigenvalue Problem\\\" sec.4.5,p.173\\n\\n    # the Givens rotation we used is determined as follows: let c,s be two complex\\n    # numbers. then we have following relation:\\n    #\\n    #     v = sqrt(|c|^2 + |s|^2)\\n    #\\n    #     1/v [ c~  s~]  [c] = [v]\\n    #         [-s   c ]  [s]   [0]\\n    #\\n    # the matrix on the left is our Givens rotation.\\n\\n    n = A.rows\\n\\n    # first step\\n\\n    # calculate givens rotation\\n    c = A[n0  ,n0] - shift\\n    s = A[n0+1,n0]\\n\\n    v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s)))\\n\\n    if v == 0:\\n        v = 1\\n        c = 1\\n        s = 0\\n    else:\\n        c /= v\\n        s /= v\\n\\n    cc = ctx.conj(c)\\n    cs = ctx.conj(s)\\n\\n    for k in xrange(n0, n):\\n        # apply givens rotation from the left\\n        x = A[n0  ,k]\\n        y = A[n0+1,k]\\n        A[n0  ,k] = cc * x + cs * y\\n        A[n0+1,k] = c * y - s * x\\n\\n    for k in xrange(min(n1, n0+3)):\\n        # apply givens rotation from the right\\n        x = A[k,n0  ]\\n        y = A[k,n0+1]\\n        A[k,n0  ] = c * x + s * y\\n        A[k,n0+1] = cc * y - cs * x\\n\\n    if not isinstance(Q, bool):\\n        for k in xrange(n):\\n            # eigenvectors\\n            x = Q[k,n0  ]\\n            y = Q[k,n0+1]\\n            Q[k,n0  ] = c * x + s * y\\n            Q[k,n0+1] = cc * y - cs * x\\n\\n    # chase the bulge\\n\\n    for j in xrange(n0, n1 - 2):\\n        # calculate givens rotation\\n\\n        c = A[j+1,j]\\n        s = A[j+2,j]\\n\\n        v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s)))\\n\\n        if v == 0:\\n            A[j+1,j] = 0\\n            v = 1\\n            c = 1\\n            s = 0\\n        else:\\n            A[j+1,j] = v\\n            c /= v\\n            s /= v\\n\\n        A[j+2,j] = 0\\n\\n        cc = ctx.conj(c)\\n        cs = ctx.conj(s)\\n\\n        for k in xrange(j+1, n):\\n            # apply givens rotation from the left\\n            x = A[j+1,k]\\n            y = A[j+2,k]\\n            A[j+1,k] = cc * x + cs * y\\n            A[j+2,k] = c * y - s * x\\n\\n        for k in xrange(0, min(n1, j+4)):\\n            # apply givens rotation from the right\\n            x = A[k,j+1]\\n            y = A[k,j+2]\\n            A[k,j+1] = c * x + s * y\\n            A[k,j+2] = cc * y - cs * x\\n\\n        if not isinstance(Q, bool):\\n            for k in xrange(0, n):\\n                # eigenvectors\\n                x = Q[k,j+1]\\n                y = Q[k,j+2]\\n                Q[k,j+1] = c * x + s * y\\n                Q[k,j+2] = cc * y - cs * x\\n\\n\\n\\ndef hessenberg_qr(ctx, A, Q):\\n    \\\"\\\"\\\"\\n    This routine computes the Schur decomposition of an upper Hessenberg matrix A.\\n    Given A, an unitary matrix Q is determined such that\\n\\n          Q' A Q = R                   and                  Q' Q = Q Q' = 1\\n\\n    where R is an upper right triangular matrix. Here ' denotes the hermitian\\n    transpose (i.e. transposition and conjugation).\\n\\n    parameters:\\n      A         (input/output) On input, A contains an upper Hessenberg matrix.\\n                On output, A is replace by the upper right triangluar matrix R.\\n\\n      Q         (input/output) The parameter Q is multiplied by the unitary\\n                matrix Q arising from the Schur decomposition. Q can also be\\n                false, in which case the unitary matrix Q is not computated.\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    norm = 0\\n    for x in xrange(n):\\n        for y in xrange(min(x+2, n)):\\n            norm += ctx.re(A[y,x]) ** 2 + ctx.im(A[y,x]) ** 2\\n    norm = ctx.sqrt(norm) / n\\n\\n    if norm == 0:\\n        return\\n\\n    n0 = 0\\n    n1 = n\\n\\n    eps = ctx.eps / (100 * n)\\n    maxits = ctx.dps * 4\\n\\n    its = totalits = 0\\n\\n    while 1:\\n        # kressner p.32 algo 3\\n        # the active submatrix is A[n0:n1,n0:n1]\\n\\n        k = n0\\n\\n        while k + 1 < n1:\\n            s = abs(ctx.re(A[k,k])) + abs(ctx.im(A[k,k])) + abs(ctx.re(A[k+1,k+1])) + abs(ctx.im(A[k+1,k+1]))\\n            if s < eps * norm:\\n                s = norm\\n            if abs(A[k+1,k]) < eps * s:\\n                break\\n            k += 1\\n\\n        if k + 1 < n1:\\n            # deflation found at position (k+1, k)\\n\\n            A[k+1,k] = 0\\n            n0 = k + 1\\n\\n            its = 0\\n\\n            if n0 + 1 >= n1:\\n                # block of size at most two has converged\\n                n0 = 0\\n                n1 = k + 1\\n                if n1 < 2:\\n                    # QR algorithm has converged\\n                    return\\n        else:\\n            if (its % 30) == 10:\\n                # exceptional shift\\n                shift = A[n1-1,n1-2]\\n            elif (its % 30) == 20:\\n                # exceptional shift\\n                shift = abs(A[n1-1,n1-2])\\n            elif (its % 30) == 29:\\n                # exceptional shift\\n                shift = norm\\n            else:\\n                #    A = [ a b ]       det(x-A)=x*x-x*tr(A)+det(A)\\n                #        [ c d ]\\n                #\\n                # eigenvalues bad:   (tr(A)+sqrt((tr(A))**2-4*det(A)))/2\\n                #     bad because of cancellation if |c| is small and |a-d| is small, too.\\n                #\\n                # eigenvalues good:     (a+d+sqrt((a-d)**2+4*b*c))/2\\n\\n                t =  A[n1-2,n1-2] + A[n1-1,n1-1]\\n                s = (A[n1-1,n1-1] - A[n1-2,n1-2]) ** 2 + 4 * A[n1-1,n1-2] * A[n1-2,n1-1]\\n                if ctx.re(s) > 0:\\n                    s = ctx.sqrt(s)\\n                else:\\n                    s = ctx.sqrt(-s) * 1j\\n                a = (t + s) / 2\\n                b = (t - s) / 2\\n                if abs(A[n1-1,n1-1] - a) > abs(A[n1-1,n1-1] - b):\\n                    shift = b\\n                else:\\n                    shift = a\\n\\n            its += 1\\n            totalits += 1\\n\\n            qr_step(ctx, n0, n1, A, Q, shift)\\n\\n            if its > maxits:\\n                raise RuntimeError(\\\"qr: failed to converge after %d steps\\\" % its)\\n\\n\\n@defun\\ndef schur(ctx, A, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine computes the Schur decomposition of a square matrix A.\\n    Given A, an unitary matrix Q is determined such that\\n\\n          Q' A Q = R                and               Q' Q = Q Q' = 1\\n\\n    where R is an upper right triangular matrix. Here ' denotes the\\n    hermitian transpose (i.e. transposition and conjugation).\\n\\n    input:\\n      A            : a real or complex square matrix\\n      overwrite_a  : if true, allows modification of A which may improve\\n                     performance. if false, A is not modified.\\n\\n    output:\\n      Q : an unitary matrix\\n      R : an upper right triangular matrix\\n\\n    return value:   (Q, R)\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])\\n      >>> Q, R = mp.schur(A)\\n      >>> mp.nprint(R, 3) # doctest:+SKIP\\n      [2.0  0.417  -2.53]\\n      [0.0    4.0  -4.74]\\n      [0.0    0.0    9.0]\\n      >>> print(mp.chop(A - Q * R * Q.transpose_conj()))\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n\\n    warning: The Schur decomposition is not unique.\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    if n == 1:\\n        return (ctx.matrix([[1]]), A)\\n\\n    if not overwrite_a:\\n        A = A.copy()\\n\\n    T = ctx.matrix(n, 1)\\n\\n    hessenberg_reduce_0(ctx, A, T)\\n    Q = A.copy()\\n    hessenberg_reduce_1(ctx, Q, T)\\n\\n    for x in xrange(n):\\n        for y in xrange(x + 2, n):\\n            A[y,x] = 0\\n\\n    hessenberg_qr(ctx, A, Q)\\n\\n    return Q, A\\n\\n\\ndef eig_tr_r(ctx, A):\\n    \\\"\\\"\\\"\\n    This routine calculates the right eigenvectors of an upper right triangular matrix.\\n\\n    input:\\n      A      an upper right triangular matrix\\n\\n    output:\\n      ER     a matrix whose columns form the right eigenvectors of A\\n\\n    return value: ER\\n    \\\"\\\"\\\"\\n\\n    # this subroutine is inspired by the lapack routines ctrevc.f,clatrs.f\\n\\n    n = A.rows\\n\\n    ER = ctx.eye(n)\\n\\n    eps = ctx.eps\\n\\n    unfl = ctx.ldexp(ctx.one, -ctx.prec * 30)\\n    # since mpmath effectively has no limits on the exponent, we simply scale doubles up\\n    # original double has prec*20\\n\\n    smlnum = unfl * (n / eps)\\n    simin = 1 / ctx.sqrt(eps)\\n\\n    rmax = 1\\n\\n    for i in xrange(1, n):\\n        s = A[i,i]\\n\\n        smin = max(eps * abs(s), smlnum)\\n\\n        for j in xrange(i - 1, -1, -1):\\n\\n            r = 0\\n            for k in xrange(j + 1, i + 1):\\n                r += A[j,k] * ER[k,i]\\n\\n            t = A[j,j] - s\\n            if abs(t) < smin:\\n                t = smin\\n\\n            r = -r / t\\n            ER[j,i] = r\\n\\n            rmax = max(rmax, abs(r))\\n            if rmax > simin:\\n                for k in xrange(j, i+1):\\n                    ER[k,i] /= rmax\\n                rmax = 1\\n\\n        if rmax != 1:\\n            for k in xrange(0, i + 1):\\n                ER[k,i] /= rmax\\n\\n    return ER\\n\\ndef eig_tr_l(ctx, A):\\n    \\\"\\\"\\\"\\n    This routine calculates the left eigenvectors of an upper right triangular matrix.\\n\\n    input:\\n      A      an upper right triangular matrix\\n\\n    output:\\n      EL     a matrix whose rows form the left eigenvectors of A\\n\\n    return value:  EL\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    EL = ctx.eye(n)\\n\\n    eps = ctx.eps\\n\\n    unfl = ctx.ldexp(ctx.one, -ctx.prec * 30)\\n    # since mpmath effectively has no limits on the exponent, we simply scale doubles up\\n    # original double has prec*20\\n\\n    smlnum = unfl * (n / eps)\\n    simin = 1 / ctx.sqrt(eps)\\n\\n    rmax = 1\\n\\n    for i in xrange(0, n - 1):\\n        s = A[i,i]\\n\\n        smin = max(eps * abs(s), smlnum)\\n\\n        for j in xrange(i + 1, n):\\n\\n            r = 0\\n            for k in xrange(i, j):\\n                r += EL[i,k] * A[k,j]\\n\\n            t = A[j,j] - s\\n            if abs(t) < smin:\\n                t = smin\\n\\n            r = -r / t\\n            EL[i,j] = r\\n\\n            rmax = max(rmax, abs(r))\\n            if rmax > simin:\\n                for k in xrange(i, j + 1):\\n                    EL[i,k] /= rmax\\n                rmax = 1\\n\\n        if rmax != 1:\\n            for k in xrange(i, n):\\n                EL[i,k] /= rmax\\n\\n    return EL\\n\\n@defun\\ndef eig(ctx, A, left = False, right = True, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine computes the eigenvalues and optionally the left and right\\n    eigenvectors of a square matrix A. Given A, a vector E and matrices ER\\n    and EL are calculated such that\\n\\n                        A ER[:,i] =         E[i] ER[:,i]\\n                EL[i,:] A         = EL[i,:] E[i]\\n\\n    E contains the eigenvalues of A. The columns of ER contain the right eigenvectors\\n    of A whereas the rows of EL contain the left eigenvectors.\\n\\n\\n    input:\\n      A           : a real or complex square matrix of shape (n, n)\\n      left        : if true, the left eigenvectors are calculated.\\n      right       : if true, the right eigenvectors are calculated.\\n      overwrite_a : if true, allows modification of A which may improve\\n                    performance. if false, A is not modified.\\n\\n    output:\\n      E    : a list of length n containing the eigenvalues of A.\\n      ER   : a matrix whose columns contain the right eigenvectors of A.\\n      EL   : a matrix whose rows contain the left eigenvectors of A.\\n\\n    return values:\\n       E            if left and right are both false.\\n      (E, ER)       if right is true and left is false.\\n      (E, EL)       if left is true and right is false.\\n      (E, EL, ER)   if left and right are true.\\n\\n\\n    examples:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])\\n      >>> E, ER = mp.eig(A)\\n      >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))\\n      [0.0]\\n      [0.0]\\n      [0.0]\\n\\n      >>> E, EL, ER = mp.eig(A,left = True, right = True)\\n      >>> E, EL, ER = mp.eig_sort(E, EL, ER)\\n      >>> mp.nprint(E)\\n      [2.0, 4.0, 9.0]\\n      >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))\\n      [0.0]\\n      [0.0]\\n      [0.0]\\n      >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0]))\\n      [0.0  0.0  0.0]\\n\\n    warning:\\n     - If there are multiple eigenvalues, the eigenvectors do not necessarily\\n       span the whole vectorspace, i.e. ER and EL may have not full rank.\\n       Furthermore in that case the eigenvectors are numerical ill-conditioned.\\n     - In the general case the eigenvalues have no natural order.\\n\\n    see also:\\n      - eigh (or eigsy, eighe) for the symmetric eigenvalue problem.\\n      - eig_sort for sorting of eigenvalues and eigenvectors\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    if n == 1:\\n        if left and (not right):\\n            return ([A[0]], ctx.matrix([[1]]))\\n\\n        if right and (not left):\\n            return ([A[0]], ctx.matrix([[1]]))\\n\\n        return ([A[0]], ctx.matrix([[1]]), ctx.matrix([[1]]))\\n\\n    if not overwrite_a:\\n        A = A.copy()\\n\\n    T = ctx.zeros(n, 1)\\n\\n    hessenberg_reduce_0(ctx, A, T)\\n\\n    if left or right:\\n        Q = A.copy()\\n        hessenberg_reduce_1(ctx, Q, T)\\n    else:\\n        Q = False\\n\\n    for x in xrange(n):\\n        for y in xrange(x + 2, n):\\n            A[y,x] = 0\\n\\n    hessenberg_qr(ctx, A, Q)\\n\\n    E = [0 for i in xrange(n)]\\n    for i in xrange(n):\\n        E[i] = A[i,i]\\n\\n    if not (left or right):\\n        return E\\n\\n    if left:\\n        EL = eig_tr_l(ctx, A)\\n        EL = EL * Q.transpose_conj()\\n\\n    if right:\\n        ER = eig_tr_r(ctx, A)\\n        ER = Q * ER\\n\\n    if left and (not right):\\n        return (E, EL)\\n\\n    if right and (not left):\\n        return (E, ER)\\n\\n    return (E, EL, ER)\\n\\n@defun\\ndef eig_sort(ctx, E, EL = False, ER = False, f = \\\"real\\\"):\\n    \\\"\\\"\\\"\\n    This routine sorts the eigenvalues and eigenvectors delivered by ``eig``.\\n\\n    parameters:\\n      E  : the eigenvalues as delivered by eig\\n      EL : the left  eigenvectors as delivered by eig, or false\\n      ER : the right eigenvectors as delivered by eig, or false\\n      f  : either a string (\\\"real\\\" sort by increasing real part, \\\"imag\\\" sort by\\n           increasing imag part, \\\"abs\\\" sort by absolute value) or a function\\n           mapping complexs to the reals, i.e. ``f = lambda x: -mp.re(x) ``\\n           would sort the eigenvalues by decreasing real part.\\n\\n    return values:\\n       E            if EL and ER are both false.\\n      (E, ER)       if ER is not false and left is false.\\n      (E, EL)       if EL is not false and right is false.\\n      (E, EL, ER)   if EL and ER are not false.\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])\\n      >>> E, EL, ER = mp.eig(A,left = True, right = True)\\n      >>> E, EL, ER = mp.eig_sort(E, EL, ER)\\n      >>> mp.nprint(E)\\n      [2.0, 4.0, 9.0]\\n      >>> E, EL, ER = mp.eig_sort(E, EL, ER,f = lambda x: -mp.re(x))\\n      >>> mp.nprint(E)\\n      [9.0, 4.0, 2.0]\\n      >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))\\n      [0.0]\\n      [0.0]\\n      [0.0]\\n      >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0]))\\n      [0.0  0.0  0.0]\\n    \\\"\\\"\\\"\\n\\n    if isinstance(f, str):\\n        if f == \\\"real\\\":\\n            f = ctx.re\\n        elif f == \\\"imag\\\":\\n            f = ctx.im\\n        elif f == \\\"abs\\\":\\n            f = abs\\n        else:\\n            raise RuntimeError(\\\"unknown function %s\\\" % f)\\n\\n    n = len(E)\\n\\n    # Sort eigenvalues (bubble-sort)\\n\\n    for i in xrange(n):\\n        imax = i\\n        s = f(E[i])         # s is the current maximal element\\n\\n        for j in xrange(i + 1, n):\\n            c = f(E[j])\\n            if c < s:\\n                s = c\\n                imax = j\\n\\n        if imax != i:\\n            # swap eigenvalues\\n\\n            z = E[i]\\n            E[i] = E[imax]\\n            E[imax] = z\\n\\n            if not isinstance(EL, bool):\\n                for j in xrange(n):\\n                    z = EL[i,j]\\n                    EL[i,j] = EL[imax,j]\\n                    EL[imax,j] = z\\n\\n            if not isinstance(ER, bool):\\n                for j in xrange(n):\\n                    z = ER[j,i]\\n                    ER[j,i] = ER[j,imax]\\n                    ER[j,imax] = z\\n\\n    if isinstance(EL, bool) and isinstance(ER, bool):\\n        return E\\n\\n    if isinstance(EL, bool) and not(isinstance(ER, bool)):\\n        return (E, ER)\\n\\n    if isinstance(ER, bool) and not(isinstance(EL, bool)):\\n        return (E, EL)\\n\\n    return (E, EL, ER)\\n\\n\\nfrom ..libmp.backend import xrange\\n\\n# TODO: should use diagonalization-based algorithms\\n\\nclass MatrixCalculusMethods(object):\\n\\n    def _exp_pade(ctx, a):\\n        \\\"\\\"\\\"\\n        Exponential of a matrix using Pade approximants.\\n\\n        See G. H. Golub, C. F. van Loan 'Matrix Computations',\\n        third Ed., page 572\\n\\n        TODO:\\n         - find a good estimate for q\\n         - reduce the number of matrix multiplications to improve\\n           performance\\n        \\\"\\\"\\\"\\n        def eps_pade(p):\\n            return ctx.mpf(2)**(3-2*p) * \\\\\\n                ctx.factorial(p)**2/(ctx.factorial(2*p)**2 * (2*p + 1))\\n        q = 4\\n        extraq = 8\\n        while 1:\\n            if eps_pade(q) < ctx.eps:\\n                break\\n            q += 1\\n        q += extraq\\n        j = int(max(1, ctx.mag(ctx.mnorm(a,'inf'))))\\n        extra = q\\n        prec = ctx.prec\\n        ctx.dps += extra + 3\\n        try:\\n            a = a/2**j\\n            na = a.rows\\n            den = ctx.eye(na)\\n            num = ctx.eye(na)\\n            x = ctx.eye(na)\\n            c = ctx.mpf(1)\\n            for k in range(1, q+1):\\n                c *= ctx.mpf(q - k + 1)/((2*q - k + 1) * k)\\n                x = a*x\\n                cx = c*x\\n                num += cx\\n                den += (-1)**k * cx\\n            f = ctx.lu_solve_mat(den, num)\\n            for k in range(j):\\n                f = f*f\\n        finally:\\n            ctx.prec = prec\\n        return f*1\\n\\n    def expm(ctx, A, method='taylor'):\\n        r\\\"\\\"\\\"\\n        Computes the matrix exponential of a square matrix `A`, which is defined\\n        by the power series\\n\\n        .. math ::\\n\\n            \\\\exp(A) = I + A + \\\\frac{A^2}{2!} + \\\\frac{A^3}{3!} + \\\\ldots\\n\\n        With method='taylor', the matrix exponential is computed\\n        using the Taylor series. With method='pade', Pade approximants\\n        are used instead.\\n\\n        **Examples**\\n\\n        Basic examples::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> expm(zeros(3))\\n            [1.0  0.0  0.0]\\n            [0.0  1.0  0.0]\\n            [0.0  0.0  1.0]\\n            >>> expm(eye(3))\\n            [2.71828182845905               0.0               0.0]\\n            [             0.0  2.71828182845905               0.0]\\n            [             0.0               0.0  2.71828182845905]\\n            >>> expm([[1,1,0],[1,0,1],[0,1,0]])\\n            [ 3.86814500615414  2.26812870852145  0.841130841230196]\\n            [ 2.26812870852145  2.44114713886289   1.42699786729125]\\n            [0.841130841230196  1.42699786729125    1.6000162976327]\\n            >>> expm([[1,1,0],[1,0,1],[0,1,0]], method='pade')\\n            [ 3.86814500615414  2.26812870852145  0.841130841230196]\\n            [ 2.26812870852145  2.44114713886289   1.42699786729125]\\n            [0.841130841230196  1.42699786729125    1.6000162976327]\\n            >>> expm([[1+j, 0], [1+j,1]])\\n            [(1.46869393991589 + 2.28735528717884j)                        0.0]\\n            [  (1.03776739863568 + 3.536943175722j)  (2.71828182845905 + 0.0j)]\\n\\n        Matrices with large entries are allowed::\\n\\n            >>> expm(matrix([[1,2],[2,3]])**25)\\n            [5.65024064048415e+2050488462815550  9.14228140091932e+2050488462815550]\\n            [9.14228140091932e+2050488462815550  1.47925220414035e+2050488462815551]\\n\\n        The identity `\\\\exp(A+B) = \\\\exp(A) \\\\exp(B)` does not hold for\\n        noncommuting matrices::\\n\\n            >>> A = hilbert(3)\\n            >>> B = A + eye(3)\\n            >>> chop(mnorm(A*B - B*A))\\n            0.0\\n            >>> chop(mnorm(expm(A+B) - expm(A)*expm(B)))\\n            0.0\\n            >>> B = A + ones(3)\\n            >>> mnorm(A*B - B*A)\\n            1.8\\n            >>> mnorm(expm(A+B) - expm(A)*expm(B))\\n            42.0927851137247\\n\\n        \\\"\\\"\\\"\\n        if method == 'pade':\\n            prec = ctx.prec\\n            try:\\n                A = ctx.matrix(A)\\n                ctx.prec += 2*A.rows\\n                res = ctx._exp_pade(A)\\n            finally:\\n                ctx.prec = prec\\n            return res\\n        A = ctx.matrix(A)\\n        prec = ctx.prec\\n        j = int(max(1, ctx.mag(ctx.mnorm(A,'inf'))))\\n        j += int(0.5*prec**0.5)\\n        try:\\n            ctx.prec += 10 + 2*j\\n            tol = +ctx.eps\\n            A = A/2**j\\n            T = A\\n            Y = A**0 + A\\n            k = 2\\n            while 1:\\n                T *= A * (1/ctx.mpf(k))\\n                if ctx.mnorm(T, 'inf') < tol:\\n                    break\\n                Y += T\\n                k += 1\\n            for k in xrange(j):\\n                Y = Y*Y\\n        finally:\\n            ctx.prec = prec\\n        Y *= 1\\n        return Y\\n\\n    def cosm(ctx, A):\\n        r\\\"\\\"\\\"\\n        Gives the cosine of a square matrix `A`, defined in analogy\\n        with the matrix exponential.\\n\\n        Examples::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> X = eye(3)\\n            >>> cosm(X)\\n            [0.54030230586814               0.0               0.0]\\n            [             0.0  0.54030230586814               0.0]\\n            [             0.0               0.0  0.54030230586814]\\n            >>> X = hilbert(3)\\n            >>> cosm(X)\\n            [ 0.424403834569555  -0.316643413047167  -0.221474945949293]\\n            [-0.316643413047167   0.820646708837824  -0.127183694770039]\\n            [-0.221474945949293  -0.127183694770039   0.909236687217541]\\n            >>> X = matrix([[1+j,-2],[0,-j]])\\n            >>> cosm(X)\\n            [(0.833730025131149 - 0.988897705762865j)  (1.07485840848393 - 0.17192140544213j)]\\n            [                                     0.0               (1.54308063481524 + 0.0j)]\\n        \\\"\\\"\\\"\\n        B = 0.5 * (ctx.expm(A*ctx.j) + ctx.expm(A*(-ctx.j)))\\n        if not sum(A.apply(ctx.im).apply(abs)):\\n            B = B.apply(ctx.re)\\n        return B\\n\\n    def sinm(ctx, A):\\n        r\\\"\\\"\\\"\\n        Gives the sine of a square matrix `A`, defined in analogy\\n        with the matrix exponential.\\n\\n        Examples::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> X = eye(3)\\n            >>> sinm(X)\\n            [0.841470984807897                0.0                0.0]\\n            [              0.0  0.841470984807897                0.0]\\n            [              0.0                0.0  0.841470984807897]\\n            >>> X = hilbert(3)\\n            >>> sinm(X)\\n            [0.711608512150994  0.339783913247439  0.220742837314741]\\n            [0.339783913247439  0.244113865695532  0.187231271174372]\\n            [0.220742837314741  0.187231271174372  0.155816730769635]\\n            >>> X = matrix([[1+j,-2],[0,-j]])\\n            >>> sinm(X)\\n            [(1.29845758141598 + 0.634963914784736j)  (-1.96751511930922 + 0.314700021761367j)]\\n            [                                    0.0                  (0.0 - 1.1752011936438j)]\\n        \\\"\\\"\\\"\\n        B = (-0.5j) * (ctx.expm(A*ctx.j) - ctx.expm(A*(-ctx.j)))\\n        if not sum(A.apply(ctx.im).apply(abs)):\\n            B = B.apply(ctx.re)\\n        return B\\n\\n    def _sqrtm_rot(ctx, A, _may_rotate):\\n        # If the iteration fails to converge, cheat by performing\\n        # a rotation by a complex number\\n        u = ctx.j**0.3\\n        return ctx.sqrtm(u*A, _may_rotate) / ctx.sqrt(u)\\n\\n    def sqrtm(ctx, A, _may_rotate=2):\\n        r\\\"\\\"\\\"\\n        Computes a square root of the square matrix `A`, i.e. returns\\n        a matrix `B = A^{1/2}` such that `B^2 = A`. The square root\\n        of a matrix, if it exists, is not unique.\\n\\n        **Examples**\\n\\n        Square roots of some simple matrices::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> sqrtm([[1,0], [0,1]])\\n            [1.0  0.0]\\n            [0.0  1.0]\\n            >>> sqrtm([[0,0], [0,0]])\\n            [0.0  0.0]\\n            [0.0  0.0]\\n            >>> sqrtm([[2,0],[0,1]])\\n            [1.4142135623731  0.0]\\n            [            0.0  1.0]\\n            >>> sqrtm([[1,1],[1,0]])\\n            [ (0.920442065259926 - 0.21728689675164j)  (0.568864481005783 + 0.351577584254143j)]\\n            [(0.568864481005783 + 0.351577584254143j)  (0.351577584254143 - 0.568864481005783j)]\\n            >>> sqrtm([[1,0],[0,1]])\\n            [1.0  0.0]\\n            [0.0  1.0]\\n            >>> sqrtm([[-1,0],[0,1]])\\n            [(0.0 - 1.0j)           0.0]\\n            [         0.0  (1.0 + 0.0j)]\\n            >>> sqrtm([[j,0],[0,j]])\\n            [(0.707106781186547 + 0.707106781186547j)                                       0.0]\\n            [                                     0.0  (0.707106781186547 + 0.707106781186547j)]\\n\\n        A square root of a rotation matrix, giving the corresponding\\n        half-angle rotation matrix::\\n\\n            >>> t1 = 0.75\\n            >>> t2 = t1 * 0.5\\n            >>> A1 = matrix([[cos(t1), -sin(t1)], [sin(t1), cos(t1)]])\\n            >>> A2 = matrix([[cos(t2), -sin(t2)], [sin(t2), cos(t2)]])\\n            >>> sqrtm(A1)\\n            [0.930507621912314  -0.366272529086048]\\n            [0.366272529086048   0.930507621912314]\\n            >>> A2\\n            [0.930507621912314  -0.366272529086048]\\n            [0.366272529086048   0.930507621912314]\\n\\n        The identity `(A^2)^{1/2} = A` does not necessarily hold::\\n\\n            >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]])\\n            >>> sqrtm(A**2)\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n            >>> sqrtm(A)**2\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n            >>> A = matrix([[-4,1,4],[7,-8,9],[10,2,11]])\\n            >>> sqrtm(A**2)\\n            [  7.43715112194995  -0.324127569985474   1.8481718827526]\\n            [-0.251549715716942    9.32699765900402  2.48221180985147]\\n            [  4.11609388833616   0.775751877098258   13.017955697342]\\n            >>> chop(sqrtm(A)**2)\\n            [-4.0   1.0   4.0]\\n            [ 7.0  -8.0   9.0]\\n            [10.0   2.0  11.0]\\n\\n        For some matrices, a square root does not exist::\\n\\n            >>> sqrtm([[0,1], [0,0]])\\n            Traceback (most recent call last):\\n              ...\\n            ZeroDivisionError: matrix is numerically singular\\n\\n        Two examples from the documentation for Matlab's ``sqrtm``::\\n\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> sqrtm([[7,10],[15,22]])\\n            [1.56669890360128  1.74077655955698]\\n            [2.61116483933547  4.17786374293675]\\n            >>>\\n            >>> X = matrix(\\\\\\n            ...   [[5,-4,1,0,0],\\n            ...   [-4,6,-4,1,0],\\n            ...   [1,-4,6,-4,1],\\n            ...   [0,1,-4,6,-4],\\n            ...   [0,0,1,-4,5]])\\n            >>> Y = matrix(\\\\\\n            ...   [[2,-1,-0,-0,-0],\\n            ...   [-1,2,-1,0,-0],\\n            ...   [0,-1,2,-1,0],\\n            ...   [-0,0,-1,2,-1],\\n            ...   [-0,-0,-0,-1,2]])\\n            >>> mnorm(sqrtm(X) - Y)\\n            4.53155328326114e-19\\n\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(A)\\n        # Trivial\\n        if A*0 == A:\\n            return A\\n        prec = ctx.prec\\n        if _may_rotate:\\n            d = ctx.det(A)\\n            if abs(ctx.im(d)) < 16*ctx.eps and ctx.re(d) < 0:\\n                return ctx._sqrtm_rot(A, _may_rotate-1)\\n        try:\\n            ctx.prec += 10\\n            tol = ctx.eps * 128\\n            Y = A\\n            Z = I = A**0\\n            k = 0\\n            # Denman-Beavers iteration\\n            while 1:\\n                Yprev = Y\\n                try:\\n                    Y, Z = 0.5*(Y+ctx.inverse(Z)), 0.5*(Z+ctx.inverse(Y))\\n                except ZeroDivisionError:\\n                    if _may_rotate:\\n                        Y = ctx._sqrtm_rot(A, _may_rotate-1)\\n                        break\\n                    else:\\n                        raise\\n                mag1 = ctx.mnorm(Y-Yprev, 'inf')\\n                mag2 = ctx.mnorm(Y, 'inf')\\n                if mag1 <= mag2*tol:\\n                    break\\n                if _may_rotate and k > 6 and not mag1 < mag2 * 0.001:\\n                    return ctx._sqrtm_rot(A, _may_rotate-1)\\n                k += 1\\n                if k > ctx.prec:\\n                    raise ctx.NoConvergence\\n        finally:\\n            ctx.prec = prec\\n        Y *= 1\\n        return Y\\n\\n    def logm(ctx, A):\\n        r\\\"\\\"\\\"\\n        Computes a logarithm of the square matrix `A`, i.e. returns\\n        a matrix `B = \\\\log(A)` such that `\\\\exp(B) = A`. The logarithm\\n        of a matrix, if it exists, is not unique.\\n\\n        **Examples**\\n\\n        Logarithms of some simple matrices::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> X = eye(3)\\n            >>> logm(X)\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n            [0.0  0.0  0.0]\\n            >>> logm(2*X)\\n            [0.693147180559945                0.0                0.0]\\n            [              0.0  0.693147180559945                0.0]\\n            [              0.0                0.0  0.693147180559945]\\n            >>> logm(expm(X))\\n            [1.0  0.0  0.0]\\n            [0.0  1.0  0.0]\\n            [0.0  0.0  1.0]\\n\\n        A logarithm of a complex matrix::\\n\\n            >>> X = matrix([[2+j, 1, 3], [1-j, 1-2*j, 1], [-4, -5, j]])\\n            >>> B = logm(X)\\n            >>> nprint(B)\\n            [ (0.808757 + 0.107759j)    (2.20752 + 0.202762j)   (1.07376 - 0.773874j)]\\n            [ (0.905709 - 0.107795j)  (0.0287395 - 0.824993j)  (0.111619 + 0.514272j)]\\n            [(-0.930151 + 0.399512j)   (-2.06266 - 0.674397j)  (0.791552 + 0.519839j)]\\n            >>> chop(expm(B))\\n            [(2.0 + 1.0j)           1.0           3.0]\\n            [(1.0 - 1.0j)  (1.0 - 2.0j)           1.0]\\n            [        -4.0          -5.0  (0.0 + 1.0j)]\\n\\n        A matrix `X` close to the identity matrix, for which\\n        `\\\\log(\\\\exp(X)) = \\\\exp(\\\\log(X)) = X` holds::\\n\\n            >>> X = eye(3) + hilbert(3)/4\\n            >>> X\\n            [              1.25             0.125  0.0833333333333333]\\n            [             0.125  1.08333333333333              0.0625]\\n            [0.0833333333333333            0.0625                1.05]\\n            >>> logm(expm(X))\\n            [              1.25             0.125  0.0833333333333333]\\n            [             0.125  1.08333333333333              0.0625]\\n            [0.0833333333333333            0.0625                1.05]\\n            >>> expm(logm(X))\\n            [              1.25             0.125  0.0833333333333333]\\n            [             0.125  1.08333333333333              0.0625]\\n            [0.0833333333333333            0.0625                1.05]\\n\\n        A logarithm of a rotation matrix, giving back the angle of\\n        the rotation::\\n\\n            >>> t = 3.7\\n            >>> A = matrix([[cos(t),sin(t)],[-sin(t),cos(t)]])\\n            >>> chop(logm(A))\\n            [             0.0  -2.58318530717959]\\n            [2.58318530717959                0.0]\\n            >>> (2*pi-t)\\n            2.58318530717959\\n\\n        For some matrices, a logarithm does not exist::\\n\\n            >>> logm([[1,0], [0,0]])\\n            Traceback (most recent call last):\\n              ...\\n            ZeroDivisionError: matrix is numerically singular\\n\\n        Logarithm of a matrix with large entries::\\n\\n            >>> logm(hilbert(3) * 10**20).apply(re)\\n            [ 45.5597513593433  1.27721006042799  0.317662687717978]\\n            [ 1.27721006042799  42.5222778973542   2.24003708791604]\\n            [0.317662687717978  2.24003708791604    42.395212822267]\\n\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(A)\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            tol = ctx.eps * 128\\n            I = A**0\\n            B = A\\n            n = 0\\n            while 1:\\n                B = ctx.sqrtm(B)\\n                n += 1\\n                if ctx.mnorm(B-I, 'inf') < 0.125:\\n                    break\\n            T = X = B-I\\n            L = X*0\\n            k = 1\\n            while 1:\\n                if k & 1:\\n                    L += T / k\\n                else:\\n                    L -= T / k\\n                T *= X\\n                if ctx.mnorm(T, 'inf') < tol:\\n                    break\\n                k += 1\\n                if k > ctx.prec:\\n                    raise ctx.NoConvergence\\n        finally:\\n            ctx.prec = prec\\n        L *= 2**n\\n        return L\\n\\n    def powm(ctx, A, r):\\n        r\\\"\\\"\\\"\\n        Computes `A^r = \\\\exp(A \\\\log r)` for a matrix `A` and complex\\n        number `r`.\\n\\n        **Examples**\\n\\n        Powers and inverse powers of a matrix::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]])\\n            >>> powm(A, 2)\\n            [ 63.0  20.0   69.0]\\n            [174.0  89.0  199.0]\\n            [164.0  48.0  179.0]\\n            >>> chop(powm(powm(A, 4), 1/4.))\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n            >>> powm(extraprec(20)(powm)(A, -4), -1/4.)\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n            >>> chop(powm(powm(A, 1+0.5j), 1/(1+0.5j)))\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n            >>> powm(extraprec(5)(powm)(A, -1.5), -1/(1.5))\\n            [ 4.0  1.0   4.0]\\n            [ 7.0  8.0   9.0]\\n            [10.0  2.0  11.0]\\n\\n        A Fibonacci-generating matrix::\\n\\n            >>> powm([[1,1],[1,0]], 10)\\n            [89.0  55.0]\\n            [55.0  34.0]\\n            >>> fib(10)\\n            55.0\\n            >>> powm([[1,1],[1,0]], 6.5)\\n            [(16.5166626964253 - 0.0121089837381789j)  (10.2078589271083 + 0.0195927472575932j)]\\n            [(10.2078589271083 + 0.0195927472575932j)  (6.30880376931698 - 0.0317017309957721j)]\\n            >>> (phi**6.5 - (1-phi)**6.5)/sqrt(5)\\n            (10.2078589271083 - 0.0195927472575932j)\\n            >>> powm([[1,1],[1,0]], 6.2)\\n            [ (14.3076953002666 - 0.008222855781077j)  (8.81733464837593 + 0.0133048601383712j)]\\n            [(8.81733464837593 + 0.0133048601383712j)  (5.49036065189071 - 0.0215277159194482j)]\\n            >>> (phi**6.2 - (1-phi)**6.2)/sqrt(5)\\n            (8.81733464837593 - 0.0133048601383712j)\\n\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(A)\\n        r = ctx.convert(r)\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            if ctx.isint(r):\\n                v = A ** int(r)\\n            elif ctx.isint(r*2):\\n                y = int(r*2)\\n                v = ctx.sqrtm(A) ** y\\n            else:\\n                v = ctx.expm(r*ctx.logm(A))\\n        finally:\\n            ctx.prec = prec\\n        v *= 1\\n        return v\\n\\n\\n#!/usr/bin/python\\n# -*- coding: utf-8 -*-\\n\\n##################################################################################################\\n#     module for the symmetric eigenvalue problem\\n#       Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)\\n#\\n# todo:\\n#  - implement balancing\\n#\\n##################################################################################################\\n\\n\\\"\\\"\\\"\\nThe symmetric eigenvalue problem.\\n---------------------------------\\n\\nThis file contains routines for the symmetric eigenvalue problem.\\n\\nhigh level routines:\\n\\n  eigsy : real symmetric (ordinary) eigenvalue problem\\n  eighe : complex hermitian (ordinary) eigenvalue problem\\n  eigh  : unified interface for eigsy and eighe\\n  svd_r : singular value decomposition for real matrices\\n  svd_c : singular value decomposition for complex matrices\\n  svd   : unified interface for svd_r and svd_c\\n\\n\\nlow level routines:\\n\\n  r_sy_tridiag : reduction of real symmetric matrix to real symmetric tridiagonal matrix\\n  c_he_tridiag_0 : reduction of complex hermitian matrix to real symmetric tridiagonal matrix\\n  c_he_tridiag_1 : auxiliary routine to c_he_tridiag_0\\n  c_he_tridiag_2 : auxiliary routine to c_he_tridiag_0\\n  tridiag_eigen : solves the real symmetric tridiagonal matrix eigenvalue problem\\n  svd_r_raw : raw singular value decomposition for real matrices\\n  svd_c_raw : raw singular value decomposition for complex matrices\\n\\\"\\\"\\\"\\n\\nfrom ..libmp.backend import xrange\\nfrom .eigen import defun\\n\\n\\ndef r_sy_tridiag(ctx, A, D, E, calc_ev = True):\\n    \\\"\\\"\\\"\\n    This routine transforms a real symmetric matrix A to a real symmetric\\n    tridiagonal matrix T using an orthogonal similarity transformation:\\n          Q' * A * Q = T     (here ' denotes the matrix transpose).\\n    The orthogonal matrix Q is build up from Householder reflectors.\\n\\n    parameters:\\n      A         (input/output) On input, A contains the real symmetric matrix of\\n                dimension (n,n). On output, if calc_ev is true, A contains the\\n                orthogonal matrix Q, otherwise A is destroyed.\\n\\n      D         (output) real array of length n, contains the diagonal elements\\n                of the tridiagonal matrix\\n\\n      E         (output) real array of length n, contains the offdiagonal elements\\n                of the tridiagonal matrix in E[0:(n-1)] where is the dimension of\\n                the matrix A. E[n-1] is undefined.\\n\\n      calc_ev   (input) If calc_ev is true, this routine explicitly calculates the\\n                orthogonal matrix Q which is then returned in A. If calc_ev is\\n                false, Q is not explicitly calculated resulting in a shorter run time.\\n\\n    This routine is a python translation of the fortran routine tred2.f in the\\n    software library EISPACK (see netlib.org) which itself is based on the algol\\n    procedure tred2 described in:\\n      - Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson\\n      - Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971)\\n\\n    For a good introduction to Householder reflections, see also\\n      Stoer, Bulirsch - Introduction to Numerical Analysis.\\n    \\\"\\\"\\\"\\n\\n    # note : the vector v of the i-th houshoulder reflector is stored in a[(i+1):,i]\\n    #        whereas v/<v,v> is stored in a[i,(i+1):]\\n\\n    n = A.rows\\n    for i in xrange(n - 1, 0, -1):\\n        # scale the vector\\n\\n        scale = 0\\n        for k in xrange(0, i):\\n            scale += abs(A[k,i])\\n\\n        scale_inv = 0\\n        if scale != 0:\\n            scale_inv = 1/scale\\n\\n        # sadly there are floating point numbers not equal to zero whose reciprocal is infinity\\n\\n        if i == 1 or scale == 0 or ctx.isinf(scale_inv):\\n            E[i] = A[i-1,i]        # nothing to do\\n            D[i] = 0\\n            continue\\n\\n        # calculate parameters for housholder transformation\\n\\n        H = 0\\n        for k in xrange(0, i):\\n            A[k,i] *= scale_inv\\n            H += A[k,i] * A[k,i]\\n\\n        F = A[i-1,i]\\n        G = ctx.sqrt(H)\\n        if F > 0:\\n            G = -G\\n        E[i] = scale * G\\n        H -= F * G\\n        A[i-1,i] = F - G\\n        F = 0\\n\\n        # apply housholder transformation\\n\\n        for j in xrange(0, i):\\n            if calc_ev:\\n                A[i,j] = A[j,i] / H\\n\\n            G = 0                  # calculate A*U\\n            for k in xrange(0, j + 1):\\n                G += A[k,j] * A[k,i]\\n            for k in xrange(j + 1, i):\\n                G += A[j,k] * A[k,i]\\n\\n            E[j] = G / H           # calculate P\\n            F += E[j] * A[j,i]\\n\\n        HH = F / (2 * H)\\n\\n        for j in xrange(0, i):     # calculate reduced A\\n            F = A[j,i]\\n            G = E[j] - HH * F      # calculate Q\\n            E[j] = G\\n\\n            for k in xrange(0, j + 1):\\n                A[k,j] -= F * E[k] + G * A[k,i]\\n\\n        D[i] = H\\n\\n    for i in xrange(1, n):         # better for compatibility\\n        E[i-1] = E[i]\\n    E[n-1] = 0\\n\\n    if calc_ev:\\n        D[0] = 0\\n        for i in xrange(0, n):\\n            if D[i] != 0:\\n                for j in xrange(0, i):     # accumulate transformation matrices\\n                    G = 0\\n                    for k in xrange(0, i):\\n                        G += A[i,k] * A[k,j]\\n                    for k in xrange(0, i):\\n                        A[k,j] -= G * A[k,i]\\n\\n            D[i] = A[i,i]\\n            A[i,i] = 1\\n\\n            for j in xrange(0, i):\\n                A[j,i] = A[i,j] = 0\\n    else:\\n        for i in xrange(0, n):\\n            D[i] = A[i,i]\\n\\n\\n\\n\\n\\ndef c_he_tridiag_0(ctx, A, D, E, T):\\n    \\\"\\\"\\\"\\n    This routine transforms a complex hermitian matrix A to a real symmetric\\n    tridiagonal matrix T using an unitary similarity transformation:\\n          Q' * A * Q = T     (here ' denotes the hermitian matrix transpose,\\n                              i.e. transposition und conjugation).\\n    The unitary matrix Q is build up from Householder reflectors and\\n    an unitary diagonal matrix.\\n\\n    parameters:\\n      A         (input/output) On input, A contains the complex hermitian matrix\\n                of dimension (n,n). On output, A contains the unitary matrix Q\\n                in compressed form.\\n\\n      D         (output) real array of length n, contains the diagonal elements\\n                of the tridiagonal matrix.\\n\\n      E         (output) real array of length n, contains the offdiagonal elements\\n                of the tridiagonal matrix in E[0:(n-1)] where is the dimension of\\n                the matrix A. E[n-1] is undefined.\\n\\n      T         (output) complex array of length n, contains a unitary diagonal\\n                matrix.\\n\\n    This routine is a python translation (in slightly modified form) of the fortran\\n    routine htridi.f in the software library EISPACK (see netlib.org) which itself\\n    is a complex version of the algol procedure tred1 described in:\\n      - Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson\\n      - Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971)\\n\\n    For a good introduction to Householder reflections, see also\\n      Stoer, Bulirsch - Introduction to Numerical Analysis.\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n    T[n-1] = 1\\n    for i in xrange(n - 1, 0, -1):\\n\\n        # scale the vector\\n\\n        scale = 0\\n        for k in xrange(0, i):\\n            scale += abs(ctx.re(A[k,i])) + abs(ctx.im(A[k,i]))\\n\\n        scale_inv = 0\\n        if scale != 0:\\n            scale_inv = 1 / scale\\n\\n        # sadly there are floating point numbers not equal to zero whose reciprocal is infinity\\n\\n        if scale == 0 or ctx.isinf(scale_inv):\\n            E[i] = 0\\n            D[i] = 0\\n            T[i-1] = 1\\n            continue\\n\\n        if i == 1:\\n            F = A[i-1,i]\\n            f = abs(F)\\n            E[i] = f\\n            D[i] = 0\\n            if f != 0:\\n                T[i-1] = T[i] * F / f\\n            else:\\n                T[i-1] = T[i]\\n            continue\\n\\n        # calculate parameters for housholder transformation\\n\\n        H = 0\\n        for k in xrange(0, i):\\n            A[k,i] *= scale_inv\\n            rr = ctx.re(A[k,i])\\n            ii = ctx.im(A[k,i])\\n            H += rr * rr + ii * ii\\n\\n        F = A[i-1,i]\\n        f = abs(F)\\n        G = ctx.sqrt(H)\\n        H += G * f\\n        E[i] = scale * G\\n        if f != 0:\\n            F = F / f\\n            TZ = - T[i] * F              # T[i-1]=-T[i]*F, but we need T[i-1] as temporary storage\\n            G *= F\\n        else:\\n            TZ = -T[i]                   # T[i-1]=-T[i]\\n        A[i-1,i] += G\\n        F = 0\\n\\n        # apply housholder transformation\\n\\n        for j in xrange(0, i):\\n            A[i,j] = A[j,i] / H\\n\\n            G = 0                        # calculate A*U\\n            for k in xrange(0, j + 1):\\n                G += ctx.conj(A[k,j]) * A[k,i]\\n            for k in xrange(j + 1, i):\\n                G += A[j,k] * A[k,i]\\n\\n            T[j] = G / H                 # calculate P\\n            F += ctx.conj(T[j]) * A[j,i]\\n\\n        HH = F / (2 * H)\\n\\n        for j in xrange(0, i):           # calculate reduced A\\n            F = A[j,i]\\n            G = T[j] - HH * F            # calculate Q\\n            T[j] = G\\n\\n            for k in xrange(0, j + 1):\\n                A[k,j] -= ctx.conj(F) * T[k] + ctx.conj(G) * A[k,i]\\n                # as we use the lower left part for storage\\n                # we have to use the transpose of the normal formula\\n\\n        T[i-1] = TZ\\n        D[i] = H\\n\\n    for i in xrange(1, n):                # better for compatibility\\n        E[i-1] = E[i]\\n    E[n-1] = 0\\n\\n    D[0] = 0\\n    for i in xrange(0, n):\\n        zw = D[i]\\n        D[i] = ctx.re(A[i,i])\\n        A[i,i] = zw\\n\\n\\n\\n\\n\\n\\n\\ndef c_he_tridiag_1(ctx, A, T):\\n    \\\"\\\"\\\"\\n    This routine forms the unitary matrix Q described in c_he_tridiag_0.\\n\\n    parameters:\\n      A    (input/output) On input, A is the same matrix as delivered by\\n           c_he_tridiag_0. On output, A is set to Q.\\n\\n      T    (input) On input, T is the same array as delivered by c_he_tridiag_0.\\n\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    for i in xrange(0, n):\\n        if A[i,i] != 0:\\n            for j in xrange(0, i):\\n                G = 0\\n                for k in xrange(0, i):\\n                    G += ctx.conj(A[i,k]) * A[k,j]\\n                for k in xrange(0, i):\\n                    A[k,j] -= G * A[k,i]\\n\\n        A[i,i] = 1\\n\\n        for j in xrange(0, i):\\n            A[j,i] = A[i,j] = 0\\n\\n    for i in xrange(0, n):\\n        for k in xrange(0, n):\\n            A[i,k] *= T[k]\\n\\n\\n\\n\\ndef c_he_tridiag_2(ctx, A, T, B):\\n    \\\"\\\"\\\"\\n    This routine applied the unitary matrix Q described in c_he_tridiag_0\\n    onto the the matrix B, i.e. it forms Q*B.\\n\\n    parameters:\\n      A    (input) On input, A is the same matrix as delivered by c_he_tridiag_0.\\n\\n      T    (input) On input, T is the same array as delivered by c_he_tridiag_0.\\n\\n      B    (input/output) On input, B is a complex matrix. On output B is replaced\\n           by Q*B.\\n\\n    This routine is a python translation of the fortran routine htribk.f in the\\n    software library EISPACK (see netlib.org). See c_he_tridiag_0 for more\\n    references.\\n    \\\"\\\"\\\"\\n\\n    n = A.rows\\n\\n    for i in xrange(0, n):\\n        for k in xrange(0, n):\\n            B[k,i] *= T[k]\\n\\n    for i in xrange(0, n):\\n        if A[i,i] != 0:\\n            for j in xrange(0, n):\\n                G = 0\\n                for k in xrange(0, i):\\n                    G += ctx.conj(A[i,k]) * B[k,j]\\n                for k in xrange(0, i):\\n                    B[k,j] -= G * A[k,i]\\n\\n\\n\\n\\n\\ndef tridiag_eigen(ctx, d, e, z = False):\\n    \\\"\\\"\\\"\\n    This subroutine find the eigenvalues and the first components of the\\n    eigenvectors of a real symmetric tridiagonal matrix using the implicit\\n    QL method.\\n\\n    parameters:\\n\\n      d (input/output) real array of length n. on input, d contains the diagonal\\n        elements of the input matrix. on output, d contains the eigenvalues in\\n        ascending order.\\n\\n      e (input) real array of length n. on input, e contains the offdiagonal\\n        elements of the input matrix in e[0:(n-1)]. On output, e has been\\n        destroyed.\\n\\n      z (input/output) If z is equal to False, no eigenvectors will be computed.\\n        Otherwise on input z should have the format z[0:m,0:n] (i.e. a real or\\n        complex matrix of dimension (m,n) ). On output this matrix will be\\n        multiplied by the matrix of the eigenvectors (i.e. the columns of this\\n        matrix are the eigenvectors): z --> z*EV\\n        That means if z[i,j]={1 if j==j; 0 otherwise} on input, then on output\\n        z will contain the first m components of the eigenvectors. That means\\n        if m is equal to n, the i-th eigenvector will be z[:,i].\\n\\n    This routine is a python translation (in slightly modified form) of the\\n    fortran routine imtql2.f in the software library EISPACK (see netlib.org)\\n    which itself is based on the algol procudure imtql2 desribed in:\\n     - num. math. 12, p. 377-383(1968) by matrin and wilkinson\\n     - modified in num. math. 15, p. 450(1970) by dubrulle\\n     - handbook for auto. comp., vol. II-linear algebra, p. 241-248 (1971)\\n    See also the routine gaussq.f in netlog.org or acm algorithm 726.\\n    \\\"\\\"\\\"\\n\\n    n = len(d)\\n    e[n-1] = 0\\n    iterlim = 2 * ctx.dps\\n\\n    for l in xrange(n):\\n        j = 0\\n        while 1:\\n            m = l\\n            while 1:\\n                # look for a small subdiagonal element\\n                if m + 1 == n:\\n                    break\\n                if abs(e[m]) <= ctx.eps * (abs(d[m]) + abs(d[m + 1])):\\n                    break\\n                m = m + 1\\n            if m == l:\\n                break\\n\\n            if j >= iterlim:\\n                raise RuntimeError(\\\"tridiag_eigen: no convergence to an eigenvalue after %d iterations\\\" % iterlim)\\n\\n            j += 1\\n\\n            # form shift\\n\\n            p = d[l]\\n            g = (d[l + 1] - p) / (2 * e[l])\\n            r = ctx.hypot(g, 1)\\n\\n            if g < 0:\\n                s = g - r\\n            else:\\n                s = g + r\\n\\n            g = d[m] - p + e[l] / s\\n\\n            s, c, p = 1, 1, 0\\n\\n            for i in xrange(m - 1, l - 1, -1):\\n                f = s * e[i]\\n                b = c * e[i]\\n                if abs(f) > abs(g):             # this here is a slight improvement also used in gaussq.f or acm algorithm 726.\\n                    c = g / f\\n                    r = ctx.hypot(c, 1)\\n                    e[i + 1] = f * r\\n                    s = 1 / r\\n                    c = c * s\\n                else:\\n                    s = f / g\\n                    r = ctx.hypot(s, 1)\\n                    e[i + 1] = g * r\\n                    c = 1 / r\\n                    s = s * c\\n                g = d[i + 1] - p\\n                r = (d[i] - g) * s + 2 * c * b\\n                p = s * r\\n                d[i + 1] = g + p\\n                g = c * r - b\\n\\n                if not isinstance(z, bool):\\n                    # calculate eigenvectors\\n                    for w in xrange(z.rows):\\n                        f = z[w,i+1]\\n                        z[w,i+1] = s * z[w,i] + c * f\\n                        z[w,i  ] = c * z[w,i] - s * f\\n\\n            d[l] = d[l] - p\\n            e[l] = g\\n            e[m] = 0\\n\\n    for ii in xrange(1, n):\\n        # sort eigenvalues and eigenvectors (bubble-sort)\\n        i = ii - 1\\n        k = i\\n        p = d[i]\\n        for j in xrange(ii, n):\\n            if d[j] >= p:\\n                continue\\n            k = j\\n            p = d[k]\\n        if k == i:\\n            continue\\n        d[k] = d[i]\\n        d[i] = p\\n\\n        if not isinstance(z, bool):\\n            for w in xrange(z.rows):\\n                p = z[w,i]\\n                z[w,i] = z[w,k]\\n                z[w,k] = p\\n\\n########################################################################################\\n\\n@defun\\ndef eigsy(ctx, A, eigvals_only = False, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine solves the (ordinary) eigenvalue problem for a real symmetric\\n    square matrix A. Given A, an orthogonal matrix Q is calculated which\\n    diagonalizes A:\\n\\n          Q' A Q = diag(E)               and                Q Q' = Q' Q = 1\\n\\n    Here diag(E) is a diagonal matrix whose diagonal is E.\\n    ' denotes the transpose.\\n\\n    The columns of Q are the eigenvectors of A and E contains the eigenvalues:\\n\\n          A Q[:,i] = E[i] Q[:,i]\\n\\n\\n    input:\\n\\n      A: real matrix of format (n,n) which is symmetric\\n         (i.e. A=A' or A[i,j]=A[j,i])\\n\\n      eigvals_only: if true, calculates only the eigenvalues E.\\n                    if false, calculates both eigenvectors and eigenvalues.\\n\\n      overwrite_a: if true, allows modification of A which may improve\\n                   performance. if false, A is not modified.\\n\\n    output:\\n\\n      E: vector of format (n). contains the eigenvalues of A in ascending order.\\n\\n      Q: orthogonal matrix of format (n,n). contains the eigenvectors\\n         of A as columns.\\n\\n    return value:\\n\\n          E          if eigvals_only is true\\n         (E, Q)      if eigvals_only is false\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, 2], [2, 0]])\\n      >>> E = mp.eigsy(A, eigvals_only = True)\\n      >>> print(E)\\n      [-1.0]\\n      [ 4.0]\\n\\n      >>> A = mp.matrix([[1, 2], [2, 3]])\\n      >>> E, Q = mp.eigsy(A)\\n      >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))\\n      [0.0]\\n      [0.0]\\n\\n    see also: eighe, eigh, eig\\n    \\\"\\\"\\\"\\n\\n    if not overwrite_a:\\n        A = A.copy()\\n\\n    d = ctx.zeros(A.rows, 1)\\n    e = ctx.zeros(A.rows, 1)\\n\\n    if eigvals_only:\\n        r_sy_tridiag(ctx, A, d, e, calc_ev = False)\\n        tridiag_eigen(ctx, d, e, False)\\n        return d\\n    else:\\n        r_sy_tridiag(ctx, A, d, e, calc_ev = True)\\n        tridiag_eigen(ctx, d, e, A)\\n        return (d, A)\\n\\n\\n@defun\\ndef eighe(ctx, A, eigvals_only = False, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine solves the (ordinary) eigenvalue problem for a complex\\n    hermitian square matrix A. Given A, an unitary matrix Q is calculated which\\n    diagonalizes A:\\n\\n        Q' A Q = diag(E)               and                Q Q' = Q' Q = 1\\n\\n    Here diag(E) a is diagonal matrix whose diagonal is E.\\n    ' denotes the hermitian transpose (i.e. ordinary transposition and\\n    complex conjugation).\\n\\n    The columns of Q are the eigenvectors of A and E contains the eigenvalues:\\n\\n        A Q[:,i] = E[i] Q[:,i]\\n\\n\\n    input:\\n\\n      A: complex matrix of format (n,n) which is hermitian\\n         (i.e. A=A' or A[i,j]=conj(A[j,i]))\\n\\n      eigvals_only: if true, calculates only the eigenvalues E.\\n                    if false, calculates both eigenvectors and eigenvalues.\\n\\n      overwrite_a: if true, allows modification of A which may improve\\n                   performance. if false, A is not modified.\\n\\n    output:\\n\\n      E: vector of format (n). contains the eigenvalues of A in ascending order.\\n\\n      Q: unitary matrix of format (n,n). contains the eigenvectors\\n         of A as columns.\\n\\n    return value:\\n\\n           E         if eigvals_only is true\\n          (E, Q)     if eigvals_only is false\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[1, -3 - 1j], [-3 + 1j, -2]])\\n      >>> E = mp.eighe(A, eigvals_only = True)\\n      >>> print(E)\\n      [-4.0]\\n      [ 3.0]\\n\\n      >>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]])\\n      >>> E, Q = mp.eighe(A)\\n      >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))\\n      [0.0]\\n      [0.0]\\n\\n    see also: eigsy, eigh, eig\\n    \\\"\\\"\\\"\\n\\n    if not overwrite_a:\\n        A = A.copy()\\n\\n    d = ctx.zeros(A.rows, 1)\\n    e = ctx.zeros(A.rows, 1)\\n    t = ctx.zeros(A.rows, 1)\\n\\n    if eigvals_only:\\n        c_he_tridiag_0(ctx, A, d, e, t)\\n        tridiag_eigen(ctx, d, e, False)\\n        return d\\n    else:\\n        c_he_tridiag_0(ctx, A, d, e, t)\\n        B = ctx.eye(A.rows)\\n        tridiag_eigen(ctx, d, e, B)\\n        c_he_tridiag_2(ctx, A, t, B)\\n        return (d, B)\\n\\n@defun\\ndef eigh(ctx, A, eigvals_only = False, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    \\\"eigh\\\" is a unified interface for \\\"eigsy\\\" and \\\"eighe\\\". Depending on\\n    whether A is real or complex the appropriate function is called.\\n\\n    This routine solves the (ordinary) eigenvalue problem for a real symmetric\\n    or complex hermitian square matrix A. Given A, an orthogonal (A real) or\\n    unitary (A complex) matrix Q is calculated which diagonalizes A:\\n\\n        Q' A Q = diag(E)               and                Q Q' = Q' Q = 1\\n\\n    Here diag(E) a is diagonal matrix whose diagonal is E.\\n    ' denotes the hermitian transpose (i.e. ordinary transposition and\\n    complex conjugation).\\n\\n    The columns of Q are the eigenvectors of A and E contains the eigenvalues:\\n\\n        A Q[:,i] = E[i] Q[:,i]\\n\\n    input:\\n\\n      A: a real or complex square matrix of format (n,n) which is symmetric\\n         (i.e. A[i,j]=A[j,i]) or hermitian (i.e. A[i,j]=conj(A[j,i])).\\n\\n      eigvals_only: if true, calculates only the eigenvalues E.\\n                    if false, calculates both eigenvectors and eigenvalues.\\n\\n      overwrite_a: if true, allows modification of A which may improve\\n                   performance. if false, A is not modified.\\n\\n    output:\\n\\n      E: vector of format (n). contains the eigenvalues of A in ascending order.\\n\\n      Q: an orthogonal or unitary matrix of format (n,n). contains the\\n         eigenvectors of A as columns.\\n\\n    return value:\\n\\n          E         if eigvals_only is true\\n         (E, Q)     if eigvals_only is false\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[3, 2], [2, 0]])\\n      >>> E = mp.eigh(A, eigvals_only = True)\\n      >>> print(E)\\n      [-1.0]\\n      [ 4.0]\\n\\n      >>> A = mp.matrix([[1, 2], [2, 3]])\\n      >>> E, Q = mp.eigh(A)\\n      >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))\\n      [0.0]\\n      [0.0]\\n\\n      >>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]])\\n      >>> E, Q = mp.eigh(A)\\n      >>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))\\n      [0.0]\\n      [0.0]\\n\\n    see also: eigsy, eighe, eig\\n    \\\"\\\"\\\"\\n\\n    iscomplex = any(type(x) is ctx.mpc for x in A)\\n\\n    if iscomplex:\\n        return ctx.eighe(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a)\\n    else:\\n        return ctx.eigsy(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a)\\n\\n\\n@defun\\ndef gauss_quadrature(ctx, n, qtype = \\\"legendre\\\", alpha = 0, beta = 0):\\n    \\\"\\\"\\\"\\n    This routine calulates gaussian quadrature rules for different\\n    families of orthogonal polynomials. Let (a, b) be an interval,\\n    W(x) a positive weight function and n a positive integer.\\n    Then the purpose of this routine is to calculate pairs (x_k, w_k)\\n    for k=0, 1, 2, ... (n-1) which give\\n\\n      int(W(x) * F(x), x = a..b) = sum(w_k * F(x_k),k = 0..(n-1))\\n\\n    exact for all polynomials F(x) of degree (strictly) less than 2*n. For all\\n    integrable functions F(x) the sum is a (more or less) good approximation to\\n    the integral. The x_k are called nodes (which are the zeros of the\\n    related orthogonal polynomials) and the w_k are called the weights.\\n\\n    parameters\\n       n        (input) The degree of the quadrature rule, i.e. its number of\\n                nodes.\\n\\n       qtype    (input) The family of orthogonal polynmomials for which to\\n                compute the quadrature rule. See the list below.\\n\\n       alpha    (input) real number, used as parameter for some orthogonal\\n                polynomials\\n\\n       beta     (input) real number, used as parameter for some orthogonal\\n                polynomials.\\n\\n    return value\\n\\n      (X, W)    a pair of two real arrays where x_k = X[k] and w_k = W[k].\\n\\n\\n    orthogonal polynomials:\\n\\n      qtype           polynomial\\n      -----           ----------\\n\\n      \\\"legendre\\\"      Legendre polynomials, W(x)=1 on the interval (-1, +1)\\n      \\\"legendre01\\\"    shifted Legendre polynomials, W(x)=1 on the interval (0, +1)\\n      \\\"hermite\\\"       Hermite polynomials, W(x)=exp(-x*x) on (-infinity,+infinity)\\n      \\\"laguerre\\\"      Laguerre polynomials, W(x)=exp(-x) on (0,+infinity)\\n      \\\"glaguerre\\\"     generalized Laguerre polynomials, W(x)=exp(-x)*x**alpha\\n                      on (0, +infinity)\\n      \\\"chebyshev1\\\"    Chebyshev polynomials of the first kind, W(x)=1/sqrt(1-x*x)\\n                      on (-1, +1)\\n      \\\"chebyshev2\\\"    Chebyshev polynomials of the second kind, W(x)=sqrt(1-x*x)\\n                      on (-1, +1)\\n      \\\"jacobi\\\"        Jacobi polynomials, W(x)=(1-x)**alpha * (1+x)**beta on (-1, +1)\\n                      with alpha>-1 and beta>-1\\n\\n    examples:\\n      >>> from mpmath import mp\\n      >>> f = lambda x: x**8 + 2 * x**6 - 3 * x**4 + 5 * x**2 - 7\\n      >>> X, W = mp.gauss_quadrature(5, \\\"hermite\\\")\\n      >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])\\n      >>> B = mp.sqrt(mp.pi) * 57 / 16\\n      >>> C = mp.quad(lambda x: mp.exp(- x * x) * f(x), [-mp.inf, +mp.inf])\\n      >>> mp.nprint((mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10)))\\n      (0.0, 0.0)\\n\\n      >>> f = lambda x: x**5 - 2 * x**4 + 3 * x**3 - 5 * x**2 + 7 * x - 11\\n      >>> X, W = mp.gauss_quadrature(3, \\\"laguerre\\\")\\n      >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])\\n      >>> B = 76\\n      >>> C = mp.quad(lambda x: mp.exp(-x) * f(x), [0, +mp.inf])\\n      >>> mp.nprint(mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10))\\n      .0\\n\\n      # orthogonality of the chebyshev polynomials:\\n      >>> f = lambda x: mp.chebyt(3, x) * mp.chebyt(2, x)\\n      >>> X, W = mp.gauss_quadrature(3, \\\"chebyshev1\\\")\\n      >>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])\\n      >>> print(mp.chop(A, tol = 1e-10))\\n      0.0\\n\\n    references:\\n      - golub and welsch, \\\"calculations of gaussian quadrature rules\\\", mathematics of\\n        computation 23, p. 221-230 (1969)\\n      - golub, \\\"some modified matrix eigenvalue problems\\\", siam review 15, p. 318-334 (1973)\\n      - stroud and secrest, \\\"gaussian quadrature formulas\\\", prentice-hall (1966)\\n\\n    See also the routine gaussq.f in netlog.org or ACM Transactions on\\n    Mathematical Software algorithm 726.\\n    \\\"\\\"\\\"\\n\\n    d = ctx.zeros(n, 1)\\n    e = ctx.zeros(n, 1)\\n    z = ctx.zeros(1, n)\\n\\n    z[0,0] = 1\\n\\n    if qtype == \\\"legendre\\\":\\n        # legendre on the range -1 +1 , abramowitz, table 25.4, p.916\\n        w = 2\\n        for i in xrange(n):\\n            j = i + 1\\n            e[i] = ctx.sqrt(j * j / (4 * j * j - ctx.mpf(1)))\\n    elif qtype == \\\"legendre01\\\":\\n        # legendre shifted to 0 1        , abramowitz, table 25.8, p.921\\n        w = 1\\n        for i in xrange(n):\\n            d[i] = 1 / ctx.mpf(2)\\n            j = i + 1\\n            e[i] = ctx.sqrt(j * j / (16 * j * j - ctx.mpf(4)))\\n    elif qtype == \\\"hermite\\\":\\n        # hermite on the range -inf +inf , abramowitz, table 25.10,p.924\\n        w = ctx.sqrt(ctx.pi)\\n        for i in xrange(n):\\n            j = i + 1\\n            e[i] = ctx.sqrt(j / ctx.mpf(2))\\n    elif qtype == \\\"laguerre\\\":\\n        # laguerre on the range 0 +inf , abramowitz, table 25.9, p. 923\\n        w = 1\\n        for i in xrange(n):\\n            j = i + 1\\n            d[i] = 2 * j - 1\\n            e[i] = j\\n    elif qtype==\\\"chebyshev1\\\":\\n        # chebyshev polynimials of the first kind\\n        w = ctx.pi\\n        for i in xrange(n):\\n            e[i] = 1 / ctx.mpf(2)\\n        e[0] = ctx.sqrt(1 / ctx.mpf(2))\\n    elif qtype == \\\"chebyshev2\\\":\\n        # chebyshev polynimials of the second kind\\n        w = ctx.pi / 2\\n        for i in xrange(n):\\n            e[i] = 1 / ctx.mpf(2)\\n    elif qtype == \\\"glaguerre\\\":\\n        # generalized laguerre on the range 0 +inf\\n        w = ctx.gamma(1 + alpha)\\n        for i in xrange(n):\\n            j = i + 1\\n            d[i] = 2 * j - 1 + alpha\\n            e[i] = ctx.sqrt(j * (j + alpha))\\n    elif qtype == \\\"jacobi\\\":\\n        # jacobi polynomials\\n        alpha = ctx.mpf(alpha)\\n        beta = ctx.mpf(beta)\\n        ab = alpha + beta\\n        abi = ab + 2\\n        w = (2**(ab+1)) * ctx.gamma(alpha + 1) * ctx.gamma(beta + 1) / ctx.gamma(abi)\\n        d[0] = (beta - alpha) / abi\\n        e[0] = ctx.sqrt(4 * (1 + alpha) * (1 + beta) / ((abi + 1) * (abi * abi)))\\n        a2b2 = beta * beta - alpha * alpha\\n        for i in xrange(1, n):\\n            j = i + 1\\n            abi = 2 * j + ab\\n            d[i] = a2b2 / ((abi - 2) * abi)\\n            e[i] = ctx.sqrt(4 * j * (j + alpha) * (j + beta) * (j + ab) / ((abi * abi - 1) * abi * abi))\\n    elif isinstance(qtype, str):\\n        raise ValueError(\\\"unknown quadrature rule \\\\\\\"%s\\\\\\\"\\\" % qtype)\\n    elif not isinstance(qtype, str):\\n        w = qtype(d, e)\\n    else:\\n        assert 0\\n\\n    tridiag_eigen(ctx, d, e, z)\\n\\n    for i in xrange(len(z)):\\n        z[i] *= z[i]\\n\\n    z = z.transpose()\\n    return (d, w * z)\\n\\n##################################################################################################\\n##################################################################################################\\n##################################################################################################\\n\\ndef svd_r_raw(ctx, A, V = False, calc_u = False):\\n    \\\"\\\"\\\"\\n    This routine computes the singular value decomposition of a matrix A.\\n    Given A, two orthogonal matrices U and V are calculated such that\\n\\n                    A = U S V\\n\\n    where S is a suitable shaped matrix whose off-diagonal elements are zero.\\n    The diagonal elements of S are the singular values of A, i.e. the\\n    squareroots of the eigenvalues of A' A or A A'. Here ' denotes the transpose.\\n    Householder bidiagonalization and a variant of the QR algorithm is used.\\n\\n    overview of the matrices :\\n\\n      A : m*n       A gets replaced by U\\n      U : m*n       U replaces A. If n>m then only the first m*m block of U is\\n                    non-zero. column-orthogonal: U' U = B\\n                    here B is a n*n matrix whose first min(m,n) diagonal\\n                    elements are 1 and all other elements are zero.\\n      S : n*n       diagonal matrix, only the diagonal elements are stored in\\n                    the array S. only the first min(m,n) diagonal elements are non-zero.\\n      V : n*n       orthogonal: V V' = V' V = 1\\n\\n    parameters:\\n      A        (input/output) On input, A contains a real matrix of shape m*n.\\n               On output, if calc_u is true A contains the column-orthogonal\\n               matrix U; otherwise A is simply used as workspace and thus destroyed.\\n\\n      V        (input/output) if false, the matrix V is not calculated. otherwise\\n               V must be a matrix of shape n*n.\\n\\n      calc_u   (input) If true, the matrix U is calculated and replaces A.\\n               if false, U is not calculated and A is simply destroyed\\n\\n    return value:\\n      S        an array of length n containing the singular values of A sorted by\\n               decreasing magnitude. only the first min(m,n) elements are non-zero.\\n\\n    This routine is a python translation of the fortran routine svd.f in the\\n    software library EISPACK (see netlib.org) which itself is based on the\\n    algol procedure svd described in:\\n      - num. math. 14, 403-420(1970) by golub and reinsch.\\n      - wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).\\n\\n    \\\"\\\"\\\"\\n\\n    m, n = A.rows, A.cols\\n\\n    S = ctx.zeros(n, 1)\\n\\n    # work is a temporary array of size n\\n    work = ctx.zeros(n, 1)\\n\\n    g = scale = anorm = 0\\n    maxits = 3 * ctx.dps\\n\\n    for i in xrange(n):     # householder reduction to bidiagonal form\\n        work[i] = scale*g\\n        g = s = scale = 0\\n        if i < m:\\n            for k in xrange(i, m):\\n                scale += ctx.fabs(A[k,i])\\n            if scale != 0:\\n                for k in xrange(i, m):\\n                    A[k,i] /= scale\\n                    s += A[k,i] * A[k,i]\\n                f = A[i,i]\\n                g = -ctx.sqrt(s)\\n                if f < 0:\\n                    g = -g\\n                h = f * g - s\\n                A[i,i] = f - g\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i, m):\\n                        s += A[k,i] * A[k,j]\\n                    f = s / h\\n                    for k in xrange(i, m):\\n                        A[k,j] += f * A[k,i]\\n                for k in xrange(i,m):\\n                    A[k,i] *= scale\\n\\n        S[i] = scale * g\\n        g = s = scale = 0\\n\\n        if i < m and i != n - 1:\\n            for k in xrange(i+1, n):\\n                scale += ctx.fabs(A[i,k])\\n            if scale:\\n                for k in xrange(i+1, n):\\n                    A[i,k] /= scale\\n                    s += A[i,k] * A[i,k]\\n                f = A[i,i+1]\\n                g = -ctx.sqrt(s)\\n                if f < 0:\\n                    g = -g\\n                h = f * g - s\\n                A[i,i+1] = f - g\\n\\n                for k in xrange(i+1, n):\\n                    work[k] = A[i,k] / h\\n\\n                for j in xrange(i+1, m):\\n                    s = 0\\n                    for k in xrange(i+1, n):\\n                        s += A[j,k] * A[i,k]\\n                    for k in xrange(i+1, n):\\n                        A[j,k] += s * work[k]\\n\\n                for k in xrange(i+1, n):\\n                    A[i,k] *= scale\\n\\n        anorm = max(anorm, ctx.fabs(S[i]) + ctx.fabs(work[i]))\\n\\n    if not isinstance(V, bool):\\n        for i in xrange(n-2, -1, -1):     # accumulation of right hand transformations\\n            V[i+1,i+1] = 1\\n\\n            if work[i+1] != 0:\\n                for j in xrange(i+1, n):\\n                    V[i,j] = (A[i,j] / A[i,i+1]) / work[i+1]\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i+1, n):\\n                        s += A[i,k] * V[j,k]\\n                    for k in xrange(i+1, n):\\n                        V[j,k] += s * V[i,k]\\n\\n            for j in xrange(i+1, n):\\n                V[j,i] = V[i,j] = 0\\n\\n        V[0,0] = 1\\n\\n    if m<n : minnm = m\\n    else   : minnm = n\\n\\n    if calc_u:\\n        for i in xrange(minnm-1, -1, -1): # accumulation of left hand transformations\\n            g = S[i]\\n            for j in xrange(i+1, n):\\n                A[i,j] = 0\\n            if g != 0:\\n                g = 1 / g\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i+1, m):\\n                        s += A[k,i] * A[k,j]\\n                    f = (s / A[i,i]) * g\\n                    for k in xrange(i, m):\\n                        A[k,j] += f * A[k,i]\\n                for j in xrange(i, m):\\n                    A[j,i] *= g\\n            else:\\n                for j in xrange(i, m):\\n                    A[j,i] = 0\\n            A[i,i] += 1\\n\\n    for k in xrange(n - 1, -1, -1):\\n        # diagonalization of the bidiagonal form:\\n        #   loop over singular values, and over allowed itations\\n\\n        its = 0\\n        while 1:\\n            its += 1\\n            flag = True\\n\\n            for l in xrange(k, -1, -1):\\n                nm = l-1\\n\\n                if ctx.fabs(work[l]) + anorm == anorm:\\n                    flag = False\\n                    break\\n\\n                if ctx.fabs(S[nm]) + anorm == anorm:\\n                    break\\n\\n            if flag:\\n                c = 0\\n                s = 1\\n                for i in xrange(l, k + 1):\\n                    f = s * work[i]\\n                    work[i] *= c\\n                    if ctx.fabs(f) + anorm == anorm:\\n                        break\\n                    g = S[i]\\n                    h = ctx.hypot(f, g)\\n                    S[i] = h\\n                    h = 1 / h\\n                    c = g * h\\n                    s = - f * h\\n\\n                    if calc_u:\\n                        for j in xrange(m):\\n                            y = A[j,nm]\\n                            z = A[j,i]\\n                            A[j,nm] = y * c + z * s\\n                            A[j,i]  = z * c - y * s\\n\\n            z = S[k]\\n\\n            if l == k:               # convergence\\n                if z < 0:            # singular value is made nonnegative\\n                    S[k] = -z\\n                    if not isinstance(V, bool):\\n                        for j in xrange(n):\\n                            V[k,j] = -V[k,j]\\n                break\\n\\n            if its >= maxits:\\n                raise RuntimeError(\\\"svd: no convergence to an eigenvalue after %d iterations\\\" % its)\\n\\n            x = S[l]         # shift from bottom 2 by 2 minor\\n            nm = k-1\\n            y = S[nm]\\n            g = work[nm]\\n            h = work[k]\\n            f = ((y - z) * (y + z) + (g - h) * (g + h))/(2 * h * y)\\n            g = ctx.hypot(f, 1)\\n            if f >= 0: f = ((x - z) * (x + z) + h * ((y / (f + g)) - h)) / x\\n            else:      f = ((x - z) * (x + z) + h * ((y / (f - g)) - h)) / x\\n\\n            c = s = 1         # next qt transformation\\n\\n            for j in xrange(l, nm + 1):\\n                g = work[j+1]\\n                y = S[j+1]\\n                h = s * g\\n                g = c * g\\n                z = ctx.hypot(f, h)\\n                work[j] = z\\n                c = f / z\\n                s = h / z\\n                f = x * c + g * s\\n                g = g * c - x * s\\n                h = y * s\\n                y *= c\\n                if not isinstance(V, bool):\\n                    for jj in xrange(n):\\n                        x = V[j  ,jj]\\n                        z = V[j+1,jj]\\n                        V[j    ,jj]= x * c + z * s\\n                        V[j+1  ,jj]= z * c - x * s\\n                z = ctx.hypot(f, h)\\n                S[j] = z\\n                if z != 0:            # rotation can be arbitray if z=0\\n                    z = 1 / z\\n                    c = f * z\\n                    s = h * z\\n                f = c * g + s * y\\n                x = c * y - s * g\\n\\n                if calc_u:\\n                    for jj in xrange(m):\\n                        y = A[jj,j  ]\\n                        z = A[jj,j+1]\\n                        A[jj,j    ] = y * c + z * s\\n                        A[jj,j+1  ] = z * c - y * s\\n\\n            work[l] = 0\\n            work[k] = f\\n            S[k] = x\\n\\n    ##########################\\n\\n    # Sort singular values into decreasing order (bubble-sort)\\n\\n    for i in xrange(n):\\n        imax = i\\n        s = ctx.fabs(S[i])         # s is the current maximal element\\n\\n        for j in xrange(i + 1, n):\\n            c = ctx.fabs(S[j])\\n            if c > s:\\n                s = c\\n                imax = j\\n\\n        if imax != i:\\n            # swap singular values\\n\\n            z = S[i]\\n            S[i] = S[imax]\\n            S[imax] = z\\n\\n            if calc_u:\\n                for j in xrange(m):\\n                    z = A[j,i]\\n                    A[j,i] = A[j,imax]\\n                    A[j,imax] = z\\n\\n            if not isinstance(V, bool):\\n                for j in xrange(n):\\n                    z = V[i,j]\\n                    V[i,j] = V[imax,j]\\n                    V[imax,j] = z\\n\\n    return S\\n\\n#######################\\n\\ndef svd_c_raw(ctx, A, V = False, calc_u = False):\\n    \\\"\\\"\\\"\\n    This routine computes the singular value decomposition of a matrix A.\\n    Given A, two unitary matrices U and V are calculated such that\\n\\n                    A = U S V\\n\\n    where S is a suitable shaped matrix whose off-diagonal elements are zero.\\n    The diagonal elements of S are the singular values of A, i.e. the\\n    squareroots of the eigenvalues of A' A or A A'. Here ' denotes the hermitian\\n    transpose (i.e. transposition and conjugation). Householder bidiagonalization\\n    and a variant of the QR algorithm is used.\\n\\n    overview of the matrices :\\n\\n      A : m*n       A gets replaced by U\\n      U : m*n       U replaces A. If n>m then only the first m*m block of U is\\n                    non-zero. column-unitary: U' U = B\\n                    here B is a n*n matrix whose first min(m,n) diagonal\\n                    elements are 1 and all other elements are zero.\\n      S : n*n       diagonal matrix, only the diagonal elements are stored in\\n                    the array S. only the first min(m,n) diagonal elements are non-zero.\\n      V : n*n       unitary: V V' = V' V = 1\\n\\n    parameters:\\n      A        (input/output) On input, A contains a complex matrix of shape m*n.\\n               On output, if calc_u is true A contains the column-unitary\\n               matrix U; otherwise A is simply used as workspace and thus destroyed.\\n\\n      V        (input/output) if false, the matrix V is not calculated. otherwise\\n               V must be a matrix of shape n*n.\\n\\n      calc_u   (input) If true, the matrix U is calculated and replaces A.\\n               if false, U is not calculated and A is simply destroyed\\n\\n    return value:\\n      S        an array of length n containing the singular values of A sorted by\\n               decreasing magnitude. only the first min(m,n) elements are non-zero.\\n\\n    This routine is a python translation of the fortran routine svd.f in the\\n    software library EISPACK (see netlib.org) which itself is based on the\\n    algol procedure svd described in:\\n      - num. math. 14, 403-420(1970) by golub and reinsch.\\n      - wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).\\n\\n    \\\"\\\"\\\"\\n\\n    m, n = A.rows, A.cols\\n\\n    S = ctx.zeros(n, 1)\\n\\n    # work is a temporary array of size n\\n    work  = ctx.zeros(n, 1)\\n    lbeta = ctx.zeros(n, 1)\\n    rbeta = ctx.zeros(n, 1)\\n    dwork = ctx.zeros(n, 1)\\n\\n    g = scale = anorm = 0\\n    maxits = 3 * ctx.dps\\n\\n    for i in xrange(n):         # householder reduction to bidiagonal form\\n        dwork[i] = scale * g    # dwork are the side-diagonal elements\\n        g = s = scale = 0\\n        if i < m:\\n            for k in xrange(i, m):\\n                scale += ctx.fabs(ctx.re(A[k,i])) + ctx.fabs(ctx.im(A[k,i]))\\n            if scale != 0:\\n                for k in xrange(i, m):\\n                    A[k,i] /= scale\\n                    ar = ctx.re(A[k,i])\\n                    ai = ctx.im(A[k,i])\\n                    s += ar * ar + ai * ai\\n                f = A[i,i]\\n                g = -ctx.sqrt(s)\\n                if ctx.re(f) < 0:\\n                    beta = -g - ctx.conj(f)\\n                    g = -g\\n                else:\\n                    beta = -g + ctx.conj(f)\\n                beta /= ctx.conj(beta)\\n                beta += 1\\n                h = 2 * (ctx.re(f) * g - s)\\n                A[i,i] = f - g\\n                beta /= h\\n                lbeta[i] = (beta / scale) / scale\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i, m):\\n                        s += ctx.conj(A[k,i]) * A[k,j]\\n                    f = beta * s\\n                    for k in xrange(i, m):\\n                        A[k,j] += f * A[k,i]\\n                for k in xrange(i, m):\\n                    A[k,i] *= scale\\n\\n        S[i] = scale * g     # S are the diagonal elements\\n        g = s = scale = 0\\n\\n        if i < m and i != n - 1:\\n            for k in xrange(i+1, n):\\n                scale += ctx.fabs(ctx.re(A[i,k])) + ctx.fabs(ctx.im(A[i,k]))\\n            if scale:\\n                for k in xrange(i+1, n):\\n                    A[i,k] /= scale\\n                    ar = ctx.re(A[i,k])\\n                    ai = ctx.im(A[i,k])\\n                    s += ar * ar + ai * ai\\n                f = A[i,i+1]\\n                g = -ctx.sqrt(s)\\n                if ctx.re(f) < 0:\\n                    beta = -g - ctx.conj(f)\\n                    g = -g\\n                else:\\n                    beta = -g + ctx.conj(f)\\n\\n                beta /= ctx.conj(beta)\\n                beta += 1\\n\\n                h = 2 * (ctx.re(f) * g - s)\\n                A[i,i+1] = f - g\\n\\n                beta /= h\\n                rbeta[i] = (beta / scale) / scale\\n\\n                for k in xrange(i+1, n):\\n                    work[k] = A[i, k]\\n\\n                for j in xrange(i+1, m):\\n                    s = 0\\n                    for k in xrange(i+1, n):\\n                        s += ctx.conj(A[i,k]) * A[j,k]\\n                    f = s * beta\\n                    for k in xrange(i+1,n):\\n                        A[j,k] += f * work[k]\\n\\n                for k in xrange(i+1, n):\\n                    A[i,k] *= scale\\n\\n        anorm = max(anorm,ctx.fabs(S[i]) + ctx.fabs(dwork[i]))\\n\\n    if not isinstance(V, bool):\\n        for i in xrange(n-2, -1, -1):     # accumulation of right hand transformations\\n            V[i+1,i+1] = 1\\n\\n            if dwork[i+1] != 0:\\n                f = ctx.conj(rbeta[i])\\n                for j in xrange(i+1, n):\\n                    V[i,j] = A[i,j] * f\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i+1, n):\\n                        s += ctx.conj(A[i,k]) * V[j,k]\\n                    for k in xrange(i+1, n):\\n                        V[j,k] += s * V[i,k]\\n\\n            for j in xrange(i+1,n):\\n                V[j,i] = V[i,j] = 0\\n\\n        V[0,0] = 1\\n\\n    if m < n : minnm = m\\n    else     : minnm = n\\n\\n    if calc_u:\\n        for i in xrange(minnm-1, -1, -1): # accumulation of left hand transformations\\n            g = S[i]\\n            for j in xrange(i+1, n):\\n                A[i,j] = 0\\n            if g != 0:\\n                g = 1 / g\\n                for j in xrange(i+1, n):\\n                    s = 0\\n                    for k in xrange(i+1, m):\\n                        s += ctx.conj(A[k,i]) * A[k,j]\\n                    f = s * ctx.conj(lbeta[i])\\n                    for k in xrange(i, m):\\n                        A[k,j] += f * A[k,i]\\n                for j in xrange(i, m):\\n                    A[j,i] *= g\\n            else:\\n                for j in xrange(i, m):\\n                    A[j,i] = 0\\n            A[i,i] += 1\\n\\n    for k in xrange(n-1, -1, -1):\\n        # diagonalization of the bidiagonal form:\\n        #   loop over singular values, and over allowed itations\\n\\n        its = 0\\n        while 1:\\n            its += 1\\n            flag = True\\n\\n            for l in xrange(k, -1, -1):\\n                nm = l - 1\\n\\n                if ctx.fabs(dwork[l]) + anorm == anorm:\\n                    flag = False\\n                    break\\n\\n                if ctx.fabs(S[nm]) + anorm == anorm:\\n                    break\\n\\n            if flag:\\n                c = 0\\n                s = 1\\n                for i in xrange(l, k+1):\\n                    f = s * dwork[i]\\n                    dwork[i] *= c\\n                    if ctx.fabs(f) + anorm == anorm:\\n                        break\\n                    g = S[i]\\n                    h = ctx.hypot(f, g)\\n                    S[i] = h\\n                    h = 1 / h\\n                    c = g * h\\n                    s = -f * h\\n\\n                    if calc_u:\\n                        for j in xrange(m):\\n                            y = A[j,nm]\\n                            z = A[j,i]\\n                            A[j,nm]= y * c + z * s\\n                            A[j,i] = z * c - y * s\\n\\n            z = S[k]\\n\\n            if l == k:         # convergence\\n                if z < 0:    # singular value is made nonnegative\\n                    S[k] = -z\\n                    if not isinstance(V, bool):\\n                        for j in xrange(n):\\n                            V[k,j] = -V[k,j]\\n                break\\n\\n            if its >= maxits:\\n                raise RuntimeError(\\\"svd: no convergence to an eigenvalue after %d iterations\\\" % its)\\n\\n            x = S[l]         # shift from bottom 2 by 2 minor\\n            nm = k-1\\n            y = S[nm]\\n            g = dwork[nm]\\n            h = dwork[k]\\n            f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2 * h * y)\\n            g = ctx.hypot(f, 1)\\n            if f >=0: f = (( x - z) *( x + z) + h *((y / (f + g)) - h)) / x\\n            else:     f = (( x - z) *( x + z) + h *((y / (f - g)) - h)) / x\\n\\n            c = s = 1         # next qt transformation\\n\\n            for j in xrange(l, nm + 1):\\n                g = dwork[j+1]\\n                y = S[j+1]\\n                h = s * g\\n                g = c * g\\n                z = ctx.hypot(f, h)\\n                dwork[j] = z\\n                c = f / z\\n                s = h / z\\n                f = x * c + g * s\\n                g = g * c - x * s\\n                h = y * s\\n                y *= c\\n                if not isinstance(V, bool):\\n                    for jj in xrange(n):\\n                        x = V[j  ,jj]\\n                        z = V[j+1,jj]\\n                        V[j    ,jj]= x * c + z * s\\n                        V[j+1,jj  ]= z * c - x * s\\n                z = ctx.hypot(f, h)\\n                S[j] = z\\n                if z != 0:            # rotation can be arbitray if z=0\\n                    z = 1 / z\\n                    c = f * z\\n                    s = h * z\\n                f = c * g + s * y\\n                x = c * y - s * g\\n                if calc_u:\\n                    for jj in xrange(m):\\n                        y = A[jj,j  ]\\n                        z = A[jj,j+1]\\n                        A[jj,j    ]= y * c + z * s\\n                        A[jj,j+1  ]= z * c - y * s\\n\\n            dwork[l] = 0\\n            dwork[k] = f\\n            S[k] = x\\n\\n    ##########################\\n\\n    # Sort singular values into decreasing order (bubble-sort)\\n\\n    for i in xrange(n):\\n        imax = i\\n        s = ctx.fabs(S[i])         # s is the current maximal element\\n\\n        for j in xrange(i + 1, n):\\n            c = ctx.fabs(S[j])\\n            if c > s:\\n                s = c\\n                imax = j\\n\\n        if imax != i:\\n            # swap singular values\\n\\n            z = S[i]\\n            S[i] = S[imax]\\n            S[imax] = z\\n\\n            if calc_u:\\n                for j in xrange(m):\\n                    z = A[j,i]\\n                    A[j,i] = A[j,imax]\\n                    A[j,imax] = z\\n\\n            if not isinstance(V, bool):\\n                for j in xrange(n):\\n                    z = V[i,j]\\n                    V[i,j] = V[imax,j]\\n                    V[imax,j] = z\\n\\n    return S\\n\\n##################################################################################################\\n\\n@defun\\ndef svd_r(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine computes the singular value decomposition of a matrix A.\\n    Given A, two orthogonal matrices U and V are calculated such that\\n\\n           A = U S V        and        U' U = 1         and         V V' = 1\\n\\n    where S is a suitable shaped matrix whose off-diagonal elements are zero.\\n    Here ' denotes the transpose. The diagonal elements of S are the singular\\n    values of A, i.e. the squareroots of the eigenvalues of A' A or A A'.\\n\\n    input:\\n      A             : a real matrix of shape (m, n)\\n      full_matrices : if true, U and V are of shape (m, m) and (n, n).\\n                      if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).\\n      compute_uv    : if true, U and V are calculated. if false, only S is calculated.\\n      overwrite_a   : if true, allows modification of A which may improve\\n                      performance. if false, A is not modified.\\n\\n    output:\\n      U : an orthogonal matrix: U' U = 1. if full_matrices is true, U is of\\n          shape (m, m). ortherwise it is of shape (m, min(m, n)).\\n\\n      S : an array of length min(m, n) containing the singular values of A sorted by\\n          decreasing magnitude.\\n\\n      V : an orthogonal matrix: V V' = 1. if full_matrices is true, V is of\\n          shape (n, n). ortherwise it is of shape (min(m, n), n).\\n\\n    return value:\\n\\n           S          if compute_uv is false\\n       (U, S, V)      if compute_uv is true\\n\\n    overview of the matrices:\\n\\n      full_matrices true:\\n        A           : m*n\\n        U           : m*m     U' U  = 1\\n        S as matrix : m*n\\n        V           : n*n     V  V' = 1\\n\\n     full_matrices false:\\n        A           : m*n\\n        U           : m*min(n,m)             U' U  = 1\\n        S as matrix : min(m,n)*min(m,n)\\n        V           : min(m,n)*n             V  V' = 1\\n\\n    examples:\\n\\n       >>> from mpmath import mp\\n       >>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]])\\n       >>> S = mp.svd_r(A, compute_uv = False)\\n       >>> print(S)\\n       [6.0]\\n       [3.0]\\n       [1.0]\\n\\n       >>> U, S, V = mp.svd_r(A)\\n       >>> print(mp.chop(A - U * mp.diag(S) * V))\\n       [0.0  0.0  0.0]\\n       [0.0  0.0  0.0]\\n       [0.0  0.0  0.0]\\n\\n\\n    see also: svd, svd_c\\n    \\\"\\\"\\\"\\n\\n    m, n = A.rows, A.cols\\n\\n    if not compute_uv:\\n        if not overwrite_a:\\n            A = A.copy()\\n        S = svd_r_raw(ctx, A, V = False, calc_u = False)\\n        S = S[:min(m,n)]\\n        return S\\n\\n    if full_matrices and n < m:\\n        V = ctx.zeros(m, m)\\n        A0 = ctx.zeros(m, m)\\n        A0[:,:n] = A\\n        S = svd_r_raw(ctx, A0, V, calc_u = True)\\n\\n        S = S[:n]\\n        V = V[:n,:n]\\n\\n        return (A0, S, V)\\n    else:\\n        if not overwrite_a:\\n            A = A.copy()\\n        V = ctx.zeros(n, n)\\n        S = svd_r_raw(ctx, A, V, calc_u = True)\\n\\n        if n > m:\\n            if full_matrices == False:\\n                V = V[:m,:]\\n\\n            S = S[:m]\\n            A = A[:,:m]\\n\\n        return (A, S, V)\\n\\n##############################\\n\\n@defun\\ndef svd_c(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    This routine computes the singular value decomposition of a matrix A.\\n    Given A, two unitary matrices U and V are calculated such that\\n\\n           A = U S V        and        U' U = 1         and         V V' = 1\\n\\n    where S is a suitable shaped matrix whose off-diagonal elements are zero.\\n    Here ' denotes the hermitian transpose (i.e. transposition and complex\\n    conjugation). The diagonal elements of S are the singular values of A,\\n    i.e. the squareroots of the eigenvalues of A' A or A A'.\\n\\n    input:\\n      A             : a complex matrix of shape (m, n)\\n      full_matrices : if true, U and V are of shape (m, m) and (n, n).\\n                      if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).\\n      compute_uv    : if true, U and V are calculated. if false, only S is calculated.\\n      overwrite_a   : if true, allows modification of A which may improve\\n                      performance. if false, A is not modified.\\n\\n    output:\\n      U : an unitary matrix: U' U = 1. if full_matrices is true, U is of\\n          shape (m, m). ortherwise it is of shape (m, min(m, n)).\\n\\n      S : an array of length min(m, n) containing the singular values of A sorted by\\n          decreasing magnitude.\\n\\n      V : an unitary matrix: V V' = 1. if full_matrices is true, V is of\\n          shape (n, n). ortherwise it is of shape (min(m, n), n).\\n\\n    return value:\\n\\n           S          if compute_uv is false\\n       (U, S, V)      if compute_uv is true\\n\\n    overview of the matrices:\\n\\n      full_matrices true:\\n        A           : m*n\\n        U           : m*m     U' U  = 1\\n        S as matrix : m*n\\n        V           : n*n     V  V' = 1\\n\\n     full_matrices false:\\n        A           : m*n\\n        U           : m*min(n,m)             U' U  = 1\\n        S as matrix : min(m,n)*min(m,n)\\n        V           : min(m,n)*n             V  V' = 1\\n\\n    example:\\n      >>> from mpmath import mp\\n      >>> A = mp.matrix([[-2j, -1-3j, -2+2j], [2-2j, -1-3j, 1], [-3+1j,-2j,0]])\\n      >>> S = mp.svd_c(A, compute_uv = False)\\n      >>> print(mp.chop(S - mp.matrix([mp.sqrt(34), mp.sqrt(15), mp.sqrt(6)])))\\n      [0.0]\\n      [0.0]\\n      [0.0]\\n\\n      >>> U, S, V = mp.svd_c(A)\\n      >>> print(mp.chop(A - U * mp.diag(S) * V))\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n      [0.0  0.0  0.0]\\n\\n    see also: svd, svd_r\\n    \\\"\\\"\\\"\\n\\n    m, n = A.rows, A.cols\\n\\n    if not compute_uv:\\n        if not overwrite_a:\\n            A = A.copy()\\n        S = svd_c_raw(ctx, A, V = False, calc_u = False)\\n        S = S[:min(m,n)]\\n        return S\\n\\n    if full_matrices and n < m:\\n        V = ctx.zeros(m, m)\\n        A0 = ctx.zeros(m, m)\\n        A0[:,:n] = A\\n        S = svd_c_raw(ctx, A0, V, calc_u = True)\\n\\n        S = S[:n]\\n        V = V[:n,:n]\\n\\n        return (A0, S, V)\\n    else:\\n        if not overwrite_a:\\n            A = A.copy()\\n        V = ctx.zeros(n, n)\\n        S = svd_c_raw(ctx, A, V, calc_u = True)\\n\\n        if n > m:\\n            if full_matrices == False:\\n                V = V[:m,:]\\n\\n            S = S[:m]\\n            A = A[:,:m]\\n\\n        return (A, S, V)\\n\\n@defun\\ndef svd(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):\\n    \\\"\\\"\\\"\\n    \\\"svd\\\" is a unified interface for \\\"svd_r\\\" and \\\"svd_c\\\". Depending on\\n    whether A is real or complex the appropriate function is called.\\n\\n    This routine computes the singular value decomposition of a matrix A.\\n    Given A, two orthogonal (A real) or unitary (A complex) matrices U and V\\n    are calculated such that\\n\\n           A = U S V        and        U' U = 1         and         V V' = 1\\n\\n    where S is a suitable shaped matrix whose off-diagonal elements are zero.\\n    Here ' denotes the hermitian transpose (i.e. transposition and complex\\n    conjugation). The diagonal elements of S are the singular values of A,\\n    i.e. the squareroots of the eigenvalues of A' A or A A'.\\n\\n    input:\\n      A             : a real or complex matrix of shape (m, n)\\n      full_matrices : if true, U and V are of shape (m, m) and (n, n).\\n                      if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).\\n      compute_uv    : if true, U and V are calculated. if false, only S is calculated.\\n      overwrite_a   : if true, allows modification of A which may improve\\n                      performance. if false, A is not modified.\\n\\n    output:\\n      U : an orthogonal or unitary matrix: U' U = 1. if full_matrices is true, U is of\\n          shape (m, m). ortherwise it is of shape (m, min(m, n)).\\n\\n      S : an array of length min(m, n) containing the singular values of A sorted by\\n          decreasing magnitude.\\n\\n      V : an orthogonal or unitary matrix: V V' = 1. if full_matrices is true, V is of\\n          shape (n, n). ortherwise it is of shape (min(m, n), n).\\n\\n    return value:\\n\\n           S          if compute_uv is false\\n       (U, S, V)      if compute_uv is true\\n\\n    overview of the matrices:\\n\\n      full_matrices true:\\n        A           : m*n\\n        U           : m*m     U' U  = 1\\n        S as matrix : m*n\\n        V           : n*n     V  V' = 1\\n\\n     full_matrices false:\\n        A           : m*n\\n        U           : m*min(n,m)             U' U  = 1\\n        S as matrix : min(m,n)*min(m,n)\\n        V           : min(m,n)*n             V  V' = 1\\n\\n    examples:\\n\\n       >>> from mpmath import mp\\n       >>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]])\\n       >>> S = mp.svd(A, compute_uv = False)\\n       >>> print(S)\\n       [6.0]\\n       [3.0]\\n       [1.0]\\n\\n       >>> U, S, V = mp.svd(A)\\n       >>> print(mp.chop(A - U * mp.diag(S) * V))\\n       [0.0  0.0  0.0]\\n       [0.0  0.0  0.0]\\n       [0.0  0.0  0.0]\\n\\n    see also: svd_r, svd_c\\n    \\\"\\\"\\\"\\n\\n    iscomplex = any(type(x) is ctx.mpc for x in A)\\n\\n    if iscomplex:\\n        return ctx.svd_c(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a)\\n    else:\\n        return ctx.svd_r(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a)\\n\\n\\nfrom ..libmp.backend import xrange\\nimport warnings\\n\\n# TODO: interpret list as vectors (for multiplication)\\n\\nrowsep = '\\\\n'\\ncolsep = '  '\\n\\nclass _matrix(object):\\n    \\\"\\\"\\\"\\n    Numerical matrix.\\n\\n    Specify the dimensions or the data as a nested list.\\n    Elements default to zero.\\n    Use a flat list to create a column vector easily.\\n\\n    The datatype of the context (mpf for mp, mpi for iv, and float for fp) is used to store the data.\\n\\n    Creating matrices\\n    -----------------\\n\\n    Matrices in mpmath are implemented using dictionaries. Only non-zero values\\n    are stored, so it is cheap to represent sparse matrices.\\n\\n    The most basic way to create one is to use the ``matrix`` class directly.\\n    You can create an empty matrix specifying the dimensions:\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15\\n        >>> matrix(2)\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n        >>> matrix(2, 3)\\n        matrix(\\n        [['0.0', '0.0', '0.0'],\\n         ['0.0', '0.0', '0.0']])\\n\\n    Calling ``matrix`` with one dimension will create a square matrix.\\n\\n    To access the dimensions of a matrix, use the ``rows`` or ``cols`` keyword:\\n\\n        >>> A = matrix(3, 2)\\n        >>> A\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n        >>> A.rows\\n        3\\n        >>> A.cols\\n        2\\n\\n    You can also change the dimension of an existing matrix. This will set the\\n    new elements to 0. If the new dimension is smaller than before, the\\n    concerning elements are discarded:\\n\\n        >>> A.rows = 2\\n        >>> A\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n\\n    Internally ``mpmathify`` is used every time an element is set. This\\n    is done using the syntax A[row,column], counting from 0:\\n\\n        >>> A = matrix(2)\\n        >>> A[1,1] = 1 + 1j\\n        >>> A\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', mpc(real='1.0', imag='1.0')]])\\n\\n    A more comfortable way to create a matrix lets you use nested lists:\\n\\n        >>> matrix([[1, 2], [3, 4]])\\n        matrix(\\n        [['1.0', '2.0'],\\n         ['3.0', '4.0']])\\n\\n    Convenient advanced functions are available for creating various standard\\n    matrices, see ``zeros``, ``ones``, ``diag``, ``eye``, ``randmatrix`` and\\n    ``hilbert``.\\n\\n    Vectors\\n    .......\\n\\n    Vectors may also be represented by the ``matrix`` class (with rows = 1 or cols = 1).\\n    For vectors there are some things which make life easier. A column vector can\\n    be created using a flat list, a row vectors using an almost flat nested list::\\n\\n        >>> matrix([1, 2, 3])\\n        matrix(\\n        [['1.0'],\\n         ['2.0'],\\n         ['3.0']])\\n        >>> matrix([[1, 2, 3]])\\n        matrix(\\n        [['1.0', '2.0', '3.0']])\\n\\n    Optionally vectors can be accessed like lists, using only a single index::\\n\\n        >>> x = matrix([1, 2, 3])\\n        >>> x[1]\\n        mpf('2.0')\\n        >>> x[1,0]\\n        mpf('2.0')\\n\\n    Other\\n    .....\\n\\n    Like you probably expected, matrices can be printed::\\n\\n        >>> print randmatrix(3) # doctest:+SKIP\\n        [ 0.782963853573023  0.802057689719883  0.427895717335467]\\n        [0.0541876859348597  0.708243266653103  0.615134039977379]\\n        [ 0.856151514955773  0.544759264818486  0.686210904770947]\\n\\n    Use ``nstr`` or ``nprint`` to specify the number of digits to print::\\n\\n        >>> nprint(randmatrix(5), 3) # doctest:+SKIP\\n        [2.07e-1  1.66e-1  5.06e-1  1.89e-1  8.29e-1]\\n        [6.62e-1  6.55e-1  4.47e-1  4.82e-1  2.06e-2]\\n        [4.33e-1  7.75e-1  6.93e-2  2.86e-1  5.71e-1]\\n        [1.01e-1  2.53e-1  6.13e-1  3.32e-1  2.59e-1]\\n        [1.56e-1  7.27e-2  6.05e-1  6.67e-2  2.79e-1]\\n\\n    As matrices are mutable, you will need to copy them sometimes::\\n\\n        >>> A = matrix(2)\\n        >>> A\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n        >>> B = A.copy()\\n        >>> B[0,0] = 1\\n        >>> B\\n        matrix(\\n        [['1.0', '0.0'],\\n         ['0.0', '0.0']])\\n        >>> A\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n\\n    Finally, it is possible to convert a matrix to a nested list. This is very useful,\\n    as most Python libraries involving matrices or arrays (namely NumPy or SymPy)\\n    support this format::\\n\\n        >>> B.tolist()\\n        [[mpf('1.0'), mpf('0.0')], [mpf('0.0'), mpf('0.0')]]\\n\\n\\n    Matrix operations\\n    -----------------\\n\\n    You can add and subtract matrices of compatible dimensions::\\n\\n        >>> A = matrix([[1, 2], [3, 4]])\\n        >>> B = matrix([[-2, 4], [5, 9]])\\n        >>> A + B\\n        matrix(\\n        [['-1.0', '6.0'],\\n         ['8.0', '13.0']])\\n        >>> A - B\\n        matrix(\\n        [['3.0', '-2.0'],\\n         ['-2.0', '-5.0']])\\n        >>> A + ones(3) # doctest:+ELLIPSIS\\n        Traceback (most recent call last):\\n          ...\\n        ValueError: incompatible dimensions for addition\\n\\n    It is possible to multiply or add matrices and scalars. In the latter case the\\n    operation will be done element-wise::\\n\\n        >>> A * 2\\n        matrix(\\n        [['2.0', '4.0'],\\n         ['6.0', '8.0']])\\n        >>> A / 4\\n        matrix(\\n        [['0.25', '0.5'],\\n         ['0.75', '1.0']])\\n        >>> A - 1\\n        matrix(\\n        [['0.0', '1.0'],\\n         ['2.0', '3.0']])\\n\\n    Of course you can perform matrix multiplication, if the dimensions are\\n    compatible, using ``@`` (for Python >= 3.5) or ``*``. For clarity, ``@`` is\\n    recommended (`PEP 465 <https://www.python.org/dev/peps/pep-0465/>`), because\\n    the meaning of ``*`` is different in many other Python libraries such as NumPy.\\n\\n        >>> A @ B # doctest:+SKIP\\n        matrix(\\n        [['8.0', '22.0'],\\n         ['14.0', '48.0']])\\n        >>> A * B # same as A @ B\\n        matrix(\\n        [['8.0', '22.0'],\\n         ['14.0', '48.0']])\\n        >>> matrix([[1, 2, 3]]) * matrix([[-6], [7], [-2]])\\n        matrix(\\n        [['2.0']])\\n\\n    ..\\n        COMMENT: TODO: the above \\\"doctest:+SKIP\\\" may be removed as soon as we\\n        have dropped support for Python 3.5 and below.\\n\\n    You can raise powers of square matrices::\\n\\n        >>> A**2\\n        matrix(\\n        [['7.0', '10.0'],\\n         ['15.0', '22.0']])\\n\\n    Negative powers will calculate the inverse::\\n\\n        >>> A**-1\\n        matrix(\\n        [['-2.0', '1.0'],\\n         ['1.5', '-0.5']])\\n        >>> A * A**-1\\n        matrix(\\n        [['1.0', '1.0842021724855e-19'],\\n         ['-2.16840434497101e-19', '1.0']])\\n\\n\\n\\n    Matrix transposition is straightforward::\\n\\n        >>> A = ones(2, 3)\\n        >>> A\\n        matrix(\\n        [['1.0', '1.0', '1.0'],\\n         ['1.0', '1.0', '1.0']])\\n        >>> A.T\\n        matrix(\\n        [['1.0', '1.0'],\\n         ['1.0', '1.0'],\\n         ['1.0', '1.0']])\\n\\n    Norms\\n    .....\\n\\n    Sometimes you need to know how \\\"large\\\" a matrix or vector is. Due to their\\n    multidimensional nature it's not possible to compare them, but there are\\n    several functions to map a matrix or a vector to a positive real number, the\\n    so called norms.\\n\\n    For vectors the p-norm is intended, usually the 1-, the 2- and the oo-norm are\\n    used.\\n\\n        >>> x = matrix([-10, 2, 100])\\n        >>> norm(x, 1)\\n        mpf('112.0')\\n        >>> norm(x, 2)\\n        mpf('100.5186549850325')\\n        >>> norm(x, inf)\\n        mpf('100.0')\\n\\n    Please note that the 2-norm is the most used one, though it is more expensive\\n    to calculate than the 1- or oo-norm.\\n\\n    It is possible to generalize some vector norms to matrix norm::\\n\\n        >>> A = matrix([[1, -1000], [100, 50]])\\n        >>> mnorm(A, 1)\\n        mpf('1050.0')\\n        >>> mnorm(A, inf)\\n        mpf('1001.0')\\n        >>> mnorm(A, 'F')\\n        mpf('1006.2310867787777')\\n\\n    The last norm (the \\\"Frobenius-norm\\\") is an approximation for the 2-norm, which\\n    is hard to calculate and not available. The Frobenius-norm lacks some\\n    mathematical properties you might expect from a norm.\\n    \\\"\\\"\\\"\\n\\n    def __init__(self, *args, **kwargs):\\n        self.__data = {}\\n        # LU decompostion cache, this is useful when solving the same system\\n        # multiple times, when calculating the inverse and when calculating the\\n        # determinant\\n        self._LU = None\\n        if \\\"force_type\\\" in kwargs:\\n            warnings.warn(\\\"The force_type argument was removed, it did not work\\\"\\n                \\\" properly anyway. If you want to force floating-point or\\\"\\n                \\\" interval computations, use the respective methods from `fp`\\\"\\n                \\\" or `mp` instead, e.g., `fp.matrix()` or `iv.matrix()`.\\\"\\n                \\\" If you want to truncate values to integer, use .apply(int) instead.\\\")\\n        if isinstance(args[0], (list, tuple)):\\n            if isinstance(args[0][0], (list, tuple)):\\n                # interpret nested list as matrix\\n                A = args[0]\\n                self.__rows = len(A)\\n                self.__cols = len(A[0])\\n                for i, row in enumerate(A):\\n                    for j, a in enumerate(row):\\n                        # note: this will call __setitem__ which will call self.ctx.convert() to convert the datatype.\\n                        self[i, j] = a\\n            else:\\n                # interpret list as row vector\\n                v = args[0]\\n                self.__rows = len(v)\\n                self.__cols = 1\\n                for i, e in enumerate(v):\\n                    self[i, 0] = e\\n        elif isinstance(args[0], int):\\n            # create empty matrix of given dimensions\\n            if len(args) == 1:\\n                self.__rows = self.__cols = args[0]\\n            else:\\n                if not isinstance(args[1], int):\\n                    raise TypeError(\\\"expected int\\\")\\n                self.__rows = args[0]\\n                self.__cols = args[1]\\n        elif isinstance(args[0], _matrix):\\n            A = args[0]\\n            self.__rows = A._matrix__rows\\n            self.__cols = A._matrix__cols\\n            for i in xrange(A.__rows):\\n                for j in xrange(A.__cols):\\n                    self[i, j] = A[i, j]\\n        elif hasattr(args[0], 'tolist'):\\n            A = self.ctx.matrix(args[0].tolist())\\n            self.__data = A._matrix__data\\n            self.__rows = A._matrix__rows\\n            self.__cols = A._matrix__cols\\n        else:\\n            raise TypeError('could not interpret given arguments')\\n\\n    def apply(self, f):\\n        \\\"\\\"\\\"\\n        Return a copy of self with the function `f` applied elementwise.\\n        \\\"\\\"\\\"\\n        new = self.ctx.matrix(self.__rows, self.__cols)\\n        for i in xrange(self.__rows):\\n            for j in xrange(self.__cols):\\n                new[i,j] = f(self[i,j])\\n        return new\\n\\n    def __nstr__(self, n=None, **kwargs):\\n        # Build table of string representations of the elements\\n        res = []\\n        # Track per-column max lengths for pretty alignment\\n        maxlen = [0] * self.cols\\n        for i in range(self.rows):\\n            res.append([])\\n            for j in range(self.cols):\\n                if n:\\n                    string = self.ctx.nstr(self[i,j], n, **kwargs)\\n                else:\\n                    string = str(self[i,j])\\n                res[-1].append(string)\\n                maxlen[j] = max(len(string), maxlen[j])\\n        # Patch strings together\\n        for i, row in enumerate(res):\\n            for j, elem in enumerate(row):\\n                # Pad each element up to maxlen so the columns line up\\n                row[j] = elem.rjust(maxlen[j])\\n            res[i] = \\\"[\\\" + colsep.join(row) + \\\"]\\\"\\n        return rowsep.join(res)\\n\\n    def __str__(self):\\n        return self.__nstr__()\\n\\n    def _toliststr(self, avoid_type=False):\\n        \\\"\\\"\\\"\\n        Create a list string from a matrix.\\n\\n        If avoid_type: avoid multiple 'mpf's.\\n        \\\"\\\"\\\"\\n        # XXX: should be something like self.ctx._types\\n        typ = self.ctx.mpf\\n        s = '['\\n        for i in xrange(self.__rows):\\n            s += '['\\n            for j in xrange(self.__cols):\\n                if not avoid_type or not isinstance(self[i,j], typ):\\n                    a = repr(self[i,j])\\n                else:\\n                    a = \\\"'\\\" + str(self[i,j]) + \\\"'\\\"\\n                s += a + ', '\\n            s = s[:-2]\\n            s += '],\\\\n '\\n        s = s[:-3]\\n        s += ']'\\n        return s\\n\\n    def tolist(self):\\n        \\\"\\\"\\\"\\n        Convert the matrix to a nested list.\\n        \\\"\\\"\\\"\\n        return [[self[i,j] for j in range(self.__cols)] for i in range(self.__rows)]\\n\\n    def __repr__(self):\\n        if self.ctx.pretty:\\n            return self.__str__()\\n        s = 'matrix(\\\\n'\\n        s += self._toliststr(avoid_type=True) + ')'\\n        return s\\n\\n    def __get_element(self, key):\\n        '''\\n        Fast extraction of the i,j element from the matrix\\n            This function is for private use only because is unsafe:\\n                1. Does not check on the value of key it expects key to be a integer tuple (i,j)\\n                2. Does not check bounds\\n        '''\\n        if key in self.__data:\\n            return self.__data[key]\\n        else:\\n            return self.ctx.zero\\n\\n    def __set_element(self, key, value):\\n        '''\\n        Fast assignment of the i,j element in the matrix\\n            This function is unsafe:\\n                1. Does not check on the value of key it expects key to be a integer tuple (i,j)\\n                2. Does not check bounds\\n                3. Does not check the value type\\n                4. Does not reset the LU cache\\n        '''\\n        if value: # only store non-zeros\\n            self.__data[key] = value\\n        elif key in self.__data:\\n            del self.__data[key]\\n\\n\\n    def __getitem__(self, key):\\n        '''\\n            Getitem function for mp matrix class with slice index enabled\\n            it allows the following assingments\\n            scalar to a slice of the matrix\\n         B = A[:,2:6]\\n        '''\\n        # Convert vector to matrix indexing\\n        if isinstance(key, int) or isinstance(key,slice):\\n            # only sufficent for vectors\\n            if self.__rows == 1:\\n                key = (0, key)\\n            elif self.__cols == 1:\\n                key = (key, 0)\\n            else:\\n                raise IndexError('insufficient indices for matrix')\\n\\n        if isinstance(key[0],slice) or isinstance(key[1],slice):\\n\\n            #Rows\\n            if isinstance(key[0],slice):\\n                #Check bounds\\n                if (key[0].start is None or key[0].start >= 0) and \\\\\\n                    (key[0].stop is None or key[0].stop <= self.__rows+1):\\n                    # Generate indices\\n                    rows = xrange(*key[0].indices(self.__rows))\\n                else:\\n                    raise IndexError('Row index out of bounds')\\n            else:\\n                # Single row\\n                rows = [key[0]]\\n\\n            # Columns\\n            if isinstance(key[1],slice):\\n                # Check bounds\\n                if (key[1].start is None or key[1].start >= 0) and \\\\\\n                    (key[1].stop is None or key[1].stop <= self.__cols+1):\\n                    # Generate indices\\n                    columns = xrange(*key[1].indices(self.__cols))\\n                else:\\n                    raise IndexError('Column index out of bounds')\\n\\n            else:\\n                # Single column\\n                columns = [key[1]]\\n\\n            # Create matrix slice\\n            m = self.ctx.matrix(len(rows),len(columns))\\n\\n            # Assign elements to the output matrix\\n            for i,x in enumerate(rows):\\n                for j,y in enumerate(columns):\\n                    m.__set_element((i,j),self.__get_element((x,y)))\\n\\n            return m\\n\\n        else:\\n            # single element extraction\\n            if key[0] >= self.__rows or key[1] >= self.__cols:\\n                raise IndexError('matrix index out of range')\\n            if key in self.__data:\\n                return self.__data[key]\\n            else:\\n                return self.ctx.zero\\n\\n    def __setitem__(self, key, value):\\n        # setitem function for mp matrix class with slice index enabled\\n        # it allows the following assingments\\n        #  scalar to a slice of the matrix\\n        # A[:,2:6] = 2.5\\n        #  submatrix to matrix (the value matrix should be the same size as the slice size)\\n        # A[3,:] = B   where A is n x m  and B is n x 1\\n        # Convert vector to matrix indexing\\n        if isinstance(key, int) or isinstance(key,slice):\\n            # only sufficent for vectors\\n            if self.__rows == 1:\\n                key = (0, key)\\n            elif self.__cols == 1:\\n                key = (key, 0)\\n            else:\\n                raise IndexError('insufficient indices for matrix')\\n        # Slice indexing\\n        if isinstance(key[0],slice) or isinstance(key[1],slice):\\n            # Rows\\n            if isinstance(key[0],slice):\\n                # Check bounds\\n                if (key[0].start is None or key[0].start >= 0) and \\\\\\n                    (key[0].stop is None or key[0].stop <= self.__rows+1):\\n                    # generate row indices\\n                    rows = xrange(*key[0].indices(self.__rows))\\n                else:\\n                    raise IndexError('Row index out of bounds')\\n            else:\\n                # Single row\\n                rows = [key[0]]\\n            # Columns\\n            if isinstance(key[1],slice):\\n                # Check bounds\\n                if (key[1].start is None or key[1].start >= 0) and \\\\\\n                    (key[1].stop is None or key[1].stop <= self.__cols+1):\\n                    # Generate column indices\\n                    columns = xrange(*key[1].indices(self.__cols))\\n                else:\\n                    raise IndexError('Column index out of bounds')\\n            else:\\n                # Single column\\n                columns = [key[1]]\\n            # Assign slice with a scalar\\n            if isinstance(value,self.ctx.matrix):\\n                # Assign elements to matrix if input and output dimensions match\\n                if len(rows) == value.rows and len(columns) == value.cols:\\n                    for i,x in enumerate(rows):\\n                        for j,y in enumerate(columns):\\n                            self.__set_element((x,y), value.__get_element((i,j)))\\n                else:\\n                    raise ValueError('Dimensions do not match')\\n            else:\\n                # Assign slice with scalars\\n                value = self.ctx.convert(value)\\n                for i in rows:\\n                    for j in columns:\\n                        self.__set_element((i,j), value)\\n        else:\\n            # Single element assingment\\n            # Check bounds\\n            if key[0] >= self.__rows or key[1] >= self.__cols:\\n                raise IndexError('matrix index out of range')\\n            # Convert and store value\\n            value = self.ctx.convert(value)\\n            if value: # only store non-zeros\\n                self.__data[key] = value\\n            elif key in self.__data:\\n                del self.__data[key]\\n\\n        if self._LU:\\n            self._LU = None\\n        return\\n\\n    def __iter__(self):\\n        for i in xrange(self.__rows):\\n            for j in xrange(self.__cols):\\n                yield self[i,j]\\n\\n    def __mul__(self, other):\\n        if isinstance(other, self.ctx.matrix):\\n            # dot multiplication\\n            if self.__cols != other.__rows:\\n                raise ValueError('dimensions not compatible for multiplication')\\n            new = self.ctx.matrix(self.__rows, other.__cols)\\n            self_zero = self.ctx.zero\\n            self_get = self.__data.get\\n            other_zero = other.ctx.zero\\n            other_get = other.__data.get\\n            for i in xrange(self.__rows):\\n                for j in xrange(other.__cols):\\n                    new[i, j] = self.ctx.fdot((self_get((i,k), self_zero), other_get((k,j), other_zero))\\n                                     for k in xrange(other.__rows))\\n            return new\\n        else:\\n            # try scalar multiplication\\n            new = self.ctx.matrix(self.__rows, self.__cols)\\n            for i in xrange(self.__rows):\\n                for j in xrange(self.__cols):\\n                    new[i, j] = other * self[i, j]\\n            return new\\n\\n    def __matmul__(self, other):\\n        return self.__mul__(other)\\n\\n    def __rmul__(self, other):\\n        # assume other is scalar and thus commutative\\n        if isinstance(other, self.ctx.matrix):\\n            raise TypeError(\\\"other should not be type of ctx.matrix\\\")\\n        return self.__mul__(other)\\n\\n    def __pow__(self, other):\\n        # avoid cyclic import problems\\n        #from linalg import inverse\\n        if not isinstance(other, int):\\n            raise ValueError('only integer exponents are supported')\\n        if not self.__rows == self.__cols:\\n            raise ValueError('only powers of square matrices are defined')\\n        n = other\\n        if n == 0:\\n            return self.ctx.eye(self.__rows)\\n        if n < 0:\\n            n = -n\\n            neg = True\\n        else:\\n            neg = False\\n        i = n\\n        y = 1\\n        z = self.copy()\\n        while i != 0:\\n            if i % 2 == 1:\\n                y = y * z\\n            z = z*z\\n            i = i // 2\\n        if neg:\\n            y = self.ctx.inverse(y)\\n        return y\\n\\n    def __div__(self, other):\\n        # assume other is scalar and do element-wise divison\\n        assert not isinstance(other, self.ctx.matrix)\\n        new = self.ctx.matrix(self.__rows, self.__cols)\\n        for i in xrange(self.__rows):\\n            for j in xrange(self.__cols):\\n                new[i,j] = self[i,j] / other\\n        return new\\n\\n    __truediv__ = __div__\\n\\n    def __add__(self, other):\\n        if isinstance(other, self.ctx.matrix):\\n            if not (self.__rows == other.__rows and self.__cols == other.__cols):\\n                raise ValueError('incompatible dimensions for addition')\\n            new = self.ctx.matrix(self.__rows, self.__cols)\\n            for i in xrange(self.__rows):\\n                for j in xrange(self.__cols):\\n                    new[i,j] = self[i,j] + other[i,j]\\n            return new\\n        else:\\n            # assume other is scalar and add element-wise\\n            new = self.ctx.matrix(self.__rows, self.__cols)\\n            for i in xrange(self.__rows):\\n                for j in xrange(self.__cols):\\n                    new[i,j] += self[i,j] + other\\n            return new\\n\\n    def __radd__(self, other):\\n        return self.__add__(other)\\n\\n    def __sub__(self, other):\\n        if isinstance(other, self.ctx.matrix) and not (self.__rows == other.__rows\\n                                              and self.__cols == other.__cols):\\n            raise ValueError('incompatible dimensions for subtraction')\\n        return self.__add__(other * (-1))\\n\\n    def __pos__(self):\\n        \\\"\\\"\\\"\\n        +M returns a copy of M, rounded to current working precision.\\n        \\\"\\\"\\\"\\n        return (+1) * self\\n\\n    def __neg__(self):\\n        return (-1) * self\\n\\n    def __rsub__(self, other):\\n        return -self + other\\n\\n    def __eq__(self, other):\\n        return self.__rows == other.__rows and self.__cols == other.__cols \\\\\\n               and self.__data == other.__data\\n\\n    def __len__(self):\\n        if self.rows == 1:\\n            return self.cols\\n        elif self.cols == 1:\\n            return self.rows\\n        else:\\n            return self.rows # do it like numpy\\n\\n    def __getrows(self):\\n        return self.__rows\\n\\n    def __setrows(self, value):\\n        for key in self.__data.copy():\\n            if key[0] >= value:\\n                del self.__data[key]\\n        self.__rows = value\\n\\n    rows = property(__getrows, __setrows, doc='number of rows')\\n\\n    def __getcols(self):\\n        return self.__cols\\n\\n    def __setcols(self, value):\\n        for key in self.__data.copy():\\n            if key[1] >= value:\\n                del self.__data[key]\\n        self.__cols = value\\n\\n    cols = property(__getcols, __setcols, doc='number of columns')\\n\\n    def transpose(self):\\n        new = self.ctx.matrix(self.__cols, self.__rows)\\n        for i in xrange(self.__rows):\\n            for j in xrange(self.__cols):\\n                new[j,i] = self[i,j]\\n        return new\\n\\n    T = property(transpose)\\n\\n    def conjugate(self):\\n        return self.apply(self.ctx.conj)\\n\\n    def transpose_conj(self):\\n        return self.conjugate().transpose()\\n\\n    H = property(transpose_conj)\\n\\n    def copy(self):\\n        new = self.ctx.matrix(self.__rows, self.__cols)\\n        new.__data = self.__data.copy()\\n        return new\\n\\n    __copy__ = copy\\n\\n    def column(self, n):\\n        m = self.ctx.matrix(self.rows, 1)\\n        for i in range(self.rows):\\n            m[i] = self[i,n]\\n        return m\\n\\nclass MatrixMethods(object):\\n\\n    def __init__(ctx):\\n        # XXX: subclass\\n        ctx.matrix = type('matrix', (_matrix,), {})\\n        ctx.matrix.ctx = ctx\\n        ctx.matrix.convert = ctx.convert\\n\\n    def eye(ctx, n, **kwargs):\\n        \\\"\\\"\\\"\\n        Create square identity matrix n x n.\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(n, **kwargs)\\n        for i in xrange(n):\\n            A[i,i] = 1\\n        return A\\n\\n    def diag(ctx, diagonal, **kwargs):\\n        \\\"\\\"\\\"\\n        Create square diagonal matrix using given list.\\n\\n        Example:\\n        >>> from mpmath import diag, mp\\n        >>> mp.pretty = False\\n        >>> diag([1, 2, 3])\\n        matrix(\\n        [['1.0', '0.0', '0.0'],\\n         ['0.0', '2.0', '0.0'],\\n         ['0.0', '0.0', '3.0']])\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(len(diagonal), **kwargs)\\n        for i in xrange(len(diagonal)):\\n            A[i,i] = diagonal[i]\\n        return A\\n\\n    def zeros(ctx, *args, **kwargs):\\n        \\\"\\\"\\\"\\n        Create matrix m x n filled with zeros.\\n        One given dimension will create square matrix n x n.\\n\\n        Example:\\n        >>> from mpmath import zeros, mp\\n        >>> mp.pretty = False\\n        >>> zeros(2)\\n        matrix(\\n        [['0.0', '0.0'],\\n         ['0.0', '0.0']])\\n        \\\"\\\"\\\"\\n        if len(args) == 1:\\n            m = n = args[0]\\n        elif len(args) == 2:\\n            m = args[0]\\n            n = args[1]\\n        else:\\n            raise TypeError('zeros expected at most 2 arguments, got %i' % len(args))\\n        A = ctx.matrix(m, n, **kwargs)\\n        for i in xrange(m):\\n            for j in xrange(n):\\n                A[i,j] = 0\\n        return A\\n\\n    def ones(ctx, *args, **kwargs):\\n        \\\"\\\"\\\"\\n        Create matrix m x n filled with ones.\\n        One given dimension will create square matrix n x n.\\n\\n        Example:\\n        >>> from mpmath import ones, mp\\n        >>> mp.pretty = False\\n        >>> ones(2)\\n        matrix(\\n        [['1.0', '1.0'],\\n         ['1.0', '1.0']])\\n        \\\"\\\"\\\"\\n        if len(args) == 1:\\n            m = n = args[0]\\n        elif len(args) == 2:\\n            m = args[0]\\n            n = args[1]\\n        else:\\n            raise TypeError('ones expected at most 2 arguments, got %i' % len(args))\\n        A = ctx.matrix(m, n, **kwargs)\\n        for i in xrange(m):\\n            for j in xrange(n):\\n                A[i,j] = 1\\n        return A\\n\\n    def hilbert(ctx, m, n=None):\\n        \\\"\\\"\\\"\\n        Create (pseudo) hilbert matrix m x n.\\n        One given dimension will create hilbert matrix n x n.\\n\\n        The matrix is very ill-conditioned and symmetric, positive definite if\\n        square.\\n        \\\"\\\"\\\"\\n        if n is None:\\n            n = m\\n        A = ctx.matrix(m, n)\\n        for i in xrange(m):\\n            for j in xrange(n):\\n                A[i,j] = ctx.one / (i + j + 1)\\n        return A\\n\\n    def randmatrix(ctx, m, n=None, min=0, max=1, **kwargs):\\n        \\\"\\\"\\\"\\n        Create a random m x n matrix.\\n\\n        All values are >= min and <max.\\n        n defaults to m.\\n\\n        Example:\\n        >>> from mpmath import randmatrix\\n        >>> randmatrix(2) # doctest:+SKIP\\n        matrix(\\n        [['0.53491598236191806', '0.57195669543302752'],\\n         ['0.85589992269513615', '0.82444367501382143']])\\n        \\\"\\\"\\\"\\n        if not n:\\n            n = m\\n        A = ctx.matrix(m, n, **kwargs)\\n        for i in xrange(m):\\n            for j in xrange(n):\\n                A[i,j] = ctx.rand() * (max - min) + min\\n        return A\\n\\n    def swap_row(ctx, A, i, j):\\n        \\\"\\\"\\\"\\n        Swap row i with row j.\\n        \\\"\\\"\\\"\\n        if i == j:\\n            return\\n        if isinstance(A, ctx.matrix):\\n            for k in xrange(A.cols):\\n                A[i,k], A[j,k] = A[j,k], A[i,k]\\n        elif isinstance(A, list):\\n            A[i], A[j] = A[j], A[i]\\n        else:\\n            raise TypeError('could not interpret type')\\n\\n    def extend(ctx, A, b):\\n        \\\"\\\"\\\"\\n        Extend matrix A with column b and return result.\\n        \\\"\\\"\\\"\\n        if not isinstance(A, ctx.matrix):\\n            raise TypeError(\\\"A should be a type of ctx.matrix\\\")\\n        if A.rows != len(b):\\n            raise ValueError(\\\"Value should be equal to len(b)\\\")\\n        A = A.copy()\\n        A.cols += 1\\n        for i in xrange(A.rows):\\n            A[i, A.cols-1] = b[i]\\n        return A\\n\\n    def norm(ctx, x, p=2):\\n        r\\\"\\\"\\\"\\n        Gives the entrywise `p`-norm of an iterable *x*, i.e. the vector norm\\n        `\\\\left(\\\\sum_k |x_k|^p\\\\right)^{1/p}`, for any given `1 \\\\le p \\\\le \\\\infty`.\\n\\n        Special cases:\\n\\n        If *x* is not iterable, this just returns ``absmax(x)``.\\n\\n        ``p=1`` gives the sum of absolute values.\\n\\n        ``p=2`` is the standard Euclidean vector norm.\\n\\n        ``p=inf`` gives the magnitude of the largest element.\\n\\n        For *x* a matrix, ``p=2`` is the Frobenius norm.\\n        For operator matrix norms, use :func:`~mpmath.mnorm` instead.\\n\\n        You can use the string 'inf' as well as float('inf') or mpf('inf')\\n        to specify the infinity norm.\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> x = matrix([-10, 2, 100])\\n            >>> norm(x, 1)\\n            mpf('112.0')\\n            >>> norm(x, 2)\\n            mpf('100.5186549850325')\\n            >>> norm(x, inf)\\n            mpf('100.0')\\n\\n        \\\"\\\"\\\"\\n        try:\\n            iter(x)\\n        except TypeError:\\n            return ctx.absmax(x)\\n        if type(p) is not int:\\n            p = ctx.convert(p)\\n        if p == ctx.inf:\\n            return max(ctx.absmax(i) for i in x)\\n        elif p == 1:\\n            return ctx.fsum(x, absolute=1)\\n        elif p == 2:\\n            return ctx.sqrt(ctx.fsum(x, absolute=1, squared=1))\\n        elif p > 1:\\n            return ctx.nthroot(ctx.fsum(abs(i)**p for i in x), p)\\n        else:\\n            raise ValueError('p has to be >= 1')\\n\\n    def mnorm(ctx, A, p=1):\\n        r\\\"\\\"\\\"\\n        Gives the matrix (operator) `p`-norm of A. Currently ``p=1`` and ``p=inf``\\n        are supported:\\n\\n        ``p=1`` gives the 1-norm (maximal column sum)\\n\\n        ``p=inf`` gives the `\\\\infty`-norm (maximal row sum).\\n        You can use the string 'inf' as well as float('inf') or mpf('inf')\\n\\n        ``p=2`` (not implemented) for a square matrix is the usual spectral\\n        matrix norm, i.e. the largest singular value.\\n\\n        ``p='f'`` (or 'F', 'fro', 'Frobenius, 'frobenius') gives the\\n        Frobenius norm, which is the elementwise 2-norm. The Frobenius norm is an\\n        approximation of the spectral norm and satisfies\\n\\n        .. math ::\\n\\n            \\\\frac{1}{\\\\sqrt{\\\\mathrm{rank}(A)}} \\\\|A\\\\|_F \\\\le \\\\|A\\\\|_2 \\\\le \\\\|A\\\\|_F\\n\\n        The Frobenius norm lacks some mathematical properties that might\\n        be expected of a norm.\\n\\n        For general elementwise `p`-norms, use :func:`~mpmath.norm` instead.\\n\\n        **Examples**\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = False\\n            >>> A = matrix([[1, -1000], [100, 50]])\\n            >>> mnorm(A, 1)\\n            mpf('1050.0')\\n            >>> mnorm(A, inf)\\n            mpf('1001.0')\\n            >>> mnorm(A, 'F')\\n            mpf('1006.2310867787777')\\n\\n        \\\"\\\"\\\"\\n        A = ctx.matrix(A)\\n        if type(p) is not int:\\n            if type(p) is str and 'frobenius'.startswith(p.lower()):\\n                return ctx.norm(A, 2)\\n            p = ctx.convert(p)\\n        m, n = A.rows, A.cols\\n        if p == 1:\\n            return max(ctx.fsum((A[i,j] for i in xrange(m)), absolute=1) for j in xrange(n))\\n        elif p == ctx.inf:\\n            return max(ctx.fsum((A[i,j] for j in xrange(n)), absolute=1) for i in xrange(m))\\n        else:\\n            raise NotImplementedError(\\\"matrix p-norm for arbitrary p\\\")\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\nfrom . import eigen           # to set methods\\nfrom . import eigen_symmetric # to set methods\\n\\n\\nimport pytest\\nfrom mpmath import *\\n\\ndef ae(a, b):\\n    return abs(a-b) < 10**(-mp.dps+5)\\n\\ndef test_basic_integrals():\\n    for prec in [15, 30, 100]:\\n        mp.dps = prec\\n        assert ae(quadts(lambda x: x**3 - 3*x**2, [-2, 4]), -12)\\n        assert ae(quadgl(lambda x: x**3 - 3*x**2, [-2, 4]), -12)\\n        assert ae(quadts(sin, [0, pi]), 2)\\n        assert ae(quadts(sin, [0, 2*pi]), 0)\\n        assert ae(quadts(exp, [-inf, -1]), 1/e)\\n        assert ae(quadts(lambda x: exp(-x), [0, inf]), 1)\\n        assert ae(quadts(lambda x: exp(-x*x), [-inf, inf]), sqrt(pi))\\n        assert ae(quadts(lambda x: 1/(1+x*x), [-1, 1]), pi/2)\\n        assert ae(quadts(lambda x: 1/(1+x*x), [-inf, inf]), pi)\\n        assert ae(quadts(lambda x: 2*sqrt(1-x*x), [-1, 1]), pi)\\n    mp.dps = 15\\n\\ndef test_multiple_intervals():\\n    y,err = quad(lambda x: sign(x), [-0.5, 0.9, 1], maxdegree=2, error=True)\\n    assert abs(y-0.5) < 2*err\\n\\ndef test_quad_symmetry():\\n    assert quadts(sin, [-1, 1]) == 0\\n    assert quadgl(sin, [-1, 1]) == 0\\n\\ndef test_quad_infinite_mirror():\\n    # Check mirrored infinite interval\\n    assert ae(quad(lambda x: exp(-x*x), [inf,-inf]), -sqrt(pi))\\n    assert ae(quad(lambda x: exp(x), [0,-inf]), -1)\\n\\ndef test_quadgl_linear():\\n    assert quadgl(lambda x: x, [0, 1], maxdegree=1).ae(0.5)\\n\\ndef test_complex_integration():\\n    assert quadts(lambda x: x, [0, 1+j]).ae(j)\\n\\ndef test_quadosc():\\n    mp.dps = 15\\n    assert quadosc(lambda x: sin(x)/x, [0, inf], period=2*pi).ae(pi/2)\\n\\n# Double integrals\\ndef test_double_trivial():\\n    assert ae(quadts(lambda x, y: x, [0, 1], [0, 1]), 0.5)\\n    assert ae(quadts(lambda x, y: x, [-1, 1], [-1, 1]), 0.0)\\n\\ndef test_double_1():\\n    assert ae(quadts(lambda x, y: cos(x+y/2), [-pi/2, pi/2], [0, pi]), 4)\\n\\ndef test_double_2():\\n    assert ae(quadts(lambda x, y: (x-1)/((1-x*y)*log(x*y)), [0, 1], [0, 1]), euler)\\n\\ndef test_double_3():\\n    assert ae(quadts(lambda x, y: 1/sqrt(1+x*x+y*y), [-1, 1], [-1, 1]), 4*log(2+sqrt(3))-2*pi/3)\\n\\ndef test_double_4():\\n    assert ae(quadts(lambda x, y: 1/(1-x*x * y*y), [0, 1], [0, 1]), pi**2 / 8)\\n\\ndef test_double_5():\\n    assert ae(quadts(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]), pi**2 / 6)\\n\\ndef test_double_6():\\n    assert ae(quadts(lambda x, y: exp(-(x+y)), [0, inf], [0, inf]), 1)\\n\\ndef test_double_7():\\n    assert ae(quadts(lambda x, y: exp(-x*x-y*y), [-inf, inf], [-inf, inf]), pi)\\n\\n\\n# Test integrals from \\\"Experimentation in Mathematics\\\" by Borwein,\\n# Bailey & Girgensohn\\ndef test_expmath_integrals():\\n    for prec in [15, 30, 50]:\\n        mp.dps = prec\\n        assert ae(quadts(lambda x: x/sinh(x), [0, inf]),                    pi**2 / 4)\\n        assert ae(quadts(lambda x: log(x)**2 / (1+x**2), [0, inf]),         pi**3 / 8)\\n        assert ae(quadts(lambda x: (1+x**2)/(1+x**4), [0, inf]),            pi/sqrt(2))\\n        assert ae(quadts(lambda x: log(x)/cosh(x)**2, [0, inf]),            log(pi)-2*log(2)-euler)\\n        assert ae(quadts(lambda x: log(1+x**3)/(1-x+x**2), [0, inf]),       2*pi*log(3)/sqrt(3))\\n        assert ae(quadts(lambda x: log(x)**2 / (x**2+x+1), [0, 1]),         8*pi**3 / (81*sqrt(3)))\\n        assert ae(quadts(lambda x: log(cos(x))**2, [0, pi/2]),              pi/2 * (log(2)**2+pi**2/12))\\n        assert ae(quadts(lambda x: x**2 / sin(x)**2, [0, pi/2]),            pi*log(2))\\n        assert ae(quadts(lambda x: x**2/sqrt(exp(x)-1), [0, inf]),          4*pi*(log(2)**2 + pi**2/12))\\n        assert ae(quadts(lambda x: x*exp(-x)*sqrt(1-exp(-2*x)), [0, inf]),  pi*(1+2*log(2))/8)\\n    mp.dps = 15\\n\\n# Do not reach full accuracy\\n@pytest.mark.xfail\\ndef test_expmath_fail():\\n    assert ae(quadts(lambda x: sqrt(tan(x)), [0, pi/2]),          pi*sqrt(2)/2)\\n    assert ae(quadts(lambda x: atan(x)/(x*sqrt(1-x**2)), [0, 1]), pi*log(1+sqrt(2))/2)\\n    assert ae(quadts(lambda x: log(1+x**2)/x**2, [0, 1]),         pi/2-log(2))\\n    assert ae(quadts(lambda x: x**2/((1+x**4)*sqrt(1-x**4)), [0, 1]),     pi/8)\\n\\n\\nfrom mpmath import *\\nfrom mpmath.libmp import *\\n\\ndef test_trig_misc_hard():\\n    mp.prec = 53\\n    # Worst-case input for an IEEE double, from a paper by Kahan\\n    x = ldexp(6381956970095103,797)\\n    assert cos(x) == mpf('-4.6871659242546277e-19')\\n    assert sin(x) == 1\\n\\n    mp.prec = 150\\n    a = mpf(10**50)\\n    mp.prec = 53\\n    assert sin(a).ae(-0.7896724934293100827)\\n    assert cos(a).ae(-0.6135286082336635622)\\n\\n    # Check relative accuracy close to x = zero\\n    assert sin(1e-100) == 1e-100  # when rounding to nearest\\n    assert sin(1e-6).ae(9.999999999998333e-007, rel_eps=2e-15, abs_eps=0)\\n    assert sin(1e-6j).ae(1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0)\\n    assert sin(-1e-6j).ae(-1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0)\\n    assert cos(1e-100) == 1\\n    assert cos(1e-6).ae(0.9999999999995)\\n    assert cos(-1e-6j).ae(1.0000000000005)\\n    assert tan(1e-100) == 1e-100\\n    assert tan(1e-6).ae(1.0000000000003335e-006, rel_eps=2e-15, abs_eps=0)\\n    assert tan(1e-6j).ae(9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0)\\n    assert tan(-1e-6j).ae(-9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0)\\n\\ndef test_trig_near_zero():\\n    mp.dps = 15\\n\\n    for r in [round_nearest, round_down, round_up, round_floor, round_ceiling]:\\n        assert sin(0, rounding=r) == 0\\n        assert cos(0, rounding=r) == 1\\n\\n    a = mpf('1e-100')\\n    b = mpf('-1e-100')\\n\\n    assert sin(a, rounding=round_nearest) == a\\n    assert sin(a, rounding=round_down) < a\\n    assert sin(a, rounding=round_floor) < a\\n    assert sin(a, rounding=round_up) >= a\\n    assert sin(a, rounding=round_ceiling) >= a\\n    assert sin(b, rounding=round_nearest) == b\\n    assert sin(b, rounding=round_down) > b\\n    assert sin(b, rounding=round_floor) <= b\\n    assert sin(b, rounding=round_up) <= b\\n    assert sin(b, rounding=round_ceiling) > b\\n\\n    assert cos(a, rounding=round_nearest) == 1\\n    assert cos(a, rounding=round_down) < 1\\n    assert cos(a, rounding=round_floor) < 1\\n    assert cos(a, rounding=round_up) == 1\\n    assert cos(a, rounding=round_ceiling) == 1\\n    assert cos(b, rounding=round_nearest) == 1\\n    assert cos(b, rounding=round_down) < 1\\n    assert cos(b, rounding=round_floor) < 1\\n    assert cos(b, rounding=round_up) == 1\\n    assert cos(b, rounding=round_ceiling) == 1\\n\\n\\ndef test_trig_near_n_pi():\\n\\n    mp.dps = 15\\n    a = [n*pi for n in [1, 2, 6, 11, 100, 1001, 10000, 100001]]\\n    mp.dps = 135\\n    a.append(10**100 * pi)\\n    mp.dps = 15\\n\\n    assert sin(a[0]) == mpf('1.2246467991473531772e-16')\\n    assert sin(a[1]) == mpf('-2.4492935982947063545e-16')\\n    assert sin(a[2]) == mpf('-7.3478807948841190634e-16')\\n    assert sin(a[3]) == mpf('4.8998251578625894243e-15')\\n    assert sin(a[4]) == mpf('1.9643867237284719452e-15')\\n    assert sin(a[5]) == mpf('-8.8632615209684813458e-15')\\n    assert sin(a[6]) == mpf('-4.8568235395684898392e-13')\\n    assert sin(a[7]) == mpf('3.9087342299491231029e-11')\\n    assert sin(a[8]) == mpf('-1.369235466754566993528e-36')\\n\\n    r = round_nearest\\n    assert cos(a[0], rounding=r) == -1\\n    assert cos(a[1], rounding=r) == 1\\n    assert cos(a[2], rounding=r) == 1\\n    assert cos(a[3], rounding=r) == -1\\n    assert cos(a[4], rounding=r) == 1\\n    assert cos(a[5], rounding=r) == -1\\n    assert cos(a[6], rounding=r) == 1\\n    assert cos(a[7], rounding=r) == -1\\n    assert cos(a[8], rounding=r) == 1\\n\\n    r = round_up\\n    assert cos(a[0], rounding=r) == -1\\n    assert cos(a[1], rounding=r) == 1\\n    assert cos(a[2], rounding=r) == 1\\n    assert cos(a[3], rounding=r) == -1\\n    assert cos(a[4], rounding=r) == 1\\n    assert cos(a[5], rounding=r) == -1\\n    assert cos(a[6], rounding=r) == 1\\n    assert cos(a[7], rounding=r) == -1\\n    assert cos(a[8], rounding=r) == 1\\n\\n    r = round_down\\n    assert cos(a[0], rounding=r) > -1\\n    assert cos(a[1], rounding=r) < 1\\n    assert cos(a[2], rounding=r) < 1\\n    assert cos(a[3], rounding=r) > -1\\n    assert cos(a[4], rounding=r) < 1\\n    assert cos(a[5], rounding=r) > -1\\n    assert cos(a[6], rounding=r) < 1\\n    assert cos(a[7], rounding=r) > -1\\n    assert cos(a[8], rounding=r) < 1\\n\\n    r = round_floor\\n    assert cos(a[0], rounding=r) == -1\\n    assert cos(a[1], rounding=r) < 1\\n    assert cos(a[2], rounding=r) < 1\\n    assert cos(a[3], rounding=r) == -1\\n    assert cos(a[4], rounding=r) < 1\\n    assert cos(a[5], rounding=r) == -1\\n    assert cos(a[6], rounding=r) < 1\\n    assert cos(a[7], rounding=r) == -1\\n    assert cos(a[8], rounding=r) < 1\\n\\n    r = round_ceiling\\n    assert cos(a[0], rounding=r) > -1\\n    assert cos(a[1], rounding=r) == 1\\n    assert cos(a[2], rounding=r) == 1\\n    assert cos(a[3], rounding=r) > -1\\n    assert cos(a[4], rounding=r) == 1\\n    assert cos(a[5], rounding=r) > -1\\n    assert cos(a[6], rounding=r) == 1\\n    assert cos(a[7], rounding=r) > -1\\n    assert cos(a[8], rounding=r) == 1\\n\\n    mp.dps = 15\\n\\n\\nfrom mpmath import *\\n\\ndef test_pslq():\\n    mp.dps = 15\\n    assert pslq([3*pi+4*e/7, pi, e, log(2)]) == [7, -21, -4, 0]\\n    assert pslq([4.9999999999999991, 1]) == [1, -5]\\n    assert pslq([2,1]) == [1, -2]\\n\\ndef test_identify():\\n    mp.dps = 20\\n    assert identify(zeta(4), ['log(2)', 'pi**4']) == '((1/90)*pi**4)'\\n    mp.dps = 15\\n    assert identify(exp(5)) == 'exp(5)'\\n    assert identify(exp(4)) == 'exp(4)'\\n    assert identify(log(5)) == 'log(5)'\\n    assert identify(exp(3*pi), ['pi']) == 'exp((3*pi))'\\n    assert identify(3, full=True) == ['3', '3', '1/(1/3)', 'sqrt(9)',\\n        '1/sqrt((1/9))', '(sqrt(12)/2)**2', '1/(sqrt(12)/6)**2']\\n    assert identify(pi+1, {'a':+pi}) == '(1 + 1*a)'\\n\\n\\nfrom mpmath.libmp import *\\nfrom mpmath import *\\nimport random\\nimport time\\nimport math\\nimport cmath\\n\\ndef mpc_ae(a, b, eps=eps):\\n    res = True\\n    res = res and a.real.ae(b.real, eps)\\n    res = res and a.imag.ae(b.imag, eps)\\n    return res\\n\\n#----------------------------------------------------------------------------\\n# Constants and functions\\n#\\n\\ntpi = \\\"3.1415926535897932384626433832795028841971693993751058209749445923078\\\\\\n1640628620899862803482534211706798\\\"\\nte = \\\"2.71828182845904523536028747135266249775724709369995957496696762772407\\\\\\n663035354759457138217852516642743\\\"\\ntdegree = \\\"0.017453292519943295769236907684886127134428718885417254560971914\\\\\\n4017100911460344944368224156963450948221\\\"\\nteuler = \\\"0.5772156649015328606065120900824024310421593359399235988057672348\\\\\\n84867726777664670936947063291746749516\\\"\\ntln2 = \\\"0.693147180559945309417232121458176568075500134360255254120680009493\\\\\\n393621969694715605863326996418687542\\\"\\ntln10 = \\\"2.30258509299404568401799145468436420760110148862877297603332790096\\\\\\n757260967735248023599720508959829834\\\"\\ntcatalan = \\\"0.91596559417721901505460351493238411077414937428167213426649811\\\\\\n9621763019776254769479356512926115106249\\\"\\ntkhinchin = \\\"2.6854520010653064453097148354817956938203822939944629530511523\\\\\\n4555721885953715200280114117493184769800\\\"\\ntglaisher = \\\"1.2824271291006226368753425688697917277676889273250011920637400\\\\\\n2174040630885882646112973649195820237439420646\\\"\\ntapery = \\\"1.2020569031595942853997381615114499907649862923404988817922715553\\\\\\n4183820578631309018645587360933525815\\\"\\ntphi = \\\"1.618033988749894848204586834365638117720309179805762862135448622705\\\\\\n26046281890244970720720418939113748475\\\"\\ntmertens = \\\"0.26149721284764278375542683860869585905156664826119920619206421\\\\\\n3924924510897368209714142631434246651052\\\"\\nttwinprime = \\\"0.660161815846869573927812110014555778432623360284733413319448\\\\\\n423335405642304495277143760031413839867912\\\"\\n\\ndef test_constants():\\n    for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:\\n        mp.dps = prec\\n        assert pi == mpf(tpi)\\n        assert e == mpf(te)\\n        assert degree == mpf(tdegree)\\n        assert euler == mpf(teuler)\\n        assert ln2 == mpf(tln2)\\n        assert ln10 == mpf(tln10)\\n        assert catalan == mpf(tcatalan)\\n        assert khinchin == mpf(tkhinchin)\\n        assert glaisher == mpf(tglaisher)\\n        assert phi == mpf(tphi)\\n        if prec < 50:\\n            assert mertens == mpf(tmertens)\\n            assert twinprime == mpf(ttwinprime)\\n    mp.dps = 15\\n    assert pi >= -1\\n    assert pi > 2\\n    assert pi > 3\\n    assert pi < 4\\n\\ndef test_exact_sqrts():\\n    for i in range(20000):\\n        assert sqrt(mpf(i*i)) == i\\n    random.seed(1)\\n    for prec in [100, 300, 1000, 10000]:\\n        mp.dps = prec\\n        for i in range(20):\\n            A = random.randint(10**(prec//2-2), 10**(prec//2-1))\\n            assert sqrt(mpf(A*A)) == A\\n    mp.dps = 15\\n    for i in range(100):\\n        for a in [1, 8, 25, 112307]:\\n            assert sqrt(mpf((a*a, 2*i))) == mpf((a, i))\\n            assert sqrt(mpf((a*a, -2*i))) == mpf((a, -i))\\n\\ndef test_sqrt_rounding():\\n    for i in [2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15]:\\n        i = from_int(i)\\n        for dps in [7, 15, 83, 106, 2000]:\\n            mp.dps = dps\\n            a = mpf_pow_int(mpf_sqrt(i, mp.prec, round_down), 2, mp.prec, round_down)\\n            b = mpf_pow_int(mpf_sqrt(i, mp.prec, round_up), 2, mp.prec, round_up)\\n            assert mpf_lt(a, i)\\n            assert mpf_gt(b, i)\\n    random.seed(1234)\\n    prec = 100\\n    for rnd in [round_down, round_nearest, round_ceiling]:\\n        for i in range(100):\\n            a = mpf_rand(prec)\\n            b = mpf_mul(a, a)\\n            assert mpf_sqrt(b, prec, rnd) == a\\n    # Test some extreme cases\\n    mp.dps = 100\\n    a = mpf(9) + 1e-90\\n    b = mpf(9) - 1e-90\\n    mp.dps = 15\\n    assert sqrt(a, rounding='d') == 3\\n    assert sqrt(a, rounding='n') == 3\\n    assert sqrt(a, rounding='u') > 3\\n    assert sqrt(b, rounding='d') < 3\\n    assert sqrt(b, rounding='n') == 3\\n    assert sqrt(b, rounding='u') == 3\\n    # A worst case, from the MPFR test suite\\n    assert sqrt(mpf('7.0503726185518891')) == mpf('2.655253776675949')\\n\\ndef test_float_sqrt():\\n    mp.dps = 15\\n    # These should round identically\\n    for x in [0, 1e-7, 0.1, 0.5, 1, 2, 3, 4, 5, 0.333, 76.19]:\\n        assert sqrt(mpf(x)) == float(x)**0.5\\n    assert sqrt(-1) == 1j\\n    assert sqrt(-2).ae(cmath.sqrt(-2))\\n    assert sqrt(-3).ae(cmath.sqrt(-3))\\n    assert sqrt(-100).ae(cmath.sqrt(-100))\\n    assert sqrt(1j).ae(cmath.sqrt(1j))\\n    assert sqrt(-1j).ae(cmath.sqrt(-1j))\\n    assert sqrt(math.pi + math.e*1j).ae(cmath.sqrt(math.pi + math.e*1j))\\n    assert sqrt(math.pi - math.e*1j).ae(cmath.sqrt(math.pi - math.e*1j))\\n\\ndef test_hypot():\\n    assert hypot(0, 0) == 0\\n    assert hypot(0, 0.33) == mpf(0.33)\\n    assert hypot(0.33, 0) == mpf(0.33)\\n    assert hypot(-0.33, 0) == mpf(0.33)\\n    assert hypot(3, 4) == mpf(5)\\n\\ndef test_exact_cbrt():\\n    for i in range(0, 20000, 200):\\n        assert cbrt(mpf(i*i*i)) == i\\n    random.seed(1)\\n    for prec in [100, 300, 1000, 10000]:\\n        mp.dps = prec\\n        A = random.randint(10**(prec//2-2), 10**(prec//2-1))\\n        assert cbrt(mpf(A*A*A)) == A\\n    mp.dps = 15\\n\\ndef test_exp():\\n    assert exp(0) == 1\\n    assert exp(10000).ae(mpf('8.8068182256629215873e4342'))\\n    assert exp(-10000).ae(mpf('1.1354838653147360985e-4343'))\\n    a = exp(mpf((1, 8198646019315405, -53, 53)))\\n    assert(a.bc == bitcount(a.man))\\n    mp.prec = 67\\n    a = exp(mpf((1, 1781864658064754565, -60, 61)))\\n    assert(a.bc == bitcount(a.man))\\n    mp.prec = 53\\n    assert exp(ln2 * 10).ae(1024)\\n    assert exp(2+2j).ae(cmath.exp(2+2j))\\n\\ndef test_issue_73():\\n    mp.dps = 512\\n    a = exp(-1)\\n    b = exp(1)\\n    mp.dps = 15\\n    assert (+a).ae(0.36787944117144233)\\n    assert (+b).ae(2.7182818284590451)\\n\\ndef test_log():\\n    mp.dps = 15\\n    assert log(1) == 0\\n    for x in [0.5, 1.5, 2.0, 3.0, 100, 10**50, 1e-50]:\\n        assert log(x).ae(math.log(x))\\n        assert log(x, x) == 1\\n    assert log(1024, 2) == 10\\n    assert log(10**1234, 10) == 1234\\n    assert log(2+2j).ae(cmath.log(2+2j))\\n    # Accuracy near 1\\n    assert (log(0.6+0.8j).real*10**17).ae(2.2204460492503131)\\n    assert (log(0.6-0.8j).real*10**17).ae(2.2204460492503131)\\n    assert (log(0.8-0.6j).real*10**17).ae(2.2204460492503131)\\n    assert (log(1+1e-8j).real*10**16).ae(0.5)\\n    assert (log(1-1e-8j).real*10**16).ae(0.5)\\n    assert (log(-1+1e-8j).real*10**16).ae(0.5)\\n    assert (log(-1-1e-8j).real*10**16).ae(0.5)\\n    assert (log(1j+1e-8).real*10**16).ae(0.5)\\n    assert (log(1j-1e-8).real*10**16).ae(0.5)\\n    assert (log(-1j+1e-8).real*10**16).ae(0.5)\\n    assert (log(-1j-1e-8).real*10**16).ae(0.5)\\n    assert (log(1+1e-40j).real*10**80).ae(0.5)\\n    assert (log(1j+1e-40).real*10**80).ae(0.5)\\n    # Huge\\n    assert log(ldexp(1.234,10**20)).ae(log(2)*1e20)\\n    assert log(ldexp(1.234,10**200)).ae(log(2)*1e200)\\n    # Some special values\\n    assert log(mpc(0,0)) == mpc(-inf,0)\\n    assert isnan(log(mpc(nan,0)).real)\\n    assert isnan(log(mpc(nan,0)).imag)\\n    assert isnan(log(mpc(0,nan)).real)\\n    assert isnan(log(mpc(0,nan)).imag)\\n    assert isnan(log(mpc(nan,1)).real)\\n    assert isnan(log(mpc(nan,1)).imag)\\n    assert isnan(log(mpc(1,nan)).real)\\n    assert isnan(log(mpc(1,nan)).imag)\\n\\ndef test_trig_hyperb_basic():\\n    for x in (list(range(100)) + list(range(-100,0))):\\n        t = x / 4.1\\n        assert cos(mpf(t)).ae(math.cos(t))\\n        assert sin(mpf(t)).ae(math.sin(t))\\n        assert tan(mpf(t)).ae(math.tan(t))\\n        assert cosh(mpf(t)).ae(math.cosh(t))\\n        assert sinh(mpf(t)).ae(math.sinh(t))\\n        assert tanh(mpf(t)).ae(math.tanh(t))\\n    assert sin(1+1j).ae(cmath.sin(1+1j))\\n    assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))\\n    assert cos(1+1j).ae(cmath.cos(1+1j))\\n    assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j))\\n\\ndef test_degrees():\\n    assert cos(0*degree) == 1\\n    assert cos(90*degree).ae(0)\\n    assert cos(180*degree).ae(-1)\\n    assert cos(270*degree).ae(0)\\n    assert cos(360*degree).ae(1)\\n    assert sin(0*degree) == 0\\n    assert sin(90*degree).ae(1)\\n    assert sin(180*degree).ae(0)\\n    assert sin(270*degree).ae(-1)\\n    assert sin(360*degree).ae(0)\\n\\ndef random_complexes(N):\\n    random.seed(1)\\n    a = []\\n    for i in range(N):\\n        x1 = random.uniform(-10, 10)\\n        y1 = random.uniform(-10, 10)\\n        x2 = random.uniform(-10, 10)\\n        y2 = random.uniform(-10, 10)\\n        z1 = complex(x1, y1)\\n        z2 = complex(x2, y2)\\n        a.append((z1, z2))\\n    return a\\n\\ndef test_complex_powers():\\n    for dps in [15, 30, 100]:\\n        # Check accuracy for complex square root\\n        mp.dps = dps\\n        a = mpc(1j)**0.5\\n        assert a.real == a.imag == mpf(2)**0.5 / 2\\n    mp.dps = 15\\n    random.seed(1)\\n    for (z1, z2) in random_complexes(100):\\n        assert (mpc(z1)**mpc(z2)).ae(z1**z2, 1e-12)\\n    assert (e**(-pi*1j)).ae(-1)\\n    mp.dps = 50\\n    assert (e**(-pi*1j)).ae(-1)\\n    mp.dps = 15\\n\\ndef test_complex_sqrt_accuracy():\\n    def test_mpc_sqrt(lst):\\n        for a, b in lst:\\n            z = mpc(a + j*b)\\n            assert mpc_ae(sqrt(z*z), z)\\n            z = mpc(-a + j*b)\\n            assert mpc_ae(sqrt(z*z), -z)\\n            z = mpc(a - j*b)\\n            assert mpc_ae(sqrt(z*z), z)\\n            z = mpc(-a - j*b)\\n            assert mpc_ae(sqrt(z*z), -z)\\n    random.seed(2)\\n    N = 10\\n    mp.dps = 30\\n    dps = mp.dps\\n    test_mpc_sqrt([(random.uniform(0, 10),random.uniform(0, 10)) for i in range(N)])\\n    test_mpc_sqrt([(i + 0.1, (i + 0.2)*10**i) for i in range(N)])\\n    mp.dps = 15\\n\\ndef test_atan():\\n    mp.dps = 15\\n    assert atan(-2.3).ae(math.atan(-2.3))\\n    assert atan(1e-50) == 1e-50\\n    assert atan(1e50).ae(pi/2)\\n    assert atan(-1e-50) == -1e-50\\n    assert atan(-1e50).ae(-pi/2)\\n    assert atan(10**1000).ae(pi/2)\\n    for dps in [25, 70, 100, 300, 1000]:\\n        mp.dps = dps\\n        assert (4*atan(1)).ae(pi)\\n    mp.dps = 15\\n    pi2 = pi/2\\n    assert atan(mpc(inf,-1)).ae(pi2)\\n    assert atan(mpc(inf,0)).ae(pi2)\\n    assert atan(mpc(inf,1)).ae(pi2)\\n    assert atan(mpc(1,inf)).ae(pi2)\\n    assert atan(mpc(0,inf)).ae(pi2)\\n    assert atan(mpc(-1,inf)).ae(-pi2)\\n    assert atan(mpc(-inf,1)).ae(-pi2)\\n    assert atan(mpc(-inf,0)).ae(-pi2)\\n    assert atan(mpc(-inf,-1)).ae(-pi2)\\n    assert atan(mpc(-1,-inf)).ae(-pi2)\\n    assert atan(mpc(0,-inf)).ae(-pi2)\\n    assert atan(mpc(1,-inf)).ae(pi2)\\n\\ndef test_atan2():\\n    mp.dps = 15\\n    assert atan2(1,1).ae(pi/4)\\n    assert atan2(1,-1).ae(3*pi/4)\\n    assert atan2(-1,-1).ae(-3*pi/4)\\n    assert atan2(-1,1).ae(-pi/4)\\n    assert atan2(-1,0).ae(-pi/2)\\n    assert atan2(1,0).ae(pi/2)\\n    assert atan2(0,0) == 0\\n    assert atan2(inf,0).ae(pi/2)\\n    assert atan2(-inf,0).ae(-pi/2)\\n    assert isnan(atan2(inf,inf))\\n    assert isnan(atan2(-inf,inf))\\n    assert isnan(atan2(inf,-inf))\\n    assert isnan(atan2(3,nan))\\n    assert isnan(atan2(nan,3))\\n    assert isnan(atan2(0,nan))\\n    assert isnan(atan2(nan,0))\\n    assert atan2(0,inf) == 0\\n    assert atan2(0,-inf).ae(pi)\\n    assert atan2(10,inf) == 0\\n    assert atan2(-10,inf) == 0\\n    assert atan2(-10,-inf).ae(-pi)\\n    assert atan2(10,-inf).ae(pi)\\n    assert atan2(inf,10).ae(pi/2)\\n    assert atan2(inf,-10).ae(pi/2)\\n    assert atan2(-inf,10).ae(-pi/2)\\n    assert atan2(-inf,-10).ae(-pi/2)\\n\\ndef test_areal_inverses():\\n    assert asin(mpf(0)) == 0\\n    assert asinh(mpf(0)) == 0\\n    assert acosh(mpf(1)) == 0\\n    assert isinstance(asin(mpf(0.5)), mpf)\\n    assert isinstance(asin(mpf(2.0)), mpc)\\n    assert isinstance(acos(mpf(0.5)), mpf)\\n    assert isinstance(acos(mpf(2.0)), mpc)\\n    assert isinstance(atanh(mpf(0.1)), mpf)\\n    assert isinstance(atanh(mpf(1.1)), mpc)\\n\\n    random.seed(1)\\n    for i in range(50):\\n        x = random.uniform(0, 1)\\n        assert asin(mpf(x)).ae(math.asin(x))\\n        assert acos(mpf(x)).ae(math.acos(x))\\n\\n        x = random.uniform(-10, 10)\\n        assert asinh(mpf(x)).ae(cmath.asinh(x).real)\\n        assert isinstance(asinh(mpf(x)), mpf)\\n        x = random.uniform(1, 10)\\n        assert acosh(mpf(x)).ae(cmath.acosh(x).real)\\n        assert isinstance(acosh(mpf(x)), mpf)\\n        x = random.uniform(-10, 0.999)\\n        assert isinstance(acosh(mpf(x)), mpc)\\n\\n        x = random.uniform(-1, 1)\\n        assert atanh(mpf(x)).ae(cmath.atanh(x).real)\\n        assert isinstance(atanh(mpf(x)), mpf)\\n\\n    dps = mp.dps\\n    mp.dps = 300\\n    assert isinstance(asin(0.5), mpf)\\n    mp.dps = 1000\\n    assert asin(1).ae(pi/2)\\n    assert asin(-1).ae(-pi/2)\\n    mp.dps = dps\\n\\ndef test_invhyperb_inaccuracy():\\n    mp.dps = 15\\n    assert (asinh(1e-5)*10**5).ae(0.99999999998333333)\\n    assert (asinh(1e-10)*10**10).ae(1)\\n    assert (asinh(1e-50)*10**50).ae(1)\\n    assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333)\\n    assert (asinh(-1e-10)*10**10).ae(-1)\\n    assert (asinh(-1e-50)*10**50).ae(-1)\\n    assert asinh(10**20).ae(46.744849040440862)\\n    assert asinh(-10**20).ae(-46.744849040440862)\\n    assert (tanh(1e-10)*10**10).ae(1)\\n    assert (tanh(-1e-10)*10**10).ae(-1)\\n    assert (atanh(1e-10)*10**10).ae(1)\\n    assert (atanh(-1e-10)*10**10).ae(-1)\\n\\ndef test_complex_functions():\\n    for x in (list(range(10)) + list(range(-10,0))):\\n        for y in (list(range(10)) + list(range(-10,0))):\\n            z = complex(x, y)/4.3 + 0.01j\\n            assert exp(mpc(z)).ae(cmath.exp(z))\\n            assert log(mpc(z)).ae(cmath.log(z))\\n            assert cos(mpc(z)).ae(cmath.cos(z))\\n            assert sin(mpc(z)).ae(cmath.sin(z))\\n            assert tan(mpc(z)).ae(cmath.tan(z))\\n            assert sinh(mpc(z)).ae(cmath.sinh(z))\\n            assert cosh(mpc(z)).ae(cmath.cosh(z))\\n            assert tanh(mpc(z)).ae(cmath.tanh(z))\\n\\ndef test_complex_inverse_functions():\\n    mp.dps = 15\\n    iv.dps = 15\\n    for (z1, z2) in random_complexes(30):\\n        # apparently cmath uses a different branch, so we\\n        # can't use it for comparison\\n        assert sinh(asinh(z1)).ae(z1)\\n        #\\n        assert acosh(z1).ae(cmath.acosh(z1))\\n        assert atanh(z1).ae(cmath.atanh(z1))\\n        assert atan(z1).ae(cmath.atan(z1))\\n        # the reason we set a big eps here is that the cmath\\n        # functions are inaccurate\\n        assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12)\\n        assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12)\\n        one = mpf(1)\\n    for i in range(-9, 10, 3):\\n        for k in range(-9, 10, 3):\\n            a = 0.9*j*10**k + 0.8*one*10**i\\n            b = cos(acos(a))\\n            assert b.ae(a)\\n            b = sin(asin(a))\\n            assert b.ae(a)\\n    one = mpf(1)\\n    err = 2*10**-15\\n    for i in range(-9, 9, 3):\\n        for k in range(-9, 9, 3):\\n            a = -0.9*10**k + j*0.8*one*10**i\\n            b = cosh(acosh(a))\\n            assert b.ae(a, err)\\n            b = sinh(asinh(a))\\n            assert b.ae(a, err)\\n\\ndef test_reciprocal_functions():\\n    assert sec(3).ae(-1.01010866590799375)\\n    assert csc(3).ae(7.08616739573718592)\\n    assert cot(3).ae(-7.01525255143453347)\\n    assert sech(3).ae(0.0993279274194332078)\\n    assert csch(3).ae(0.0998215696688227329)\\n    assert coth(3).ae(1.00496982331368917)\\n    assert asec(3).ae(1.23095941734077468)\\n    assert acsc(3).ae(0.339836909454121937)\\n    assert acot(3).ae(0.321750554396642193)\\n    assert asech(0.5).ae(1.31695789692481671)\\n    assert acsch(3).ae(0.327450150237258443)\\n    assert acoth(3).ae(0.346573590279972655)\\n    assert acot(0).ae(1.5707963267948966192)\\n    assert acoth(0).ae(1.5707963267948966192j)\\n\\ndef test_ldexp():\\n    mp.dps = 15\\n    assert ldexp(mpf(2.5), 0) == 2.5\\n    assert ldexp(mpf(2.5), -1) == 1.25\\n    assert ldexp(mpf(2.5), 2) == 10\\n    assert ldexp(mpf('inf'), 3) == mpf('inf')\\n\\ndef test_frexp():\\n    mp.dps = 15\\n    assert frexp(0) == (0.0, 0)\\n    assert frexp(9) == (0.5625, 4)\\n    assert frexp(1) == (0.5, 1)\\n    assert frexp(0.2) == (0.8, -2)\\n    assert frexp(1000) == (0.9765625, 10)\\n\\ndef test_aliases():\\n    assert ln(7) == log(7)\\n    assert log10(3.75) == log(3.75,10)\\n    assert degrees(5.6) == 5.6 / degree\\n    assert radians(5.6) == 5.6 * degree\\n    assert power(-1,0.5) == j\\n    assert fmod(25,7) == 4.0 and isinstance(fmod(25,7), mpf)\\n\\ndef test_arg_sign():\\n    assert arg(3) == 0\\n    assert arg(-3).ae(pi)\\n    assert arg(j).ae(pi/2)\\n    assert arg(-j).ae(-pi/2)\\n    assert arg(0) == 0\\n    assert isnan(atan2(3,nan))\\n    assert isnan(atan2(nan,3))\\n    assert isnan(atan2(0,nan))\\n    assert isnan(atan2(nan,0))\\n    assert isnan(atan2(nan,nan))\\n    assert arg(inf) == 0\\n    assert arg(-inf).ae(pi)\\n    assert isnan(arg(nan))\\n    #assert arg(inf*j).ae(pi/2)\\n    assert sign(0) == 0\\n    assert sign(3) == 1\\n    assert sign(-3) == -1\\n    assert sign(inf) == 1\\n    assert sign(-inf) == -1\\n    assert isnan(sign(nan))\\n    assert sign(j) == j\\n    assert sign(-3*j) == -j\\n    assert sign(1+j).ae((1+j)/sqrt(2))\\n\\ndef test_misc_bugs():\\n    # test that this doesn't raise an exception\\n    mp.dps = 1000\\n    log(1302)\\n    mp.dps = 15\\n\\ndef test_arange():\\n    assert arange(10) == [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0'),\\n                          mpf('4.0'), mpf('5.0'), mpf('6.0'), mpf('7.0'),\\n                          mpf('8.0'), mpf('9.0')]\\n    assert arange(-5, 5) == [mpf('-5.0'), mpf('-4.0'), mpf('-3.0'),\\n                             mpf('-2.0'), mpf('-1.0'), mpf('0.0'),\\n                             mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')]\\n    assert arange(0, 1, 0.1) == [mpf('0.0'), mpf('0.10000000000000001'),\\n                                 mpf('0.20000000000000001'),\\n                                 mpf('0.30000000000000004'),\\n                                 mpf('0.40000000000000002'),\\n                                 mpf('0.5'), mpf('0.60000000000000009'),\\n                                 mpf('0.70000000000000007'),\\n                                 mpf('0.80000000000000004'),\\n                                 mpf('0.90000000000000002')]\\n    assert arange(17, -9, -3) == [mpf('17.0'), mpf('14.0'), mpf('11.0'),\\n                                  mpf('8.0'), mpf('5.0'), mpf('2.0'),\\n                                  mpf('-1.0'), mpf('-4.0'), mpf('-7.0')]\\n    assert arange(0.2, 0.1, -0.1) == [mpf('0.20000000000000001')]\\n    assert arange(0) == []\\n    assert arange(1000, -1) == []\\n    assert arange(-1.23, 3.21, -0.0000001) == []\\n\\ndef test_linspace():\\n    assert linspace(2, 9, 7) == [mpf('2.0'), mpf('3.166666666666667'),\\n        mpf('4.3333333333333339'), mpf('5.5'), mpf('6.666666666666667'),\\n        mpf('7.8333333333333339'), mpf('9.0')]\\n    assert linspace(2, 9, 7, endpoint=0) == [mpf('2.0'), mpf('3.0'), mpf('4.0'),\\n        mpf('5.0'), mpf('6.0'), mpf('7.0'), mpf('8.0')]\\n    assert linspace(2, 7, 1) == [mpf(2)]\\n\\ndef test_float_cbrt():\\n    mp.dps = 30\\n    for a in arange(0,10,0.1):\\n        assert cbrt(a*a*a).ae(a, eps)\\n    assert cbrt(-1).ae(0.5 + j*sqrt(3)/2)\\n    one_third = mpf(1)/3\\n    for a in arange(0,10,2.7) + [0.1 + 10**5]:\\n        a = mpc(a + 1.1j)\\n        r1 = cbrt(a)\\n        mp.dps += 10\\n        r2 = pow(a, one_third)\\n        mp.dps -= 10\\n        assert r1.ae(r2, eps)\\n    mp.dps = 100\\n    for n in range(100, 301, 100):\\n        w = 10**n + j*10**-3\\n        z = w*w*w\\n        r = cbrt(z)\\n        assert mpc_ae(r, w, eps)\\n    mp.dps = 15\\n\\ndef test_root():\\n    mp.dps = 30\\n    random.seed(1)\\n    a = random.randint(0, 10000)\\n    p = a*a*a\\n    r = nthroot(mpf(p), 3)\\n    assert r == a\\n    for n in range(4, 10):\\n        p = p*a\\n        assert nthroot(mpf(p), n) == a\\n    mp.dps = 40\\n    for n in range(10, 5000, 100):\\n        for a in [random.random()*10000, random.random()*10**100]:\\n            r = nthroot(a, n)\\n            r1 = pow(a, mpf(1)/n)\\n            assert r.ae(r1)\\n            r = nthroot(a, -n)\\n            r1 = pow(a, -mpf(1)/n)\\n            assert r.ae(r1)\\n    # XXX: this is broken right now\\n    # tests for nthroot rounding\\n    for rnd in ['nearest', 'up', 'down']:\\n        mp.rounding = rnd\\n        for n in [-5, -3, 3, 5]:\\n            prec = 50\\n            for i in range(10):\\n                mp.prec = prec\\n                a = rand()\\n                mp.prec = 2*prec\\n                b = a**n\\n                mp.prec = prec\\n                r = nthroot(b, n)\\n                assert r == a\\n    mp.dps = 30\\n    for n in range(3, 21):\\n        a = (random.random() + j*random.random())\\n        assert nthroot(a, n).ae(pow(a, mpf(1)/n))\\n        assert mpc_ae(nthroot(a, n), pow(a, mpf(1)/n))\\n        a = (random.random()*10**100 + j*random.random())\\n        r = nthroot(a, n)\\n        mp.dps += 4\\n        r1 = pow(a, mpf(1)/n)\\n        mp.dps -= 4\\n        assert r.ae(r1)\\n        assert mpc_ae(r, r1, eps)\\n        r = nthroot(a, -n)\\n        mp.dps += 4\\n        r1 = pow(a, -mpf(1)/n)\\n        mp.dps -= 4\\n        assert r.ae(r1)\\n        assert mpc_ae(r, r1, eps)\\n    mp.dps = 15\\n    assert nthroot(4, 1) == 4\\n    assert nthroot(4, 0) == 1\\n    assert nthroot(4, -1) == 0.25\\n    assert nthroot(inf, 1) == inf\\n    assert nthroot(inf, 2) == inf\\n    assert nthroot(inf, 3) == inf\\n    assert nthroot(inf, -1) == 0\\n    assert nthroot(inf, -2) == 0\\n    assert nthroot(inf, -3) == 0\\n    assert nthroot(j, 1) == j\\n    assert nthroot(j, 0) == 1\\n    assert nthroot(j, -1) == -j\\n    assert isnan(nthroot(nan, 1))\\n    assert isnan(nthroot(nan, 0))\\n    assert isnan(nthroot(nan, -1))\\n    assert isnan(nthroot(inf, 0))\\n    assert root(2,3) == nthroot(2,3)\\n    assert root(16,4,0) == 2\\n    assert root(16,4,1) == 2j\\n    assert root(16,4,2) == -2\\n    assert root(16,4,3) == -2j\\n    assert root(16,4,4) == 2\\n    assert root(-125,3,1) == -5\\n\\ndef test_issue_136():\\n    for dps in [20, 80]:\\n        mp.dps = dps\\n        r = nthroot(mpf('-1e-20'), 4)\\n        assert r.ae(mpf(10)**(-5) * (1 + j) * mpf(2)**(-0.5))\\n    mp.dps = 80\\n    assert nthroot('-1e-3', 4).ae(mpf(10)**(-3./4) * (1 + j)/sqrt(2))\\n    assert nthroot('-1e-6', 4).ae((1 + j)/(10 * sqrt(20)))\\n    # Check that this doesn't take eternity to compute\\n    mp.dps = 20\\n    assert nthroot('-1e100000000', 4).ae((1+j)*mpf('1e25000000')/sqrt(2))\\n    mp.dps = 15\\n\\ndef test_mpcfun_real_imag():\\n    mp.dps = 15\\n    x = mpf(0.3)\\n    y = mpf(0.4)\\n    assert exp(mpc(x,0)) == exp(x)\\n    assert exp(mpc(0,y)) == mpc(cos(y),sin(y))\\n    assert cos(mpc(x,0)) == cos(x)\\n    assert sin(mpc(x,0)) == sin(x)\\n    assert cos(mpc(0,y)) == cosh(y)\\n    assert sin(mpc(0,y)) == mpc(0,sinh(y))\\n    assert cospi(mpc(x,0)) == cospi(x)\\n    assert sinpi(mpc(x,0)) == sinpi(x)\\n    assert cospi(mpc(0,y)).ae(cosh(pi*y))\\n    assert sinpi(mpc(0,y)).ae(mpc(0,sinh(pi*y)))\\n    c, s = cospi_sinpi(mpc(x,0))\\n    assert c == cospi(x)\\n    assert s == sinpi(x)\\n    c, s = cospi_sinpi(mpc(0,y))\\n    assert c.ae(cosh(pi*y))\\n    assert s.ae(mpc(0,sinh(pi*y)))\\n    c, s = cos_sin(mpc(x,0))\\n    assert c == cos(x)\\n    assert s == sin(x)\\n    c, s = cos_sin(mpc(0,y))\\n    assert c == cosh(y)\\n    assert s == mpc(0,sinh(y))\\n\\ndef test_perturbation_rounding():\\n    mp.dps = 100\\n    a = pi/10**50\\n    b = -pi/10**50\\n    c = 1 + a\\n    d = 1 + b\\n    mp.dps = 15\\n    assert exp(a) == 1\\n    assert exp(a, rounding='c') > 1\\n    assert exp(b, rounding='c') == 1\\n    assert exp(a, rounding='f') == 1\\n    assert exp(b, rounding='f') < 1\\n    assert cos(a) == 1\\n    assert cos(a, rounding='c') == 1\\n    assert cos(b, rounding='c') == 1\\n    assert cos(a, rounding='f') < 1\\n    assert cos(b, rounding='f') < 1\\n    for f in [sin, atan, asinh, tanh]:\\n        assert f(a) == +a\\n        assert f(a, rounding='c') > a\\n        assert f(a, rounding='f') < a\\n        assert f(b) == +b\\n        assert f(b, rounding='c') > b\\n        assert f(b, rounding='f') < b\\n    for f in [asin, tan, sinh, atanh]:\\n        assert f(a) == +a\\n        assert f(b) == +b\\n        assert f(a, rounding='c') > a\\n        assert f(b, rounding='c') > b\\n        assert f(a, rounding='f') < a\\n        assert f(b, rounding='f') < b\\n    assert ln(c) == +a\\n    assert ln(d) == +b\\n    assert ln(c, rounding='c') > a\\n    assert ln(c, rounding='f') < a\\n    assert ln(d, rounding='c') > b\\n    assert ln(d, rounding='f') < b\\n    assert cosh(a) == 1\\n    assert cosh(b) == 1\\n    assert cosh(a, rounding='c') > 1\\n    assert cosh(b, rounding='c') > 1\\n    assert cosh(a, rounding='f') == 1\\n    assert cosh(b, rounding='f') == 1\\n\\ndef test_integer_parts():\\n    assert floor(3.2) == 3\\n    assert ceil(3.2) == 4\\n    assert floor(3.2+5j) == 3+5j\\n    assert ceil(3.2+5j) == 4+5j\\n\\ndef test_complex_parts():\\n    assert fabs('3') == 3\\n    assert fabs(3+4j) == 5\\n    assert re(3) == 3\\n    assert re(1+4j) == 1\\n    assert im(3) == 0\\n    assert im(1+4j) == 4\\n    assert conj(3) == 3\\n    assert conj(3+4j) == 3-4j\\n    assert mpf(3).conjugate() == 3\\n\\ndef test_cospi_sinpi():\\n    assert sinpi(0) == 0\\n    assert sinpi(0.5) == 1\\n    assert sinpi(1) == 0\\n    assert sinpi(1.5) == -1\\n    assert sinpi(2) == 0\\n    assert sinpi(2.5) == 1\\n    assert sinpi(-0.5) == -1\\n    assert cospi(0) == 1\\n    assert cospi(0.5) == 0\\n    assert cospi(1) == -1\\n    assert cospi(1.5) == 0\\n    assert cospi(2) == 1\\n    assert cospi(2.5) == 0\\n    assert cospi(-0.5) == 0\\n    assert cospi(100000000000.25).ae(sqrt(2)/2)\\n    a = cospi(2+3j)\\n    assert a.real.ae(cos((2+3j)*pi).real)\\n    assert a.imag == 0\\n    b = sinpi(2+3j)\\n    assert b.imag.ae(sin((2+3j)*pi).imag)\\n    assert b.real == 0\\n    mp.dps = 35\\n    x1 = mpf(10000) - mpf('1e-15')\\n    x2 = mpf(10000) + mpf('1e-15')\\n    x3 = mpf(10000.5) - mpf('1e-15')\\n    x4 = mpf(10000.5) + mpf('1e-15')\\n    x5 = mpf(10001) - mpf('1e-15')\\n    x6 = mpf(10001) + mpf('1e-15')\\n    x7 = mpf(10001.5) - mpf('1e-15')\\n    x8 = mpf(10001.5) + mpf('1e-15')\\n    mp.dps = 15\\n    M = 10**15\\n    assert (sinpi(x1)*M).ae(-pi)\\n    assert (sinpi(x2)*M).ae(pi)\\n    assert (cospi(x3)*M).ae(pi)\\n    assert (cospi(x4)*M).ae(-pi)\\n    assert (sinpi(x5)*M).ae(pi)\\n    assert (sinpi(x6)*M).ae(-pi)\\n    assert (cospi(x7)*M).ae(-pi)\\n    assert (cospi(x8)*M).ae(pi)\\n    assert 0.999 < cospi(x1, rounding='d') < 1\\n    assert 0.999 < cospi(x2, rounding='d') < 1\\n    assert 0.999 < sinpi(x3, rounding='d') < 1\\n    assert 0.999 < sinpi(x4, rounding='d') < 1\\n    assert -1 < cospi(x5, rounding='d') < -0.999\\n    assert -1 < cospi(x6, rounding='d') < -0.999\\n    assert -1 < sinpi(x7, rounding='d') < -0.999\\n    assert -1 < sinpi(x8, rounding='d') < -0.999\\n    assert (sinpi(1e-15)*M).ae(pi)\\n    assert (sinpi(-1e-15)*M).ae(-pi)\\n    assert cospi(1e-15) == 1\\n    assert cospi(1e-15, rounding='d') < 1\\n\\ndef test_expj():\\n    assert expj(0) == 1\\n    assert expj(1).ae(exp(j))\\n    assert expj(j).ae(exp(-1))\\n    assert expj(1+j).ae(exp(j*(1+j)))\\n    assert expjpi(0) == 1\\n    assert expjpi(1).ae(exp(j*pi))\\n    assert expjpi(j).ae(exp(-pi))\\n    assert expjpi(1+j).ae(exp(j*pi*(1+j)))\\n    assert expjpi(-10**15 * j).ae('2.22579818340535731e+1364376353841841')\\n\\ndef test_sinc():\\n    assert sinc(0) == sincpi(0) == 1\\n    assert sinc(inf) == sincpi(inf) == 0\\n    assert sinc(-inf) == sincpi(-inf) == 0\\n    assert sinc(2).ae(0.45464871341284084770)\\n    assert sinc(2+3j).ae(0.4463290318402435457-2.7539470277436474940j)\\n    assert sincpi(2) == 0\\n    assert sincpi(1.5).ae(-0.212206590789193781)\\n\\ndef test_fibonacci():\\n    mp.dps = 15\\n    assert [fibonacci(n) for n in range(-5, 10)] == \\\\\\n        [5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\\n    assert fib(2.5).ae(1.4893065462657091)\\n    assert fib(3+4j).ae(-5248.51130728372 - 14195.962288353j)\\n    assert fib(1000).ae(4.3466557686937455e+208)\\n    assert str(fib(10**100)) == '6.24499112864607e+2089876402499787337692720892375554168224592399182109535392875613974104853496745963277658556235103534'\\n    mp.dps = 2100\\n    a = fib(10000)\\n    assert a % 10**10 == 9947366875\\n    mp.dps = 15\\n    assert fibonacci(inf) == inf\\n    assert fib(3+0j) == 2\\n\\ndef test_call_with_dps():\\n    mp.dps = 15\\n    assert abs(exp(1, dps=30)-e(dps=35)) < 1e-29\\n\\ndef test_tanh():\\n    mp.dps = 15\\n    assert tanh(0) == 0\\n    assert tanh(inf) == 1\\n    assert tanh(-inf) == -1\\n    assert isnan(tanh(nan))\\n    assert tanh(mpc('inf', '0')) == 1\\n\\ndef test_atanh():\\n    mp.dps = 15\\n    assert atanh(0) == 0\\n    assert atanh(0.5).ae(0.54930614433405484570)\\n    assert atanh(-0.5).ae(-0.54930614433405484570)\\n    assert atanh(1) == inf\\n    assert atanh(-1) == -inf\\n    assert isnan(atanh(nan))\\n    assert isinstance(atanh(1), mpf)\\n    assert isinstance(atanh(-1), mpf)\\n    # Limits at infinity\\n    jpi2 = j*pi/2\\n    assert atanh(inf).ae(-jpi2)\\n    assert atanh(-inf).ae(jpi2)\\n    assert atanh(mpc(inf,-1)).ae(-jpi2)\\n    assert atanh(mpc(inf,0)).ae(-jpi2)\\n    assert atanh(mpc(inf,1)).ae(jpi2)\\n    assert atanh(mpc(1,inf)).ae(jpi2)\\n    assert atanh(mpc(0,inf)).ae(jpi2)\\n    assert atanh(mpc(-1,inf)).ae(jpi2)\\n    assert atanh(mpc(-inf,1)).ae(jpi2)\\n    assert atanh(mpc(-inf,0)).ae(jpi2)\\n    assert atanh(mpc(-inf,-1)).ae(-jpi2)\\n    assert atanh(mpc(-1,-inf)).ae(-jpi2)\\n    assert atanh(mpc(0,-inf)).ae(-jpi2)\\n    assert atanh(mpc(1,-inf)).ae(-jpi2)\\n\\ndef test_expm1():\\n    mp.dps = 15\\n    assert expm1(0) == 0\\n    assert expm1(3).ae(exp(3)-1)\\n    assert expm1(inf) == inf\\n    assert expm1(1e-50).ae(1e-50)\\n    assert (expm1(1e-10)*1e10).ae(1.00000000005)\\n\\ndef test_log1p():\\n    mp.dps = 15\\n    assert log1p(0) == 0\\n    assert log1p(3).ae(log(1+3))\\n    assert log1p(inf) == inf\\n    assert log1p(1e-50).ae(1e-50)\\n    assert (log1p(1e-10)*1e10).ae(0.99999999995)\\n\\ndef test_powm1():\\n    mp.dps = 15\\n    assert powm1(2,3) == 7\\n    assert powm1(-1,2) == 0\\n    assert powm1(-1,0) == 0\\n    assert powm1(-2,0) == 0\\n    assert powm1(3+4j,0) == 0\\n    assert powm1(0,1) == -1\\n    assert powm1(0,0) == 0\\n    assert powm1(1,0) == 0\\n    assert powm1(1,2) == 0\\n    assert powm1(1,3+4j) == 0\\n    assert powm1(1,5) == 0\\n    assert powm1(j,4) == 0\\n    assert powm1(-j,4) == 0\\n    assert (powm1(2,1e-100)*1e100).ae(ln2)\\n    assert powm1(2,'1e-100000000000') != 0\\n    assert (powm1(fadd(1,1e-100,exact=True), 5)*1e100).ae(5)\\n\\ndef test_unitroots():\\n    assert unitroots(1) == [1]\\n    assert unitroots(2) == [1, -1]\\n    a, b, c = unitroots(3)\\n    assert a == 1\\n    assert b.ae(-0.5 + 0.86602540378443864676j)\\n    assert c.ae(-0.5 - 0.86602540378443864676j)\\n    assert unitroots(1, primitive=True) == [1]\\n    assert unitroots(2, primitive=True) == [-1]\\n    assert unitroots(3, primitive=True) == unitroots(3)[1:]\\n    assert unitroots(4, primitive=True) == [j, -j]\\n    assert len(unitroots(17, primitive=True)) == 16\\n    assert len(unitroots(16, primitive=True)) == 8\\n\\ndef test_cyclotomic():\\n    mp.dps = 15\\n    assert [cyclotomic(n,1) for n in range(31)] == [1,0,2,3,2,5,1,7,2,3,1,11,1,13,1,1,2,17,1,19,1,1,1,23,1,5,1,3,1,29,1]\\n    assert [cyclotomic(n,-1) for n in range(31)] == [1,-2,0,1,2,1,3,1,2,1,5,1,1,1,7,1,2,1,3,1,1,1,11,1,1,1,13,1,1,1,1]\\n    assert [cyclotomic(n,j) for n in range(21)] == [1,-1+j,1+j,j,0,1,-j,j,2,-j,1,j,3,1,-j,1,2,1,j,j,5]\\n    assert [cyclotomic(n,-j) for n in range(21)] == [1,-1-j,1-j,-j,0,1,j,-j,2,j,1,-j,3,1,j,1,2,1,-j,-j,5]\\n    assert cyclotomic(1624,j) == 1\\n    assert cyclotomic(33600,j) == 1\\n    u = sqrt(j, prec=500)\\n    assert cyclotomic(8, u).ae(0)\\n    assert cyclotomic(30, u).ae(5.8284271247461900976)\\n    assert cyclotomic(2040, u).ae(1)\\n    assert cyclotomic(0,2.5) == 1\\n    assert cyclotomic(1,2.5) == 2.5-1\\n    assert cyclotomic(2,2.5) == 2.5+1\\n    assert cyclotomic(3,2.5) == 2.5**2 + 2.5 + 1\\n    assert cyclotomic(7,2.5) == 406.234375\\n\\n\\n#!/usr/bin/python\\n# -*- coding: utf-8 -*-\\n\\nfrom mpmath import mp\\nfrom mpmath import libmp\\n\\nxrange = libmp.backend.xrange\\n\\ndef run_eigsy(A, verbose = False):\\n    if verbose:\\n        print(\\\"original matrix:\\\\n\\\", str(A))\\n\\n    D, Q = mp.eigsy(A)\\n    B = Q * mp.diag(D) * Q.transpose()\\n    C = A - B\\n    E = Q * Q.transpose() - mp.eye(A.rows)\\n\\n    if verbose:\\n        print(\\\"eigenvalues:\\\\n\\\", D)\\n        print(\\\"eigenvectors:\\\\n\\\", Q)\\n\\n    NC = mp.mnorm(C)\\n    NE = mp.mnorm(E)\\n\\n    if verbose:\\n        print(\\\"difference:\\\", NC, \\\"\\\\n\\\", C, \\\"\\\\n\\\")\\n        print(\\\"difference:\\\", NE, \\\"\\\\n\\\", E, \\\"\\\\n\\\")\\n\\n    eps = mp.exp( 0.8 * mp.log(mp.eps))\\n\\n    assert NC < eps\\n    assert NE < eps\\n\\n    return NC\\n\\ndef run_eighe(A, verbose = False):\\n    if verbose:\\n        print(\\\"original matrix:\\\\n\\\", str(A))\\n\\n    D, Q = mp.eighe(A)\\n    B = Q * mp.diag(D) * Q.transpose_conj()\\n    C = A - B\\n    E = Q * Q.transpose_conj() - mp.eye(A.rows)\\n\\n    if verbose:\\n        print(\\\"eigenvalues:\\\\n\\\", D)\\n        print(\\\"eigenvectors:\\\\n\\\", Q)\\n\\n    NC = mp.mnorm(C)\\n    NE = mp.mnorm(E)\\n\\n    if verbose:\\n        print(\\\"difference:\\\", NC, \\\"\\\\n\\\", C, \\\"\\\\n\\\")\\n        print(\\\"difference:\\\", NE, \\\"\\\\n\\\", E, \\\"\\\\n\\\")\\n\\n    eps = mp.exp( 0.8 * mp.log(mp.eps))\\n\\n    assert NC < eps\\n    assert NE < eps\\n\\n    return NC\\n\\ndef run_svd_r(A, full_matrices = False, verbose = True):\\n\\n    m, n = A.rows, A.cols\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    if verbose:\\n        print(\\\"original matrix:\\\\n\\\", str(A))\\n        print(\\\"full\\\", full_matrices)\\n\\n    U, S0, V = mp.svd_r(A, full_matrices = full_matrices)\\n\\n    S = mp.zeros(U.cols, V.rows)\\n    for j in xrange(min(m, n)):\\n        S[j,j] = S0[j]\\n\\n    if verbose:\\n        print(\\\"U:\\\\n\\\", str(U))\\n        print(\\\"S:\\\\n\\\", str(S0))\\n        print(\\\"V:\\\\n\\\", str(V))\\n\\n    C = U * S * V - A\\n    err = mp.mnorm(C)\\n    if verbose:\\n        print(\\\"C\\\\n\\\", str(C), \\\"\\\\n\\\", err)\\n    assert err < eps\\n\\n    D = V * V.transpose() - mp.eye(V.rows)\\n    err = mp.mnorm(D)\\n    if verbose:\\n        print(\\\"D:\\\\n\\\", str(D), \\\"\\\\n\\\", err)\\n    assert err < eps\\n\\n    E = U.transpose() * U - mp.eye(U.cols)\\n    err = mp.mnorm(E)\\n    if verbose:\\n        print(\\\"E:\\\\n\\\", str(E), \\\"\\\\n\\\", err)\\n    assert err < eps\\n\\ndef run_svd_c(A, full_matrices = False, verbose = True):\\n\\n    m, n = A.rows, A.cols\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    if verbose:\\n        print(\\\"original matrix:\\\\n\\\", str(A))\\n        print(\\\"full\\\", full_matrices)\\n\\n    U, S0, V = mp.svd_c(A, full_matrices = full_matrices)\\n\\n    S = mp.zeros(U.cols, V.rows)\\n    for j in xrange(min(m, n)):\\n        S[j,j] = S0[j]\\n\\n    if verbose:\\n        print(\\\"U:\\\\n\\\", str(U))\\n        print(\\\"S:\\\\n\\\", str(S0))\\n        print(\\\"V:\\\\n\\\", str(V))\\n\\n    C = U * S * V - A\\n    err = mp.mnorm(C)\\n    if verbose:\\n        print(\\\"C\\\\n\\\", str(C), \\\"\\\\n\\\", err)\\n    assert err  < eps\\n\\n    D = V * V.transpose_conj() - mp.eye(V.rows)\\n    err = mp.mnorm(D)\\n    if verbose:\\n        print(\\\"D:\\\\n\\\", str(D), \\\"\\\\n\\\", err)\\n    assert err < eps\\n\\n    E = U.transpose_conj() * U - mp.eye(U.cols)\\n    err = mp.mnorm(E)\\n    if verbose:\\n        print(\\\"E:\\\\n\\\", str(E), \\\"\\\\n\\\", err)\\n    assert err < eps\\n\\ndef run_gauss(qtype, a, b):\\n    eps = 1e-5\\n\\n    d, e = mp.gauss_quadrature(len(a), qtype)\\n    d -= mp.matrix(a)\\n    e -= mp.matrix(b)\\n\\n    assert mp.mnorm(d) < eps\\n    assert mp.mnorm(e) < eps\\n\\ndef irandmatrix(n, range = 10):\\n    \\\"\\\"\\\"\\n    random matrix with integer entries\\n    \\\"\\\"\\\"\\n    A = mp.matrix(n, n)\\n    for i in xrange(n):\\n        for j in xrange(n):\\n            A[i,j]=int( (2 * mp.rand() - 1) * range)\\n    return A\\n\\n#######################\\n\\ndef test_eighe_fixed_matrix():\\n    A = mp.matrix([[2, 3], [3, 5]])\\n    run_eigsy(A)\\n    run_eighe(A)\\n\\n    A = mp.matrix([[7, -11], [-11, 13]])\\n    run_eigsy(A)\\n    run_eighe(A)\\n\\n    A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]])\\n    run_eigsy(A)\\n    run_eighe(A)\\n\\n    A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]])\\n    run_eigsy(A)\\n    run_eighe(A)\\n\\n    #\\n\\n    A = mp.matrix([[2, 3+7j], [3-7j, 5]])\\n    run_eighe(A)\\n\\n    A = mp.matrix([[2, -11j, 0], [+11j, 3, 29j], [0, -29j, 5]])\\n    run_eighe(A)\\n\\n    A = mp.matrix([[2, 11 + 17j, 7 + 19j], [11 - 17j, 3, -13 + 23j], [7 - 19j, -13 - 23j, 5]])\\n    run_eighe(A)\\n\\ndef test_eigsy_randmatrix():\\n    N = 5\\n\\n    for a in xrange(10):\\n        A = 2 * mp.randmatrix(N, N) - 1\\n\\n        for i in xrange(0, N):\\n            for j in xrange(i + 1, N):\\n                A[j,i] = A[i,j]\\n\\n        run_eigsy(A)\\n\\ndef test_eighe_randmatrix():\\n    N = 5\\n\\n    for a in xrange(10):\\n        A = (2 * mp.randmatrix(N, N) - 1) + 1j * (2 * mp.randmatrix(N, N) - 1)\\n\\n        for i in xrange(0, N):\\n            A[i,i] = mp.re(A[i,i])\\n            for j in xrange(i + 1, N):\\n                A[j,i] = mp.conj(A[i,j])\\n\\n        run_eighe(A)\\n\\ndef test_eigsy_irandmatrix():\\n    N = 4\\n    R = 4\\n\\n    for a in xrange(10):\\n        A=irandmatrix(N, R)\\n\\n        for i in xrange(0, N):\\n            for j in xrange(i + 1, N):\\n                A[j,i] = A[i,j]\\n\\n        run_eigsy(A)\\n\\ndef test_eighe_irandmatrix():\\n    N = 4\\n    R = 4\\n\\n    for a in xrange(10):\\n        A=irandmatrix(N, R) + 1j * irandmatrix(N, R)\\n\\n        for i in xrange(0, N):\\n            A[i,i] = mp.re(A[i,i])\\n            for j in xrange(i + 1, N):\\n                A[j,i] = mp.conj(A[i,j])\\n\\n        run_eighe(A)\\n\\ndef test_svd_r_rand():\\n    for i in xrange(5):\\n        full = mp.rand() > 0.5\\n        m = 1 + int(mp.rand() * 10)\\n        n = 1 + int(mp.rand() * 10)\\n        A = 2 * mp.randmatrix(m, n) - 1\\n        if mp.rand() > 0.5:\\n            A *= 10\\n            for x in xrange(m):\\n                for y in xrange(n):\\n                    A[x,y]=int(A[x,y])\\n\\n        run_svd_r(A, full_matrices = full, verbose = False)\\n\\ndef test_svd_c_rand():\\n    for i in xrange(5):\\n        full = mp.rand() > 0.5\\n        m = 1 + int(mp.rand() * 10)\\n        n = 1 + int(mp.rand() * 10)\\n        A = (2 * mp.randmatrix(m, n) - 1) + 1j * (2 * mp.randmatrix(m, n) - 1)\\n        if mp.rand() > 0.5:\\n            A *= 10\\n            for x in xrange(m):\\n                for y in xrange(n):\\n                    A[x,y]=int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y]))\\n\\n        run_svd_c(A, full_matrices=full, verbose=False)\\n\\ndef test_svd_test_case():\\n    # a test case from Golub and Reinsch\\n    #  (see wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).)\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    a = [[22, 10,  2,   3,  7],\\n         [14,  7, 10,   0,  8],\\n         [-1, 13, -1, -11,  3],\\n         [-3, -2, 13,  -2,  4],\\n         [ 9,  8,  1,  -2,  4],\\n         [ 9,  1, -7,   5, -1],\\n         [ 2, -6,  6,   5,  1],\\n         [ 4,  5,  0,  -2,  2]]\\n\\n    a = mp.matrix(a)\\n    b = mp.matrix([mp.sqrt(1248), 20, mp.sqrt(384), 0, 0])\\n\\n    S = mp.svd_r(a, compute_uv = False)\\n    S -= b\\n    assert mp.mnorm(S) < eps\\n\\n    S = mp.svd_c(a, compute_uv = False)\\n    S -= b\\n    assert mp.mnorm(S) < eps\\n\\n\\ndef test_gauss_quadrature_static():\\n    a = [-0.57735027,  0.57735027]\\n    b = [ 1,  1]\\n    run_gauss(\\\"legendre\\\", a , b)\\n\\n    a = [ -0.906179846,  -0.538469310,   0,           0.538469310,   0.906179846]\\n    b = [  0.23692689,    0.47862867,    0.56888889,  0.47862867,    0.23692689]\\n    run_gauss(\\\"legendre\\\", a , b)\\n\\n    a = [ 0.06943184,  0.33000948,  0.66999052,  0.93056816]\\n    b = [ 0.17392742,  0.32607258,  0.32607258,  0.17392742]\\n    run_gauss(\\\"legendre01\\\", a , b)\\n\\n    a = [-0.70710678,  0.70710678]\\n    b = [ 0.88622693,  0.88622693]\\n    run_gauss(\\\"hermite\\\", a , b)\\n\\n    a = [ -2.02018287,  -0.958572465,   0,           0.958572465,   2.02018287]\\n    b = [  0.01995324,   0.39361932,    0.94530872,  0.39361932,    0.01995324]\\n    run_gauss(\\\"hermite\\\", a , b)\\n\\n    a = [ 0.41577456,  2.29428036,  6.28994508]\\n    b = [ 0.71109301,  0.27851773,  0.01038926]\\n    run_gauss(\\\"laguerre\\\", a , b)\\n\\ndef test_gauss_quadrature_dynamic(verbose = False):\\n    n = 5\\n\\n    A = mp.randmatrix(2 * n, 1)\\n\\n    def F(x):\\n        r = 0\\n        for i in xrange(len(A) - 1, -1, -1):\\n            r = r * x + A[i]\\n        return r\\n\\n    def run(qtype, FW, R, alpha = 0, beta = 0):\\n        X, W = mp.gauss_quadrature(n, qtype, alpha = alpha, beta = beta)\\n\\n        a = 0\\n        for i in xrange(len(X)):\\n            a += W[i] * F(X[i])\\n\\n        b = mp.quad(lambda x: FW(x) * F(x), R)\\n\\n        c = mp.fabs(a - b)\\n\\n        if verbose:\\n            print(qtype, c, a, b)\\n\\n        assert c < 1e-5\\n\\n    run(\\\"legendre\\\", lambda x: 1, [-1, 1])\\n    run(\\\"legendre01\\\", lambda x: 1, [0, 1])\\n    run(\\\"hermite\\\", lambda x: mp.exp(-x*x), [-mp.inf, mp.inf])\\n    run(\\\"laguerre\\\", lambda x: mp.exp(-x), [0, mp.inf])\\n    run(\\\"glaguerre\\\", lambda x: mp.sqrt(x)*mp.exp(-x), [0, mp.inf], alpha = 1 / mp.mpf(2))\\n    run(\\\"chebyshev1\\\", lambda x: 1/mp.sqrt(1-x*x), [-1, 1])\\n    run(\\\"chebyshev2\\\", lambda x: mp.sqrt(1-x*x), [-1, 1])\\n    run(\\\"jacobi\\\", lambda x: (1-x)**(1/mp.mpf(3)) * (1+x)**(1/mp.mpf(5)), [-1, 1], alpha = 1 / mp.mpf(3), beta = 1 / mp.mpf(5) )\\n\\n\\nimport random\\nfrom mpmath import *\\nfrom mpmath.libmp import *\\n\\n\\ndef test_basic_string():\\n    \\\"\\\"\\\"\\n    Test basic string conversion\\n    \\\"\\\"\\\"\\n    mp.dps = 15\\n    assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0)\\n    assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0)\\n    for i in range(10):\\n        for j in range(10):\\n            assert mpf('%ie%i' % (i,j)) == i * 10**j\\n    assert str(mpf('25000.0')) == '25000.0'\\n    assert str(mpf('2500.0')) == '2500.0'\\n    assert str(mpf('250.0')) == '250.0'\\n    assert str(mpf('25.0')) == '25.0'\\n    assert str(mpf('2.5')) == '2.5'\\n    assert str(mpf('0.25')) == '0.25'\\n    assert str(mpf('0.025')) == '0.025'\\n    assert str(mpf('0.0025')) == '0.0025'\\n    assert str(mpf('0.00025')) == '0.00025'\\n    assert str(mpf('0.000025')) == '2.5e-5'\\n    assert str(mpf(0)) == '0.0'\\n    assert str(mpf('2.5e1000000000000000000000')) == '2.5e+1000000000000000000000'\\n    assert str(mpf('2.6e-1000000000000000000000')) == '2.6e-1000000000000000000000'\\n    assert str(mpf(1.23402834e-15)) == '1.23402834e-15'\\n    assert str(mpf(-1.23402834e-15)) == '-1.23402834e-15'\\n    assert str(mpf(-1.2344e-15)) == '-1.2344e-15'\\n    assert repr(mpf(-1.2344e-15)) == \\\"mpf('-1.2343999999999999e-15')\\\"\\n    assert str(mpf(\\\"2163048125L\\\")) == '2163048125.0'\\n    assert str(mpf(\\\"-2163048125l\\\")) == '-2163048125.0'\\n    assert str(mpf(\\\"-2163048125L/1088391168\\\")) == '-1.98738118113799'\\n    assert str(mpf(\\\"2163048125/1088391168l\\\")) == '1.98738118113799'\\n\\ndef test_pretty():\\n    mp.pretty = True\\n    assert repr(mpf(2.5)) == '2.5'\\n    assert repr(mpc(2.5,3.5)) == '(2.5 + 3.5j)'\\n    mp.pretty = False\\n    iv.pretty = True\\n    assert repr(mpi(2.5,3.5)) == '[2.5, 3.5]'\\n    iv.pretty = False\\n\\ndef test_str_whitespace():\\n    assert mpf('1.26 ') == 1.26\\n\\ndef test_unicode():\\n    mp.dps = 15\\n    try:\\n        unicode = unicode\\n    except NameError:\\n        unicode = str\\n    assert mpf(unicode('2.76')) == 2.76\\n    assert mpf(unicode('inf')) == inf\\n\\ndef test_str_format():\\n    assert to_str(from_float(0.1),15,strip_zeros=False) == '0.100000000000000'\\n    assert to_str(from_float(0.0),15,show_zero_exponent=True) == '0.0e+0'\\n    assert to_str(from_float(0.0),0,show_zero_exponent=True) == '.0e+0'\\n    assert to_str(from_float(0.0),0,show_zero_exponent=False) == '.0'\\n    assert to_str(from_float(0.0),1,show_zero_exponent=True) == '0.0e+0'\\n    assert to_str(from_float(0.0),1,show_zero_exponent=False) == '0.0'\\n    assert to_str(from_float(1.23),3,show_zero_exponent=True) == '1.23e+0'\\n    assert to_str(from_float(1.23456789000000e-2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e-2'\\n    assert to_str(from_float(1.23456789000000e+2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e+2'\\n    assert to_str(from_float(2.1287e14), 15, max_fixed=1000) == '212870000000000.0'\\n    assert to_str(from_float(2.1287e15), 15, max_fixed=1000) == '2128700000000000.0'\\n    assert to_str(from_float(2.1287e16), 15, max_fixed=1000) == '21287000000000000.0'\\n    assert to_str(from_float(2.1287e30), 15, max_fixed=1000) == '2128700000000000000000000000000.0'\\n\\ndef test_tight_string_conversion():\\n    mp.dps = 15\\n    # In an old version, '0.5' wasn't recognized as representing\\n    # an exact binary number and was erroneously rounded up or down\\n    assert from_str('0.5', 10, round_floor) == fhalf\\n    assert from_str('0.5', 10, round_ceiling) == fhalf\\n\\ndef test_eval_repr_invariant():\\n    \\\"\\\"\\\"Test that eval(repr(x)) == x\\\"\\\"\\\"\\n    random.seed(123)\\n    for dps in [10, 15, 20, 50, 100]:\\n        mp.dps = dps\\n        for i in range(1000):\\n            a = mpf(random.random())**0.5 * 10**random.randint(-100, 100)\\n            assert eval(repr(a)) == a\\n    mp.dps = 15\\n\\ndef test_str_bugs():\\n    mp.dps = 15\\n    # Decimal rounding used to give the wrong exponent in some cases\\n    assert str(mpf('1e600')) == '1.0e+600'\\n    assert str(mpf('1e10000')) == '1.0e+10000'\\n\\ndef test_str_prec0():\\n    assert to_str(from_float(1.234), 0) == '.0e+0'\\n    assert to_str(from_float(1e-15), 0) == '.0e-15'\\n    assert to_str(from_float(1e+15), 0) == '.0e+15'\\n    assert to_str(from_float(-1e-15), 0) == '-.0e-15'\\n    assert to_str(from_float(-1e+15), 0) == '-.0e+15'\\n\\ndef test_convert_rational():\\n    mp.dps = 15\\n    assert from_rational(30, 5, 53, round_nearest) == (0, 3, 1, 2)\\n    assert from_rational(-7, 4, 53, round_nearest) == (1, 7, -2, 3)\\n    assert to_rational((0, 1, -1, 1)) == (1, 2)\\n\\ndef test_custom_class():\\n    class mympf:\\n        @property\\n        def _mpf_(self):\\n            return mpf(3.5)._mpf_\\n    class mympc:\\n        @property\\n        def _mpc_(self):\\n            return mpf(3.5)._mpf_, mpf(2.5)._mpf_\\n    assert mpf(2) + mympf() == 5.5\\n    assert mympf() + mpf(2) == 5.5\\n    assert mpf(mympf()) == 3.5\\n    assert mympc() + mpc(2) == mpc(5.5, 2.5)\\n    assert mpc(2) + mympc() == mpc(5.5, 2.5)\\n    assert mpc(mympc()) == (3.5+2.5j)\\n\\ndef test_conversion_methods():\\n    class SomethingRandom:\\n        pass\\n    class SomethingReal:\\n        def _mpmath_(self, prec, rounding):\\n            return mp.make_mpf(from_str('1.3', prec, rounding))\\n    class SomethingComplex:\\n        def _mpmath_(self, prec, rounding):\\n            return mp.make_mpc((from_str('1.3', prec, rounding), \\\\\\n                from_str('1.7', prec, rounding)))\\n    x = mpf(3)\\n    z = mpc(3)\\n    a = SomethingRandom()\\n    y = SomethingReal()\\n    w = SomethingComplex()\\n    for d in [15, 45]:\\n        mp.dps = d\\n        assert (x+y).ae(mpf('4.3'))\\n        assert (y+x).ae(mpf('4.3'))\\n        assert (x+w).ae(mpc('4.3', '1.7'))\\n        assert (w+x).ae(mpc('4.3', '1.7'))\\n        assert (z+y).ae(mpc('4.3'))\\n        assert (y+z).ae(mpc('4.3'))\\n        assert (z+w).ae(mpc('4.3', '1.7'))\\n        assert (w+z).ae(mpc('4.3', '1.7'))\\n        x-y; y-x; x-w; w-x; z-y; y-z; z-w; w-z\\n        x*y; y*x; x*w; w*x; z*y; y*z; z*w; w*z\\n        x/y; y/x; x/w; w/x; z/y; y/z; z/w; w/z\\n        x**y; y**x; x**w; w**x; z**y; y**z; z**w; w**z\\n        x==y; y==x; x==w; w==x; z==y; y==z; z==w; w==z\\n    mp.dps = 15\\n    assert x.__add__(a) is NotImplemented\\n    assert x.__radd__(a) is NotImplemented\\n    assert x.__lt__(a) is NotImplemented\\n    assert x.__gt__(a) is NotImplemented\\n    assert x.__le__(a) is NotImplemented\\n    assert x.__ge__(a) is NotImplemented\\n    assert x.__eq__(a) is NotImplemented\\n    assert x.__ne__(a) is NotImplemented\\n    # implementation detail\\n    if hasattr(x, \\\"__cmp__\\\"):\\n        assert x.__cmp__(a) is NotImplemented\\n    assert x.__sub__(a) is NotImplemented\\n    assert x.__rsub__(a) is NotImplemented\\n    assert x.__mul__(a) is NotImplemented\\n    assert x.__rmul__(a) is NotImplemented\\n    assert x.__div__(a) is NotImplemented\\n    assert x.__rdiv__(a) is NotImplemented\\n    assert x.__mod__(a) is NotImplemented\\n    assert x.__rmod__(a) is NotImplemented\\n    assert x.__pow__(a) is NotImplemented\\n    assert x.__rpow__(a) is NotImplemented\\n    assert z.__add__(a) is NotImplemented\\n    assert z.__radd__(a) is NotImplemented\\n    assert z.__eq__(a) is NotImplemented\\n    assert z.__ne__(a) is NotImplemented\\n    assert z.__sub__(a) is NotImplemented\\n    assert z.__rsub__(a) is NotImplemented\\n    assert z.__mul__(a) is NotImplemented\\n    assert z.__rmul__(a) is NotImplemented\\n    assert z.__div__(a) is NotImplemented\\n    assert z.__rdiv__(a) is NotImplemented\\n    assert z.__pow__(a) is NotImplemented\\n    assert z.__rpow__(a) is NotImplemented\\n\\ndef test_mpmathify():\\n    assert mpmathify('1/2') == 0.5\\n    assert mpmathify('(1.0+1.0j)') == mpc(1, 1)\\n    assert mpmathify('(1.2e-10 - 3.4e5j)') == mpc('1.2e-10', '-3.4e5')\\n    assert mpmathify('1j') == mpc(1j)\\n\\ndef test_issue548():\\n    try:\\n        # This expression is invalid, but may trigger the ReDOS vulnerability\\n        # in the regular expression for parsing complex numbers.\\n        mpmathify('(' + '1' * 5000 + '!j')\\n    except:\\n        return\\n    # The expression is invalid and should raise an exception.\\n    assert False\\n\\ndef test_compatibility():\\n    try:\\n        import numpy as np\\n        from fractions import Fraction\\n        from decimal import Decimal\\n        import decimal\\n    except ImportError:\\n        return\\n    # numpy types\\n    for nptype in np.core.numerictypes.typeDict.values():\\n        if issubclass(nptype, np.complexfloating):\\n            x = nptype(complex(0.5, -0.5))\\n        elif issubclass(nptype, np.floating):\\n            x = nptype(0.5)\\n        elif issubclass(nptype, np.integer):\\n            x = nptype(2)\\n        # Handle the weird types\\n        try: diff = np.abs(type(np.sqrt(x))(sqrt(x)) - np.sqrt(x))\\n        except: continue\\n        assert diff < 2.0**-53\\n    #Fraction and Decimal\\n    oldprec = mp.prec\\n    mp.prec = 1000\\n    decimal.getcontext().prec = mp.dps\\n    assert sqrt(Fraction(2, 3)).ae(sqrt(mpf('2/3')))\\n    assert sqrt(Decimal(2)/Decimal(3)).ae(sqrt(mpf('2/3')))\\n    mp.prec = oldprec\\n\\n\\n#!/usr/bin/python\\n# -*- coding: utf-8 -*-\\n\\nfrom mpmath import mp\\nfrom mpmath import libmp\\n\\nxrange = libmp.backend.xrange\\n\\n# Attention:\\n#   These tests run with 15-20 decimal digits precision. For higher precision the\\n#   working precision must be raised.\\n\\ndef test_levin_0():\\n    mp.dps = 17\\n    eps = mp.mpf(mp.eps)\\n    with mp.extraprec(2 * mp.prec):\\n        L = mp.levin(method = \\\"levin\\\", variant = \\\"u\\\")\\n        S, s, n = [], 0, 1\\n        while 1:\\n            s += mp.one / (n * n)\\n            n += 1\\n            S.append(s)\\n            v, e = L.update_psum(S)\\n            if e < eps:\\n                break\\n            if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    eps = mp.exp(0.9 * mp.log(eps))\\n    err = abs(v - mp.pi ** 2 / 6)\\n    assert err < eps\\n    w = mp.nsum(lambda n: 1/(n * n), [1, mp.inf], method = \\\"levin\\\", levin_variant = \\\"u\\\")\\n    err = abs(v - w)\\n    assert err < eps\\n\\ndef test_levin_1():\\n    mp.dps = 17\\n    eps = mp.mpf(mp.eps)\\n    with mp.extraprec(2 * mp.prec):\\n        L = mp.levin(method = \\\"levin\\\", variant = \\\"v\\\")\\n        A, n = [], 1\\n        while 1:\\n            s = mp.mpf(n) ** (2 + 3j)\\n            n += 1\\n            A.append(s)\\n            v, e = L.update(A)\\n            if e < eps:\\n                break\\n            if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    eps = mp.exp(0.9 * mp.log(eps))\\n    err = abs(v - mp.zeta(-2-3j))\\n    assert err < eps\\n    w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = \\\"levin\\\", levin_variant = \\\"v\\\")\\n    err = abs(v - w)\\n    assert err < eps\\n\\ndef test_levin_2():\\n    # [2] A. Sidi - \\\"Pratical Extrapolation Methods\\\" p.373\\n    mp.dps = 17\\n    z=mp.mpf(10)\\n    eps = mp.mpf(mp.eps)\\n    with mp.extraprec(2 * mp.prec):\\n        L = mp.levin(method = \\\"sidi\\\", variant = \\\"t\\\")\\n        n = 0\\n        while 1:\\n            s = (-1)**n * mp.fac(n) * z ** (-n)\\n            v, e = L.step(s)\\n            n += 1\\n            if e < eps:\\n                break\\n            if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    eps = mp.exp(0.9 * mp.log(eps))\\n    exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf])\\n    # there is also a symbolic expression for the integral:\\n    #   exact = z * mp.exp(z) * mp.expint(1,z)\\n    err = abs(v - exact)\\n    assert err < eps\\n    w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = \\\"sidi\\\", levin_variant = \\\"t\\\")\\n    assert err < eps\\n\\ndef test_levin_3():\\n    mp.dps = 17\\n    z=mp.mpf(2)\\n    eps = mp.mpf(mp.eps)\\n    with mp.extraprec(7*mp.prec):  # we need copious amount of precision to sum this highly divergent series\\n        L = mp.levin(method = \\\"levin\\\", variant = \\\"t\\\")\\n        n, s = 0, 0\\n        while 1:\\n            s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n))\\n            n += 1\\n            v, e = L.step_psum(s)\\n            if e < eps:\\n                break\\n            if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    eps = mp.exp(0.8 * mp.log(eps))\\n    exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi)\\n    # there is also a symbolic expression for the integral:\\n    #   exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi))\\n    err = abs(v - exact)\\n    assert err < eps\\n    w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), [0, mp.inf], method = \\\"levin\\\", levin_variant = \\\"t\\\", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)])\\n    err = abs(v - w)\\n    assert err < eps\\n\\ndef test_levin_nsum():\\n    mp.dps = 17\\n\\n    with mp.extraprec(mp.prec):\\n        z = mp.mpf(10) ** (-10)\\n        a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = \\\"l\\\") - 1 / z\\n        assert abs(a - mp.euler) < 1e-10\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = \\\"sidi\\\")\\n    assert abs(a - mp.log(2)) < eps\\n\\n    z = 2 + 1j\\n    f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n))\\n    v = mp.nsum(f, [0, mp.inf], method = \\\"levin\\\", steps = [10 for x in xrange(1000)])\\n    exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z)\\n    assert abs(exact - v) < eps\\n\\ndef test_cohen_alt_0():\\n    mp.dps = 17\\n    AC = mp.cohen_alt()\\n    S, s, n = [], 0, 1\\n    while 1:\\n        s += -((-1) ** n) * mp.one / (n * n)\\n        n += 1\\n        S.append(s)\\n        v, e = AC.update_psum(S)\\n        if e < mp.eps:\\n            break\\n        if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    eps = mp.exp(0.9 * mp.log(mp.eps))\\n    err = abs(v - mp.pi ** 2 / 12)\\n    assert err < eps\\n\\ndef test_cohen_alt_1():\\n    mp.dps = 17\\n    A = []\\n    AC = mp.cohen_alt()\\n    n = 1\\n    while 1:\\n        A.append( mp.loggamma(1 + mp.one / (2 * n - 1)))\\n        A.append(-mp.loggamma(1 + mp.one / (2 * n)))\\n        n += 1\\n        v, e = AC.update(A)\\n        if e < mp.eps:\\n            break\\n        if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n    v = mp.exp(v)\\n    err = abs(v - 1.06215090557106)\\n    assert err < 1e-12\\n\\n\\nimport pytest\\nfrom mpmath import *\\nfrom mpmath.calculus.optimization import Secant, Muller, Bisection, Illinois, \\\\\\n    Pegasus, Anderson, Ridder, ANewton, Newton, MNewton, MDNewton\\n\\ndef test_findroot():\\n    # old tests, assuming secant\\n    mp.dps = 15\\n    assert findroot(lambda x: 4*x-3, mpf(5)).ae(0.75)\\n    assert findroot(sin, mpf(3)).ae(pi)\\n    assert findroot(sin, (mpf(3), mpf(3.14))).ae(pi)\\n    assert findroot(lambda x: x*x+1, mpc(2+2j)).ae(1j)\\n    # test all solvers with 1 starting point\\n    f = lambda x: cos(x)\\n    for solver in [Newton, Secant, MNewton, Muller, ANewton]:\\n        x = findroot(f, 2., solver=solver)\\n        assert abs(f(x)) < eps\\n    # test all solvers with interval of 2 points\\n    for solver in [Secant, Muller, Bisection, Illinois, Pegasus, Anderson,\\n                   Ridder]:\\n        x = findroot(f, (1., 2.), solver=solver)\\n        assert abs(f(x)) < eps\\n    # test types\\n    f = lambda x: (x - 2)**2\\n\\n    assert isinstance(findroot(f, 1, tol=1e-10), mpf)\\n    assert isinstance(iv.findroot(f, 1., tol=1e-10), iv.mpf)\\n    assert isinstance(fp.findroot(f, 1, tol=1e-10), float)\\n    assert isinstance(fp.findroot(f, 1+0j, tol=1e-10), complex)\\n\\n    # issue 401\\n    with pytest.raises(ValueError):\\n        with workprec(2):\\n            findroot(lambda x: x**2 - 4456178*x + 60372201703370,\\n                     mpc(real='5.278e+13', imag='-5.278e+13'))\\n\\n    # issue 192\\n    with pytest.raises(ValueError):\\n        findroot(lambda x: -1, 0)\\n\\n    # issue 387\\n    with pytest.raises(ValueError):\\n        findroot(lambda p: (1 - p)**30 - 1, 0.9)\\n\\ndef test_bisection():\\n    # issue 273\\n    assert findroot(lambda x: x**2-1,(0,2),solver='bisect') == 1\\n\\ndef test_mnewton():\\n    f = lambda x: polyval([1,3,3,1],x)\\n    x = findroot(f, -0.9, solver='mnewton')\\n    assert abs(f(x)) < eps\\n\\ndef test_anewton():\\n    f = lambda x: (x - 2)**100\\n    x = findroot(f, 1., solver=ANewton)\\n    assert abs(f(x)) < eps\\n\\ndef test_muller():\\n    f = lambda x: (2 + x)**3 + 2\\n    x = findroot(f, 1., solver=Muller)\\n    assert abs(f(x)) < eps\\n\\ndef test_multiplicity():\\n    for i in range(1, 5):\\n        assert multiplicity(lambda x: (x - 1)**i, 1) == i\\n    assert multiplicity(lambda x: x**2, 1) == 0\\n\\ndef test_multidimensional():\\n    def f(*x):\\n        return [3*x[0]**2-2*x[1]**2-1, x[0]**2-2*x[0]+x[1]**2+2*x[1]-8]\\n    assert mnorm(jacobian(f, (1,-2)) - matrix([[6,8],[0,-2]]),1) < 1.e-7\\n    for x, error in MDNewton(mp, f, (1,-2), verbose=0,\\n                             norm=lambda x: norm(x, inf)):\\n        pass\\n    assert norm(f(*x), 2) < 1e-14\\n    # The Chinese mathematician Zhu Shijie was the very first to solve this\\n    # nonlinear system 700 years ago\\n    f1 = lambda x, y: -x + 2*y\\n    f2 = lambda x, y: (x**2 + x*(y**2 - 2) - 4*y)  /  (x + 4)\\n    f3 = lambda x, y: sqrt(x**2 + y**2)\\n    def f(x, y):\\n        f1x = f1(x, y)\\n        return (f2(x, y) - f1x, f3(x, y) - f1x)\\n    x = findroot(f, (10, 10))\\n    assert [int(round(i)) for i in x] == [3, 4]\\n\\ndef test_trivial():\\n    assert findroot(lambda x: 0, 1) == 1\\n    assert findroot(lambda x: x, 0) == 0\\n    #assert findroot(lambda x, y: x + y, (1, -1)) == (1, -1)\\n\\n\\nimport math\\nimport pytest\\nfrom mpmath import *\\n\\ndef test_bessel():\\n    mp.dps = 15\\n    assert j0(1).ae(0.765197686557966551)\\n    assert j0(pi).ae(-0.304242177644093864)\\n    assert j0(1000).ae(0.0247866861524201746)\\n    assert j0(-25).ae(0.0962667832759581162)\\n    assert j1(1).ae(0.440050585744933516)\\n    assert j1(pi).ae(0.284615343179752757)\\n    assert j1(1000).ae(0.00472831190708952392)\\n    assert j1(-25).ae(0.125350249580289905)\\n    assert besselj(5,1).ae(0.000249757730211234431)\\n    assert besselj(5+0j,1).ae(0.000249757730211234431)\\n    assert besselj(5,pi).ae(0.0521411843671184747)\\n    assert besselj(5,1000).ae(0.00502540694523318607)\\n    assert besselj(5,-25).ae(0.0660079953984229934)\\n    assert besselj(-3,2).ae(-0.128943249474402051)\\n    assert besselj(-4,2).ae(0.0339957198075684341)\\n    assert besselj(3,3+2j).ae(0.424718794929639595942 + 0.625665327745785804812j)\\n    assert besselj(0.25,4).ae(-0.374760630804249715)\\n    assert besselj(1+2j,3+4j).ae(0.319247428741872131 - 0.669557748880365678j)\\n    assert (besselj(3, 10**10) * 10**5).ae(0.76765081748139204023)\\n    assert bessely(-0.5, 0) == 0\\n    assert bessely(0.5, 0) == -inf\\n    assert bessely(1.5, 0) == -inf\\n    assert bessely(0,0) == -inf\\n    assert bessely(-0.4, 0) == -inf\\n    assert bessely(-0.6, 0) == inf\\n    assert bessely(-1, 0) == inf\\n    assert bessely(-1.4, 0) == inf\\n    assert bessely(-1.6, 0) == -inf\\n    assert bessely(-1, 0) == inf\\n    assert bessely(-2, 0) == -inf\\n    assert bessely(-3, 0) == inf\\n    assert bessely(0.5, 0) == -inf\\n    assert bessely(1, 0) == -inf\\n    assert bessely(1.5, 0) == -inf\\n    assert bessely(2, 0) == -inf\\n    assert bessely(2.5, 0) == -inf\\n    assert bessely(3, 0) == -inf\\n    assert bessely(0,0.5).ae(-0.44451873350670655715)\\n    assert bessely(1,0.5).ae(-1.4714723926702430692)\\n    assert bessely(-1,0.5).ae(1.4714723926702430692)\\n    assert bessely(3.5,0.5).ae(-138.86400867242488443)\\n    assert bessely(0,3+4j).ae(4.6047596915010138655-8.8110771408232264208j)\\n    assert bessely(0,j).ae(-0.26803248203398854876+1.26606587775200833560j)\\n    assert (bessely(3, 10**10) * 10**5).ae(0.21755917537013204058)\\n    assert besseli(0,0) == 1\\n    assert besseli(1,0) == 0\\n    assert besseli(2,0) == 0\\n    assert besseli(-1,0) == 0\\n    assert besseli(-2,0) == 0\\n    assert besseli(0,0.5).ae(1.0634833707413235193)\\n    assert besseli(1,0.5).ae(0.25789430539089631636)\\n    assert besseli(-1,0.5).ae(0.25789430539089631636)\\n    assert besseli(3.5,0.5).ae(0.00068103597085793815863)\\n    assert besseli(0,3+4j).ae(-3.3924877882755196097-1.3239458916287264815j)\\n    assert besseli(0,j).ae(besselj(0,1))\\n    assert (besseli(3, 10**10) * mpf(10)**(-4342944813)).ae(4.2996028505491271875)\\n    assert besselk(0,0) == inf\\n    assert besselk(1,0) == inf\\n    assert besselk(2,0) == inf\\n    assert besselk(-1,0) == inf\\n    assert besselk(-2,0) == inf\\n    assert besselk(0,0.5).ae(0.92441907122766586178)\\n    assert besselk(1,0.5).ae(1.6564411200033008937)\\n    assert besselk(-1,0.5).ae(1.6564411200033008937)\\n    assert besselk(3.5,0.5).ae(207.48418747548460607)\\n    assert besselk(0,3+4j).ae(-0.007239051213570155013+0.026510418350267677215j)\\n    assert besselk(0,j).ae(-0.13863371520405399968-1.20196971531720649914j)\\n    assert (besselk(3, 10**10) * mpf(10)**4342944824).ae(1.1628981033356187851)\\n    # test for issue 331, bug reported by Michael Hartmann\\n    for n in range(10,100,10):\\n        mp.dps = n\\n        assert besseli(91.5,24.7708).ae(\\\"4.00830632138673963619656140653537080438462342928377020695738635559218797348548092636896796324190271316137982810144874264e-41\\\")\\n\\ndef test_bessel_zeros():\\n    mp.dps = 15\\n    assert besseljzero(0,1).ae(2.40482555769577276869)\\n    assert besseljzero(2,1).ae(5.1356223018406825563)\\n    assert besseljzero(1,50).ae(157.86265540193029781)\\n    assert besseljzero(10,1).ae(14.475500686554541220)\\n    assert besseljzero(0.5,3).ae(9.4247779607693797153)\\n    assert besseljzero(2,1,1).ae(3.0542369282271403228)\\n    assert besselyzero(0,1).ae(0.89357696627916752158)\\n    assert besselyzero(2,1).ae(3.3842417671495934727)\\n    assert besselyzero(1,50).ae(156.29183520147840108)\\n    assert besselyzero(10,1).ae(12.128927704415439387)\\n    assert besselyzero(0.5,3).ae(7.8539816339744830962)\\n    assert besselyzero(2,1,1).ae(5.0025829314460639452)\\n\\ndef test_hankel():\\n    mp.dps = 15\\n    assert hankel1(0,0.5).ae(0.93846980724081290423-0.44451873350670655715j)\\n    assert hankel1(1,0.5).ae(0.2422684576748738864-1.4714723926702430692j)\\n    assert hankel1(-1,0.5).ae(-0.2422684576748738864+1.4714723926702430692j)\\n    assert hankel1(1.5,0.5).ae(0.0917016996256513026-2.5214655504213378514j)\\n    assert hankel1(1.5,3+4j).ae(0.0066806866476728165382-0.0036684231610839127106j)\\n    assert hankel2(0,0.5).ae(0.93846980724081290423+0.44451873350670655715j)\\n    assert hankel2(1,0.5).ae(0.2422684576748738864+1.4714723926702430692j)\\n    assert hankel2(-1,0.5).ae(-0.2422684576748738864-1.4714723926702430692j)\\n    assert hankel2(1.5,0.5).ae(0.0917016996256513026+2.5214655504213378514j)\\n    assert hankel2(1.5,3+4j).ae(14.783528526098567526-7.397390270853446512j)\\n\\ndef test_struve():\\n    mp.dps = 15\\n    assert struveh(2,3).ae(0.74238666967748318564)\\n    assert struveh(-2.5,3).ae(0.41271003220971599344)\\n    assert struvel(2,3).ae(1.7476573277362782744)\\n    assert struvel(-2.5,3).ae(1.5153394466819651377)\\n\\ndef test_whittaker():\\n    mp.dps = 15\\n    assert whitm(2,3,4).ae(49.753745589025246591)\\n    assert whitw(2,3,4).ae(14.111656223052932215)\\n\\ndef test_kelvin():\\n    mp.dps = 15\\n    assert ber(2,3).ae(0.80836846563726819091)\\n    assert ber(3,4).ae(-0.28262680167242600233)\\n    assert ber(-3,2).ae(-0.085611448496796363669)\\n    assert bei(2,3).ae(-0.89102236377977331571)\\n    assert bei(-3,2).ae(-0.14420994155731828415)\\n    assert ker(2,3).ae(0.12839126695733458928)\\n    assert ker(-3,2).ae(-0.29802153400559142783)\\n    assert ker(0.5,3).ae(-0.085662378535217097524)\\n    assert kei(2,3).ae(0.036804426134164634000)\\n    assert kei(-3,2).ae(0.88682069845786731114)\\n    assert kei(0.5,3).ae(0.013633041571314302948)\\n\\ndef test_hyper_misc():\\n    mp.dps = 15\\n    assert hyp0f1(1,0) == 1\\n    assert hyp1f1(1,2,0) == 1\\n    assert hyp1f2(1,2,3,0) == 1\\n    assert hyp2f1(1,2,3,0) == 1\\n    assert hyp2f2(1,2,3,4,0) == 1\\n    assert hyp2f3(1,2,3,4,5,0) == 1\\n    # Degenerate case: 0F0\\n    assert hyper([],[],0) == 1\\n    assert hyper([],[],-2).ae(exp(-2))\\n    # Degenerate case: 1F0\\n    assert hyper([2],[],1.5) == 4\\n    #\\n    assert hyp2f1((1,3),(2,3),(5,6),mpf(27)/32).ae(1.6)\\n    assert hyp2f1((1,4),(1,2),(3,4),mpf(80)/81).ae(1.8)\\n    assert hyp2f1((2,3),(1,1),(3,2),(2+j)/3).ae(1.327531603558679093+0.439585080092769253j)\\n    mp.dps = 25\\n    v = mpc('1.2282306665029814734863026', '-0.1225033830118305184672133')\\n    assert hyper([(3,4),2+j,1],[1,5,j/3],mpf(1)/5+j/8).ae(v)\\n    mp.dps = 15\\n\\ndef test_elliptic_integrals():\\n    mp.dps = 15\\n    assert ellipk(0).ae(pi/2)\\n    assert ellipk(0.5).ae(gamma(0.25)**2/(4*sqrt(pi)))\\n    assert ellipk(1) == inf\\n    assert ellipk(1+0j) == inf\\n    assert ellipk(-1).ae('1.3110287771460599052')\\n    assert ellipk(-2).ae('1.1714200841467698589')\\n    assert isinstance(ellipk(-2), mpf)\\n    assert isinstance(ellipe(-2), mpf)\\n    assert ellipk(-50).ae('0.47103424540873331679')\\n    mp.dps = 30\\n    n1 = +fraction(99999,100000)\\n    n2 = +fraction(100001,100000)\\n    mp.dps = 15\\n    assert ellipk(n1).ae('7.1427724505817781901')\\n    assert ellipk(n2).ae(mpc('7.1427417367963090109', '-1.5707923998261688019'))\\n    assert ellipe(n1).ae('1.0000332138990829170')\\n    v = ellipe(n2)\\n    assert v.real.ae('0.999966786328145474069137')\\n    assert (v.imag*10**6).ae('7.853952181727432')\\n    assert ellipk(2).ae(mpc('1.3110287771460599052', '-1.3110287771460599052'))\\n    assert ellipk(50).ae(mpc('0.22326753950210985451', '-0.47434723226254522087'))\\n    assert ellipk(3+4j).ae(mpc('0.91119556380496500866', '0.63133428324134524388'))\\n    assert ellipk(3-4j).ae(mpc('0.91119556380496500866', '-0.63133428324134524388'))\\n    assert ellipk(-3+4j).ae(mpc('0.95357894880405122483', '0.23093044503746114444'))\\n    assert ellipk(-3-4j).ae(mpc('0.95357894880405122483', '-0.23093044503746114444'))\\n    assert isnan(ellipk(nan))\\n    assert isnan(ellipe(nan))\\n    assert ellipk(inf) == 0\\n    assert isinstance(ellipk(inf), mpc)\\n    assert ellipk(-inf) == 0\\n    assert ellipk(1+0j) == inf\\n    assert ellipe(0).ae(pi/2)\\n    assert ellipe(0.5).ae(pi**(mpf(3)/2)/gamma(0.25)**2 +gamma(0.25)**2/(8*sqrt(pi)))\\n    assert ellipe(1) == 1\\n    assert ellipe(1+0j) == 1\\n    assert ellipe(inf) == mpc(0,inf)\\n    assert ellipe(-inf) == inf\\n    assert ellipe(3+4j).ae(1.4995535209333469543-1.5778790079127582745j)\\n    assert ellipe(3-4j).ae(1.4995535209333469543+1.5778790079127582745j)\\n    assert ellipe(-3+4j).ae(2.5804237855343377803-0.8306096791000413778j)\\n    assert ellipe(-3-4j).ae(2.5804237855343377803+0.8306096791000413778j)\\n    assert ellipe(2).ae(0.59907011736779610372+0.59907011736779610372j)\\n    assert ellipe('1e-1000000000').ae(pi/2)\\n    assert ellipk('1e-1000000000').ae(pi/2)\\n    assert ellipe(-pi).ae(2.4535865983838923)\\n    mp.dps = 50\\n    assert ellipk(1/pi).ae('1.724756270009501831744438120951614673874904182624739673')\\n    assert ellipe(1/pi).ae('1.437129808135123030101542922290970050337425479058225712')\\n    assert ellipk(-10*pi).ae('0.5519067523886233967683646782286965823151896970015484512')\\n    assert ellipe(-10*pi).ae('5.926192483740483797854383268707108012328213431657645509')\\n    v = ellipk(pi)\\n    assert v.real.ae('0.973089521698042334840454592642137667227167622330325225')\\n    assert v.imag.ae('-1.156151296372835303836814390793087600271609993858798016')\\n    v = ellipe(pi)\\n    assert v.real.ae('0.4632848917264710404078033487934663562998345622611263332')\\n    assert v.imag.ae('1.0637961621753130852473300451583414489944099504180510966')\\n    mp.dps = 15\\n\\ndef test_exp_integrals():\\n    mp.dps = 15\\n    x = +e\\n    z = e + sqrt(3)*j\\n    assert ei(x).ae(8.21168165538361560)\\n    assert li(x).ae(1.89511781635593676)\\n    assert si(x).ae(1.82104026914756705)\\n    assert ci(x).ae(0.213958001340379779)\\n    assert shi(x).ae(4.11520706247846193)\\n    assert chi(x).ae(4.09647459290515367)\\n    assert fresnels(x).ae(0.437189718149787643)\\n    assert fresnelc(x).ae(0.401777759590243012)\\n    assert airyai(x).ae(0.0108502401568586681)\\n    assert airybi(x).ae(8.98245748585468627)\\n    assert ei(z).ae(3.72597969491314951 + 7.34213212314224421j)\\n    assert li(z).ae(2.28662658112562502 + 1.50427225297269364j)\\n    assert si(z).ae(2.48122029237669054 + 0.12684703275254834j)\\n    assert ci(z).ae(0.169255590269456633 - 0.892020751420780353j)\\n    assert shi(z).ae(1.85810366559344468 + 3.66435842914920263j)\\n    assert chi(z).ae(1.86787602931970484 + 3.67777369399304159j)\\n    assert fresnels(z/3).ae(0.034534397197008182 + 0.754859844188218737j)\\n    assert fresnelc(z/3).ae(1.261581645990027372 + 0.417949198775061893j)\\n    assert airyai(z).ae(-0.0162552579839056062 - 0.0018045715700210556j)\\n    assert airybi(z).ae(-4.98856113282883371 + 2.08558537872180623j)\\n    assert li(0) == 0.0\\n    assert li(1) == -inf\\n    assert li(inf) == inf\\n    assert isinstance(li(0.7), mpf)\\n    assert si(inf).ae(pi/2)\\n    assert si(-inf).ae(-pi/2)\\n    assert ci(inf) == 0\\n    assert ci(0) == -inf\\n    assert isinstance(ei(-0.7), mpf)\\n    assert airyai(inf) == 0\\n    assert airybi(inf) == inf\\n    assert airyai(-inf) == 0\\n    assert airybi(-inf) == 0\\n    assert fresnels(inf) == 0.5\\n    assert fresnelc(inf) == 0.5\\n    assert fresnels(-inf) == -0.5\\n    assert fresnelc(-inf) == -0.5\\n    assert shi(0) == 0\\n    assert shi(inf) == inf\\n    assert shi(-inf) == -inf\\n    assert chi(0) == -inf\\n    assert chi(inf) == inf\\n\\ndef test_ei():\\n    mp.dps = 15\\n    assert ei(0) == -inf\\n    assert ei(inf) == inf\\n    assert ei(-inf) == -0.0\\n    assert ei(20+70j).ae(6.1041351911152984397e6 - 2.7324109310519928872e6j)\\n    # tests for the asymptotic expansion\\n    # values checked with Mathematica ExpIntegralEi\\n    mp.dps = 50\\n    r = ei(20000)\\n    s = '3.8781962825045010930273870085501819470698476975019e+8681'\\n    assert str(r) == s\\n    r = ei(-200)\\n    s = '-6.8852261063076355977108174824557929738368086933303e-90'\\n    assert str(r) == s\\n    r =ei(20000 + 10*j)\\n    sre = '-3.255138234032069402493850638874410725961401274106e+8681'\\n    sim = '-2.1081929993474403520785942429469187647767369645423e+8681'\\n    assert str(r.real) == sre and str(r.imag) == sim\\n    mp.dps = 15\\n    # More asymptotic expansions\\n    assert chi(-10**6+100j).ae('1.3077239389562548386e+434288 + 7.6808956999707408158e+434287j')\\n    assert shi(-10**6+100j).ae('-1.3077239389562548386e+434288 - 7.6808956999707408158e+434287j')\\n    mp.dps = 15\\n    assert ei(10j).ae(-0.0454564330044553726+3.2291439210137706686j)\\n    assert ei(100j).ae(-0.0051488251426104921+3.1330217936839529126j)\\n    u = ei(fmul(10**20, j, exact=True))\\n    assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps)\\n    assert u.imag.ae(pi)\\n    assert ei(-10j).ae(-0.0454564330044553726-3.2291439210137706686j)\\n    assert ei(-100j).ae(-0.0051488251426104921-3.1330217936839529126j)\\n    u = ei(fmul(-10**20, j, exact=True))\\n    assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps)\\n    assert u.imag.ae(-pi)\\n    assert ei(10+10j).ae(-1576.1504265768517448+436.9192317011328140j)\\n    u = ei(-10+10j)\\n    assert u.real.ae(7.6698978415553488362543e-7, abs_eps=0, rel_eps=8*eps)\\n    assert u.imag.ae(3.141595611735621062025)\\n\\ndef test_e1():\\n    mp.dps = 15\\n    assert e1(0) == inf\\n    assert e1(inf) == 0\\n    assert e1(-inf) == mpc(-inf, -pi)\\n    assert e1(10j).ae(0.045456433004455372635 + 0.087551267423977430100j)\\n    assert e1(100j).ae(0.0051488251426104921444 - 0.0085708599058403258790j)\\n    assert e1(fmul(10**20, j, exact=True)).ae(6.4525128526578084421e-21 - 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps)\\n    assert e1(-10j).ae(0.045456433004455372635 - 0.087551267423977430100j)\\n    assert e1(-100j).ae(0.0051488251426104921444 + 0.0085708599058403258790j)\\n    assert e1(fmul(-10**20, j, exact=True)).ae(6.4525128526578084421e-21 + 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps)\\n\\ndef test_expint():\\n    mp.dps = 15\\n    assert expint(0,0) == inf\\n    assert expint(0,1).ae(1/e)\\n    assert expint(0,1.5).ae(2/exp(1.5)/3)\\n    assert expint(1,1).ae(-ei(-1))\\n    assert expint(2,0).ae(1)\\n    assert expint(3,0).ae(1/2.)\\n    assert expint(4,0).ae(1/3.)\\n    assert expint(-2, 0.5).ae(26/sqrt(e))\\n    assert expint(-1,-1) == 0\\n    assert expint(-2,-1).ae(-e)\\n    assert expint(5.5, 0).ae(2/9.)\\n    assert expint(2.00000001,0).ae(100000000./100000001)\\n    assert expint(2+3j,4-j).ae(0.0023461179581675065414+0.0020395540604713669262j)\\n    assert expint('1.01', '1e-1000').ae(99.9999999899412802)\\n    assert expint('1.000000000001', 3.5).ae(0.00697013985754701819446)\\n    assert expint(2,3).ae(3*ei(-3)+exp(-3))\\n    assert (expint(10,20)*10**10).ae(0.694439055541231353)\\n    assert expint(3,inf) == 0\\n    assert expint(3.2,inf) == 0\\n    assert expint(3.2+2j,inf) == 0\\n    assert expint(1,3j).ae(-0.11962978600800032763 + 0.27785620120457163717j)\\n    assert expint(1,3).ae(0.013048381094197037413)\\n    assert expint(1,-3).ae(-ei(3)-pi*j)\\n    #assert expint(3) == expint(1,3)\\n    assert expint(1,-20).ae(-25615652.66405658882 - 3.1415926535897932385j)\\n    assert expint(1000000,0).ae(1./999999)\\n    assert expint(0,2+3j).ae(-0.025019798357114678171 + 0.027980439405104419040j)\\n    assert expint(-1,2+3j).ae(-0.022411973626262070419 + 0.038058922011377716932j)\\n    assert expint(-1.5,0) == inf\\n\\ndef test_trig_integrals():\\n    mp.dps = 30\\n    assert si(mpf(1)/1000000).ae('0.000000999999999999944444444444446111')\\n    assert ci(mpf(1)/1000000).ae('-13.2382948930629912435014366276')\\n    assert si(10**10).ae('1.5707963267075846569685111517747537')\\n    assert ci(10**10).ae('-4.87506025174822653785729773959e-11')\\n    assert si(10**100).ae(pi/2)\\n    assert (ci(10**100)*10**100).ae('-0.372376123661276688262086695553')\\n    assert si(-3) == -si(3)\\n    assert ci(-3).ae(ci(3) + pi*j)\\n    # Test complex structure\\n    mp.dps = 15\\n    assert mp.ci(50).ae(-0.0056283863241163054402)\\n    assert mp.ci(50+2j).ae(-0.018378282946133067149+0.070352808023688336193j)\\n    assert mp.ci(20j).ae(1.28078263320282943611e7+1.5707963267949j)\\n    assert mp.ci(-2+20j).ae(-4.050116856873293505e6+1.207476188206989909e7j)\\n    assert mp.ci(-50+2j).ae(-0.0183782829461330671+3.0712398455661049023j)\\n    assert mp.ci(-50).ae(-0.0056283863241163054+3.1415926535897932385j)\\n    assert mp.ci(-50-2j).ae(-0.0183782829461330671-3.0712398455661049023j)\\n    assert mp.ci(-2-20j).ae(-4.050116856873293505e6-1.207476188206989909e7j)\\n    assert mp.ci(-20j).ae(1.28078263320282943611e7-1.5707963267949j)\\n    assert mp.ci(50-2j).ae(-0.018378282946133067149-0.070352808023688336193j)\\n    assert mp.si(50).ae(1.5516170724859358947)\\n    assert mp.si(50+2j).ae(1.497884414277228461-0.017515007378437448j)\\n    assert mp.si(20j).ae(1.2807826332028294459e7j)\\n    assert mp.si(-2+20j).ae(-1.20747603112735722103e7-4.050116856873293554e6j)\\n    assert mp.si(-50+2j).ae(-1.497884414277228461-0.017515007378437448j)\\n    assert mp.si(-50).ae(-1.5516170724859358947)\\n    assert mp.si(-50-2j).ae(-1.497884414277228461+0.017515007378437448j)\\n    assert mp.si(-2-20j).ae(-1.20747603112735722103e7+4.050116856873293554e6j)\\n    assert mp.si(-20j).ae(-1.2807826332028294459e7j)\\n    assert mp.si(50-2j).ae(1.497884414277228461+0.017515007378437448j)\\n    assert mp.chi(50j).ae(-0.0056283863241163054+1.5707963267948966192j)\\n    assert mp.chi(-2+50j).ae(-0.0183782829461330671+1.6411491348185849554j)\\n    assert mp.chi(-20).ae(1.28078263320282943611e7+3.1415926535898j)\\n    assert mp.chi(-20-2j).ae(-4.050116856873293505e6+1.20747571696809187053e7j)\\n    assert mp.chi(-2-50j).ae(-0.0183782829461330671-1.6411491348185849554j)\\n    assert mp.chi(-50j).ae(-0.0056283863241163054-1.5707963267948966192j)\\n    assert mp.chi(2-50j).ae(-0.0183782829461330671-1.500443518771208283j)\\n    assert mp.chi(20-2j).ae(-4.050116856873293505e6-1.20747603112735722951e7j)\\n    assert mp.chi(20).ae(1.2807826332028294361e7)\\n    assert mp.chi(2+50j).ae(-0.0183782829461330671+1.500443518771208283j)\\n    assert mp.shi(50j).ae(1.5516170724859358947j)\\n    assert mp.shi(-2+50j).ae(0.017515007378437448+1.497884414277228461j)\\n    assert mp.shi(-20).ae(-1.2807826332028294459e7)\\n    assert mp.shi(-20-2j).ae(4.050116856873293554e6-1.20747603112735722103e7j)\\n    assert mp.shi(-2-50j).ae(0.017515007378437448-1.497884414277228461j)\\n    assert mp.shi(-50j).ae(-1.5516170724859358947j)\\n    assert mp.shi(2-50j).ae(-0.017515007378437448-1.497884414277228461j)\\n    assert mp.shi(20-2j).ae(-4.050116856873293554e6-1.20747603112735722103e7j)\\n    assert mp.shi(20).ae(1.2807826332028294459e7)\\n    assert mp.shi(2+50j).ae(-0.017515007378437448+1.497884414277228461j)\\n    def ae(x,y,tol=1e-12):\\n        return abs(x-y) <= abs(y)*tol\\n    assert fp.ci(fp.inf) == 0\\n    assert ae(fp.ci(fp.ninf), fp.pi*1j)\\n    assert ae(fp.si(fp.inf), fp.pi/2)\\n    assert ae(fp.si(fp.ninf), -fp.pi/2)\\n    assert fp.si(0) == 0\\n    assert ae(fp.ci(50), -0.0056283863241163054402)\\n    assert ae(fp.ci(50+2j), -0.018378282946133067149+0.070352808023688336193j)\\n    assert ae(fp.ci(20j), 1.28078263320282943611e7+1.5707963267949j)\\n    assert ae(fp.ci(-2+20j), -4.050116856873293505e6+1.207476188206989909e7j)\\n    assert ae(fp.ci(-50+2j), -0.0183782829461330671+3.0712398455661049023j)\\n    assert ae(fp.ci(-50), -0.0056283863241163054+3.1415926535897932385j)\\n    assert ae(fp.ci(-50-2j), -0.0183782829461330671-3.0712398455661049023j)\\n    assert ae(fp.ci(-2-20j), -4.050116856873293505e6-1.207476188206989909e7j)\\n    assert ae(fp.ci(-20j), 1.28078263320282943611e7-1.5707963267949j)\\n    assert ae(fp.ci(50-2j), -0.018378282946133067149-0.070352808023688336193j)\\n    assert ae(fp.si(50), 1.5516170724859358947)\\n    assert ae(fp.si(50+2j), 1.497884414277228461-0.017515007378437448j)\\n    assert ae(fp.si(20j), 1.2807826332028294459e7j)\\n    assert ae(fp.si(-2+20j), -1.20747603112735722103e7-4.050116856873293554e6j)\\n    assert ae(fp.si(-50+2j), -1.497884414277228461-0.017515007378437448j)\\n    assert ae(fp.si(-50), -1.5516170724859358947)\\n    assert ae(fp.si(-50-2j), -1.497884414277228461+0.017515007378437448j)\\n    assert ae(fp.si(-2-20j), -1.20747603112735722103e7+4.050116856873293554e6j)\\n    assert ae(fp.si(-20j), -1.2807826332028294459e7j)\\n    assert ae(fp.si(50-2j), 1.497884414277228461+0.017515007378437448j)\\n    assert ae(fp.chi(50j), -0.0056283863241163054+1.5707963267948966192j)\\n    assert ae(fp.chi(-2+50j), -0.0183782829461330671+1.6411491348185849554j)\\n    assert ae(fp.chi(-20), 1.28078263320282943611e7+3.1415926535898j)\\n    assert ae(fp.chi(-20-2j), -4.050116856873293505e6+1.20747571696809187053e7j)\\n    assert ae(fp.chi(-2-50j), -0.0183782829461330671-1.6411491348185849554j)\\n    assert ae(fp.chi(-50j), -0.0056283863241163054-1.5707963267948966192j)\\n    assert ae(fp.chi(2-50j), -0.0183782829461330671-1.500443518771208283j)\\n    assert ae(fp.chi(20-2j), -4.050116856873293505e6-1.20747603112735722951e7j)\\n    assert ae(fp.chi(20), 1.2807826332028294361e7)\\n    assert ae(fp.chi(2+50j), -0.0183782829461330671+1.500443518771208283j)\\n    assert ae(fp.shi(50j), 1.5516170724859358947j)\\n    assert ae(fp.shi(-2+50j), 0.017515007378437448+1.497884414277228461j)\\n    assert ae(fp.shi(-20), -1.2807826332028294459e7)\\n    assert ae(fp.shi(-20-2j), 4.050116856873293554e6-1.20747603112735722103e7j)\\n    assert ae(fp.shi(-2-50j), 0.017515007378437448-1.497884414277228461j)\\n    assert ae(fp.shi(-50j), -1.5516170724859358947j)\\n    assert ae(fp.shi(2-50j), -0.017515007378437448-1.497884414277228461j)\\n    assert ae(fp.shi(20-2j), -4.050116856873293554e6-1.20747603112735722103e7j)\\n    assert ae(fp.shi(20), 1.2807826332028294459e7)\\n    assert ae(fp.shi(2+50j), -0.017515007378437448+1.497884414277228461j)\\n\\ndef test_airy():\\n    mp.dps = 15\\n    assert (airyai(10)*10**10).ae(1.1047532552898687)\\n    assert (airybi(10)/10**9).ae(0.45564115354822515)\\n    assert (airyai(1000)*10**9158).ae(9.306933063179556004)\\n    assert (airybi(1000)/10**9154).ae(5.4077118391949465477)\\n    assert airyai(-1000).ae(0.055971895773019918842)\\n    assert airybi(-1000).ae(-0.083264574117080633012)\\n    assert (airyai(100+100j)*10**188).ae(2.9099582462207032076 + 2.353013591706178756j)\\n    assert (airybi(100+100j)/10**185).ae(1.7086751714463652039 - 3.1416590020830804578j)\\n\\ndef test_hyper_0f1():\\n    mp.dps = 15\\n    v = 8.63911136507950465\\n    assert hyper([],[(1,3)],1.5).ae(v)\\n    assert hyper([],[1/3.],1.5).ae(v)\\n    assert hyp0f1(1/3.,1.5).ae(v)\\n    assert hyp0f1((1,3),1.5).ae(v)\\n    # Asymptotic expansion\\n    assert hyp0f1(3,1e9).ae('4.9679055380347771271e+27455')\\n    assert hyp0f1(3,1e9j).ae('-2.1222788784457702157e+19410 + 5.0840597555401854116e+19410j')\\n\\ndef test_hyper_1f1():\\n    mp.dps = 15\\n    v = 1.2917526488617656673\\n    assert hyper([(1,2)],[(3,2)],0.7).ae(v)\\n    assert hyper([(1,2)],[(3,2)],0.7+0j).ae(v)\\n    assert hyper([0.5],[(3,2)],0.7).ae(v)\\n    assert hyper([0.5],[1.5],0.7).ae(v)\\n    assert hyper([0.5],[(3,2)],0.7+0j).ae(v)\\n    assert hyper([0.5],[1.5],0.7+0j).ae(v)\\n    assert hyper([(1,2)],[1.5+0j],0.7).ae(v)\\n    assert hyper([0.5+0j],[1.5],0.7).ae(v)\\n    assert hyper([0.5+0j],[1.5+0j],0.7+0j).ae(v)\\n    assert hyp1f1(0.5,1.5,0.7).ae(v)\\n    assert hyp1f1((1,2),1.5,0.7).ae(v)\\n    # Asymptotic expansion\\n    assert hyp1f1(2,3,1e10).ae('2.1555012157015796988e+4342944809')\\n    assert (hyp1f1(2,3,1e10j)*10**10).ae(-0.97501205020039745852 - 1.7462392454512132074j)\\n    # Shouldn't use asymptotic expansion\\n    assert hyp1f1(-2, 1, 10000).ae(49980001)\\n    # Bug\\n    assert hyp1f1(1j,fraction(1,3),0.415-69.739j).ae(25.857588206024346592 + 15.738060264515292063j)\\n\\ndef test_hyper_2f1():\\n    mp.dps = 15\\n    v = 1.0652207633823291032\\n    assert hyper([(1,2), (3,4)], [2], 0.3).ae(v)\\n    assert hyper([(1,2), 0.75], [2], 0.3).ae(v)\\n    assert hyper([0.5, 0.75], [2.0], 0.3).ae(v)\\n    assert hyper([0.5, 0.75], [2.0], 0.3+0j).ae(v)\\n    assert hyper([0.5+0j, (3,4)], [2.0], 0.3+0j).ae(v)\\n    assert hyper([0.5+0j, (3,4)], [2.0], 0.3).ae(v)\\n    assert hyper([0.5, (3,4)], [2.0+0j], 0.3).ae(v)\\n    assert hyper([0.5+0j, 0.75+0j], [2.0+0j], 0.3+0j).ae(v)\\n    v = 1.09234681096223231717 + 0.18104859169479360380j\\n    assert hyper([(1,2),0.75+j], [2], 0.5).ae(v)\\n    assert hyper([0.5,0.75+j], [2.0], 0.5).ae(v)\\n    assert hyper([0.5,0.75+j], [2.0], 0.5+0j).ae(v)\\n    assert hyper([0.5,0.75+j], [2.0+0j], 0.5+0j).ae(v)\\n    v = 0.9625 - 0.125j\\n    assert hyper([(3,2),-1],[4], 0.1+j/3).ae(v)\\n    assert hyper([1.5,-1.0],[4], 0.1+j/3).ae(v)\\n    assert hyper([1.5,-1.0],[4+0j], 0.1+j/3).ae(v)\\n    assert hyper([1.5+0j,-1.0+0j],[4+0j], 0.1+j/3).ae(v)\\n    v = 1.02111069501693445001 - 0.50402252613466859521j\\n    assert hyper([(2,10),(3,10)],[(4,10)],1.5).ae(v)\\n    assert hyper([0.2,(3,10)],[0.4+0j],1.5).ae(v)\\n    assert hyper([0.2,(3,10)],[0.4+0j],1.5+0j).ae(v)\\n    v = 0.76922501362865848528 + 0.32640579593235886194j\\n    assert hyper([(2,10),(3,10)],[(4,10)],4+2j).ae(v)\\n    assert hyper([0.2,(3,10)],[0.4+0j],4+2j).ae(v)\\n    assert hyper([0.2,(3,10)],[(4,10)],4+2j).ae(v)\\n\\ndef test_hyper_2f1_hard():\\n    mp.dps = 15\\n    # Singular cases\\n    assert hyp2f1(2,-1,-1,3).ae(7)\\n    assert hyp2f1(2,-1,-1,3,eliminate_all=True).ae(0.25)\\n    assert hyp2f1(2,-2,-2,3).ae(34)\\n    assert hyp2f1(2,-2,-2,3,eliminate_all=True).ae(0.25)\\n    assert hyp2f1(2,-2,-3,3) == 14\\n    assert hyp2f1(2,-3,-2,3) == inf\\n    assert hyp2f1(2,-1.5,-1.5,3) == 0.25\\n    assert hyp2f1(1,2,3,0) == 1\\n    assert hyp2f1(0,1,0,0) == 1\\n    assert hyp2f1(0,0,0,0) == 1\\n    assert isnan(hyp2f1(1,1,0,0))\\n    assert hyp2f1(2,-1,-5, 0.25+0.25j).ae(1.1+0.1j)\\n    assert hyp2f1(2,-5,-5, 0.25+0.25j, eliminate=False).ae(163./128 + 125./128*j)\\n    assert hyp2f1(0.7235, -1, -5, 0.3).ae(1.04341)\\n    assert hyp2f1(0.7235, -5, -5, 0.3, eliminate=False).ae(1.2939225017815903812)\\n    assert hyp2f1(-1,-2,4,1) == 1.5\\n    assert hyp2f1(1,2,-3,1) == inf\\n    assert hyp2f1(-2,-2,1,1) == 6\\n    assert hyp2f1(1,-2,-4,1).ae(5./3)\\n    assert hyp2f1(0,-6,-4,1) == 1\\n    assert hyp2f1(0,-3,-4,1) == 1\\n    assert hyp2f1(0,0,0,1) == 1\\n    assert hyp2f1(1,0,0,1,eliminate=False) == 1\\n    assert hyp2f1(1,1,0,1) == inf\\n    assert hyp2f1(1,-6,-4,1) == inf\\n    assert hyp2f1(-7.2,-0.5,-4.5,1) == 0\\n    assert hyp2f1(-7.2,-1,-2,1).ae(-2.6)\\n    assert hyp2f1(1,-0.5,-4.5, 1) == inf\\n    assert hyp2f1(1,0.5,-4.5, 1) == -inf\\n    # Check evaluation on / close to unit circle\\n    z = exp(j*pi/3)\\n    w = (nthroot(2,3)+1)*exp(j*pi/12)/nthroot(3,4)**3\\n    assert hyp2f1('1/2','1/6','1/3', z).ae(w)\\n    assert hyp2f1('1/2','1/6','1/3', z.conjugate()).ae(w.conjugate())\\n    assert hyp2f1(0.25, (1,3), 2, '0.999').ae(1.06826449496030635)\\n    assert hyp2f1(0.25, (1,3), 2, '1.001').ae(1.06867299254830309446-0.00001446586793975874j)\\n    assert hyp2f1(0.25, (1,3), 2, -1).ae(0.96656584492524351673)\\n    assert hyp2f1(0.25, (1,3), 2, j).ae(0.99041766248982072266+0.03777135604180735522j)\\n    assert hyp2f1(2,3,5,'0.99').ae(27.699347904322690602)\\n    assert hyp2f1((3,2),-0.5,3,'0.99').ae(0.68403036843911661388)\\n    assert hyp2f1(2,3,5,1j).ae(0.37290667145974386127+0.59210004902748285917j)\\n    assert fsum([hyp2f1((7,10),(2,3),(-1,2), 0.95*exp(j*k)) for k in range(1,15)]).ae(52.851400204289452922+6.244285013912953225j)\\n    assert fsum([hyp2f1((7,10),(2,3),(-1,2), 1.05*exp(j*k)) for k in range(1,15)]).ae(54.506013786220655330-3.000118813413217097j)\\n    assert fsum([hyp2f1((7,10),(2,3),(-1,2), exp(j*k)) for k in range(1,15)]).ae(55.792077935955314887+1.731986485778500241j)\\n    assert hyp2f1(2,2.5,-3.25,0.999).ae(218373932801217082543180041.33)\\n    # Branches\\n    assert hyp2f1(1,1,2,1.01).ae(4.5595744415723676911-3.1104877758314784539j)\\n    assert hyp2f1(1,1,2,1.01+0.1j).ae(2.4149427480552782484+1.4148224796836938829j)\\n    assert hyp2f1(1,1,2,3+4j).ae(0.14576709331407297807+0.48379185417980360773j)\\n    assert hyp2f1(1,1,2,4).ae(-0.27465307216702742285 - 0.78539816339744830962j)\\n    assert hyp2f1(1,1,2,-4).ae(0.40235947810852509365)\\n    # Other:\\n    # Cancellation with a large parameter involved (bug reported on sage-devel)\\n    assert hyp2f1(112, (51,10), (-9,10), -0.99999).ae(-1.6241361047970862961e-24, abs_eps=0, rel_eps=eps*16)\\n\\ndef test_hyper_3f2_etc():\\n    assert hyper([1,2,3],[1.5,8],-1).ae(0.67108992351533333030)\\n    assert hyper([1,2,3,4],[5,6,7], -1).ae(0.90232988035425506008)\\n    assert hyper([1,2,3],[1.25,5], 1).ae(28.924181329701905701)\\n    assert hyper([1,2,3,4],[5,6,7],5).ae(1.5192307344006649499-1.1529845225075537461j)\\n    assert hyper([1,2,3,4,5],[6,7,8,9],-1).ae(0.96288759462882357253)\\n    assert hyper([1,2,3,4,5],[6,7,8,9],1).ae(1.0428697385885855841)\\n    assert hyper([1,2,3,4,5],[6,7,8,9],5).ae(1.33980653631074769423-0.07143405251029226699j)\\n    assert hyper([1,2.79,3.08,4.37],[5.2,6.1,7.3],5).ae(1.0996321464692607231-1.7748052293979985001j)\\n    assert hyper([1,1,1],[1,2],1) == inf\\n    assert hyper([1,1,1],[2,(101,100)],1).ae(100.01621213528313220)\\n    # slow -- covered by doctests\\n    #assert hyper([1,1,1],[2,3],0.9999).ae(1.2897972005319693905)\\n\\ndef test_hyper_u():\\n    mp.dps = 15\\n    assert hyperu(2,-3,0).ae(0.05)\\n    assert hyperu(2,-3.5,0).ae(4./99)\\n    assert hyperu(2,0,0) == 0.5\\n    assert hyperu(-5,1,0) == -120\\n    assert hyperu(-5,2,0) == inf\\n    assert hyperu(-5,-2,0) == 0\\n    assert hyperu(7,7,3).ae(0.00014681269365593503986)  #exp(3)*gammainc(-6,3)\\n    assert hyperu(2,-3,4).ae(0.011836478100271995559)\\n    assert hyperu(3,4,5).ae(1./125)\\n    assert hyperu(2,3,0.0625) == 256\\n    assert hyperu(-1,2,0.25+0.5j) == -1.75+0.5j\\n    assert hyperu(0.5,1.5,7.25).ae(2/sqrt(29))\\n    assert hyperu(2,6,pi).ae(0.55804439825913399130)\\n    assert (hyperu((3,2),8,100+201j)*10**4).ae(-0.3797318333856738798 - 2.9974928453561707782j)\\n    assert (hyperu((5,2),(-1,2),-5000)*10**10).ae(-5.6681877926881664678j)\\n    # XXX: fails because of undetected cancellation in low level series code\\n    # Alternatively: could use asymptotic series here, if convergence test\\n    # tweaked back to recognize this one\\n    #assert (hyperu((5,2),(-1,2),-500)*10**7).ae(-1.82526906001593252847j)\\n\\ndef test_hyper_2f0():\\n    mp.dps = 15\\n    assert hyper([1,2],[],3) == hyp2f0(1,2,3)\\n    assert hyp2f0(2,3,7).ae(0.0116108068639728714668 - 0.0073727413865865802130j)\\n    assert hyp2f0(2,3,0) == 1\\n    assert hyp2f0(0,0,0) == 1\\n    assert hyp2f0(-1,-1,1).ae(2)\\n    assert hyp2f0(-4,1,1.5).ae(62.5)\\n    assert hyp2f0(-4,1,50).ae(147029801)\\n    assert hyp2f0(-4,1,0.0001).ae(0.99960011997600240000)\\n    assert hyp2f0(0.5,0.25,0.001).ae(1.0001251174078538115)\\n    assert hyp2f0(0.5,0.25,3+4j).ae(0.85548875824755163518 + 0.21636041283392292973j)\\n    # Important: cancellation check\\n    assert hyp2f0((1,6),(5,6),-0.02371708245126284498).ae(0.996785723120804309)\\n    # Should be exact; polynomial case\\n    assert hyp2f0(-2,1,0.5+0.5j,zeroprec=200) == 0\\n    assert hyp2f0(1,-2,0.5+0.5j,zeroprec=200) == 0\\n    # There used to be a bug in thresholds that made one of the following hang\\n    for d in [15, 50, 80]:\\n        mp.dps = d\\n        assert hyp2f0(1.5, 0.5, 0.009).ae('1.006867007239309717945323585695344927904000945829843527398772456281301440034218290443367270629519483 + 1.238277162240704919639384945859073461954721356062919829456053965502443570466701567100438048602352623e-46j')\\n\\ndef test_hyper_1f2():\\n    mp.dps = 15\\n    assert hyper([1],[2,3],4) == hyp1f2(1,2,3,4)\\n    a1,b1,b2 = (1,10),(2,3),1./16\\n    assert hyp1f2(a1,b1,b2,10).ae(298.7482725554557568)\\n    assert hyp1f2(a1,b1,b2,100).ae(224128961.48602947604)\\n    assert hyp1f2(a1,b1,b2,1000).ae(1.1669528298622675109e+27)\\n    assert hyp1f2(a1,b1,b2,10000).ae(2.4780514622487212192e+86)\\n    assert hyp1f2(a1,b1,b2,100000).ae(1.3885391458871523997e+274)\\n    assert hyp1f2(a1,b1,b2,1000000).ae('9.8851796978960318255e+867')\\n    assert hyp1f2(a1,b1,b2,10**7).ae('1.1505659189516303646e+2746')\\n    assert hyp1f2(a1,b1,b2,10**8).ae('1.4672005404314334081e+8685')\\n    assert hyp1f2(a1,b1,b2,10**20).ae('3.6888217332150976493e+8685889636')\\n    assert hyp1f2(a1,b1,b2,10*j).ae(-16.163252524618572878 - 44.321567896480184312j)\\n    assert hyp1f2(a1,b1,b2,100*j).ae(61938.155294517848171 + 637349.45215942348739j)\\n    assert hyp1f2(a1,b1,b2,1000*j).ae(8455057657257695958.7 + 6261969266997571510.6j)\\n    assert hyp1f2(a1,b1,b2,10000*j).ae(-8.9771211184008593089e+60 + 4.6550528111731631456e+59j)\\n    assert hyp1f2(a1,b1,b2,100000*j).ae(2.6398091437239324225e+193 + 4.1658080666870618332e+193j)\\n    assert hyp1f2(a1,b1,b2,1000000*j).ae('3.5999042951925965458e+613 + 1.5026014707128947992e+613j')\\n    assert hyp1f2(a1,b1,b2,10**7*j).ae('-8.3208715051623234801e+1939 - 3.6752883490851869429e+1941j')\\n    assert hyp1f2(a1,b1,b2,10**8*j).ae('2.0724195707891484454e+6140 - 1.3276619482724266387e+6141j')\\n    assert hyp1f2(a1,b1,b2,10**20*j).ae('-1.1734497974795488504e+6141851462 + 1.1498106965385471542e+6141851462j')\\n\\ndef test_hyper_2f3():\\n    mp.dps = 15\\n    assert hyper([1,2],[3,4,5],6) == hyp2f3(1,2,3,4,5,6)\\n    a1,a2,b1,b2,b3 = (1,10),(2,3),(3,10), 2, 1./16\\n    # Check asymptotic expansion\\n    assert hyp2f3(a1,a2,b1,b2,b3,10).ae(128.98207160698659976)\\n    assert hyp2f3(a1,a2,b1,b2,b3,1000).ae(6.6309632883131273141e25)\\n    assert hyp2f3(a1,a2,b1,b2,b3,10000).ae(4.6863639362713340539e84)\\n    assert hyp2f3(a1,a2,b1,b2,b3,100000).ae(8.6632451236103084119e271)\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**6).ae('2.0291718386574980641e865')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**7).ae('7.7639836665710030977e2742')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**8).ae('3.2537462584071268759e8681')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**20).ae('1.2966030542911614163e+8685889627')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10*j).ae(-18.551602185587547854 - 13.348031097874113552j)\\n    assert hyp2f3(a1,a2,b1,b2,b3,100*j).ae(78634.359124504488695 + 74459.535945281973996j)\\n    assert hyp2f3(a1,a2,b1,b2,b3,1000*j).ae(597682550276527901.59 - 65136194809352613.078j)\\n    assert hyp2f3(a1,a2,b1,b2,b3,10000*j).ae(-1.1779696326238582496e+59 + 1.2297607505213133872e+59j)\\n    assert hyp2f3(a1,a2,b1,b2,b3,100000*j).ae(2.9844228969804380301e+191 + 7.5587163231490273296e+190j)\\n    assert hyp2f3(a1,a2,b1,b2,b3,1000000*j).ae('7.4859161049322370311e+610 - 2.8467477015940090189e+610j')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**7*j).ae('-1.7477645579418800826e+1938 - 1.7606522995808116405e+1938j')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**8*j).ae('-1.6932731942958401784e+6137 - 2.4521909113114629368e+6137j')\\n    assert hyp2f3(a1,a2,b1,b2,b3,10**20*j).ae('-2.0988815677627225449e+6141851451 + 5.7708223542739208681e+6141851452j')\\n\\ndef test_hyper_2f2():\\n    mp.dps = 15\\n    assert hyper([1,2],[3,4],5) == hyp2f2(1,2,3,4,5)\\n    a1,a2,b1,b2 = (3,10),4,(1,2),1./16\\n    assert hyp2f2(a1,a2,b1,b2,10).ae(448225936.3377556696)\\n    assert hyp2f2(a1,a2,b1,b2,10000).ae('1.2012553712966636711e+4358')\\n    assert hyp2f2(a1,a2,b1,b2,-20000).ae(-0.04182343755661214626)\\n    assert hyp2f2(a1,a2,b1,b2,10**20).ae('1.1148680024303263661e+43429448190325182840')\\n\\ndef test_orthpoly():\\n    mp.dps = 15\\n    assert jacobi(-4,2,3,0.7).ae(22800./4913)\\n    assert jacobi(3,2,4,5.5) == 4133.125\\n    assert jacobi(1.5,5/6.,4,0).ae(-1.0851951434075508417)\\n    assert jacobi(-2, 1, 2, 4).ae(-0.16)\\n    assert jacobi(2, -1, 2.5, 4).ae(34.59375)\\n    #assert jacobi(2, -1, 2, 4) == 28.5\\n    assert legendre(5, 7) == 129367\\n    assert legendre(0.5,0).ae(0.53935260118837935667)\\n    assert legendre(-1,-1) == 1\\n    assert legendre(0,-1) == 1\\n    assert legendre(0, 1) == 1\\n    assert legendre(1, -1) == -1\\n    assert legendre(7, 1) == 1\\n    assert legendre(7, -1) == -1\\n    assert legendre(8,1.5).ae(15457523./32768)\\n    assert legendre(j,-j).ae(2.4448182735671431011 + 0.6928881737669934843j)\\n    assert chebyu(5,1) == 6\\n    assert chebyt(3,2) == 26\\n    assert legendre(3.5,-1) == inf\\n    assert legendre(4.5,-1) == -inf\\n    assert legendre(3.5+1j,-1) == mpc(inf,inf)\\n    assert legendre(4.5+1j,-1) == mpc(-inf,-inf)\\n    assert laguerre(4, -2, 3).ae(-1.125)\\n    assert laguerre(3, 1+j, 0.5).ae(0.2291666666666666667 + 2.5416666666666666667j)\\n\\ndef test_hermite():\\n    mp.dps = 15\\n    assert hermite(-2, 0).ae(0.5)\\n    assert hermite(-1, 0).ae(0.88622692545275801365)\\n    assert hermite(0, 0).ae(1)\\n    assert hermite(1, 0) == 0\\n    assert hermite(2, 0).ae(-2)\\n    assert hermite(0, 2).ae(1)\\n    assert hermite(1, 2).ae(4)\\n    assert hermite(1, -2).ae(-4)\\n    assert hermite(2, -2).ae(14)\\n    assert hermite(0.5, 0).ae(0.69136733903629335053)\\n    assert hermite(9, 0) == 0\\n    assert hermite(4,4).ae(3340)\\n    assert hermite(3,4).ae(464)\\n    assert hermite(-4,4).ae(0.00018623860287512396181)\\n    assert hermite(-3,4).ae(0.0016540169879668766270)\\n    assert hermite(9, 2.5j).ae(13638725j)\\n    assert hermite(9, -2.5j).ae(-13638725j)\\n    assert hermite(9, 100).ae(511078883759363024000)\\n    assert hermite(9, -100).ae(-511078883759363024000)\\n    assert hermite(9, 100j).ae(512922083920643024000j)\\n    assert hermite(9, -100j).ae(-512922083920643024000j)\\n    assert hermite(-9.5, 2.5j).ae(-2.9004951258126778174e-6 + 1.7601372934039951100e-6j)\\n    assert hermite(-9.5, -2.5j).ae(-2.9004951258126778174e-6 - 1.7601372934039951100e-6j)\\n    assert hermite(-9.5, 100).ae(1.3776300722767084162e-22, abs_eps=0, rel_eps=eps)\\n    assert hermite(-9.5, -100).ae('1.3106082028470671626e4355')\\n    assert hermite(-9.5, 100j).ae(-9.7900218581864768430e-23 - 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps)\\n    assert hermite(-9.5, -100j).ae(-9.7900218581864768430e-23 + 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps)\\n    assert hermite(2+3j, -1-j).ae(851.3677063883687676 - 1496.4373467871007997j)\\n\\ndef test_gegenbauer():\\n    mp.dps = 15\\n    assert gegenbauer(1,2,3).ae(12)\\n    assert gegenbauer(2,3,4).ae(381)\\n    assert gegenbauer(0,0,0) == 0\\n    assert gegenbauer(2,-1,3) == 0\\n    assert gegenbauer(-7, 0.5, 3).ae(8989)\\n    assert gegenbauer(1, -0.5, 3).ae(-3)\\n    assert gegenbauer(1, -1.5, 3).ae(-9)\\n    assert gegenbauer(1, -0.5, 3).ae(-3)\\n    assert gegenbauer(-0.5, -0.5, 3).ae(-2.6383553159023906245)\\n    assert gegenbauer(2+3j, 1-j, 3+4j).ae(14.880536623203696780 + 20.022029711598032898j)\\n    #assert gegenbauer(-2, -0.5, 3).ae(-12)\\n\\ndef test_legenp():\\n    mp.dps = 15\\n    assert legenp(2,0,4) == legendre(2,4)\\n    assert legenp(-2, -1, 0.5).ae(0.43301270189221932338)\\n    assert legenp(-2, -1, 0.5, type=3).ae(0.43301270189221932338j)\\n    assert legenp(-2, 1, 0.5).ae(-0.86602540378443864676)\\n    assert legenp(2+j, 3+4j, -j).ae(134742.98773236786148 + 429782.72924463851745j)\\n    assert legenp(2+j, 3+4j, -j, type=3).ae(802.59463394152268507 - 251.62481308942906447j)\\n    assert legenp(2,4,3).ae(0)\\n    assert legenp(2,4,3,type=3).ae(0)\\n    assert legenp(2,1,0.5).ae(-1.2990381056766579701)\\n    assert legenp(2,1,0.5,type=3).ae(1.2990381056766579701j)\\n    assert legenp(3,2,3).ae(-360)\\n    assert legenp(3,3,3).ae(240j*2**0.5)\\n    assert legenp(3,4,3).ae(0)\\n    assert legenp(0,0.5,2).ae(0.52503756790433198939 - 0.52503756790433198939j)\\n    assert legenp(-1,-0.5,2).ae(0.60626116232846498110 + 0.60626116232846498110j)\\n    assert legenp(-2,0.5,2).ae(1.5751127037129959682 - 1.5751127037129959682j)\\n    assert legenp(-2,0.5,-0.5).ae(-0.85738275810499171286)\\n\\ndef test_legenq():\\n    mp.dps = 15\\n    f = legenq\\n    # Evaluation at poles\\n    assert isnan(f(3,2,1))\\n    assert isnan(f(3,2,-1))\\n    assert isnan(f(3,2,1,type=3))\\n    assert isnan(f(3,2,-1,type=3))\\n    # Evaluation at 0\\n    assert f(0,1,0,type=2).ae(-1)\\n    assert f(-2,2,0,type=2,zeroprec=200).ae(0)\\n    assert f(1.5,3,0,type=2).ae(-2.2239343475841951023)\\n    assert f(0,1,0,type=3).ae(j)\\n    assert f(-2,2,0,type=3,zeroprec=200).ae(0)\\n    assert f(1.5,3,0,type=3).ae(2.2239343475841951022*(1-1j))\\n    # Standard case, degree 0\\n    assert f(0,0,-1.5).ae(-0.8047189562170501873 + 1.5707963267948966192j)\\n    assert f(0,0,-0.5).ae(-0.54930614433405484570)\\n    assert f(0,0,0,zeroprec=200).ae(0)\\n    assert f(0,0,0.5).ae(0.54930614433405484570)\\n    assert f(0,0,1.5).ae(0.8047189562170501873 - 1.5707963267948966192j)\\n    assert f(0,0,-1.5,type=3).ae(-0.80471895621705018730)\\n    assert f(0,0,-0.5,type=3).ae(-0.5493061443340548457 - 1.5707963267948966192j)\\n    assert f(0,0,0,type=3).ae(-1.5707963267948966192j)\\n    assert f(0,0,0.5,type=3).ae(0.5493061443340548457 - 1.5707963267948966192j)\\n    assert f(0,0,1.5,type=3).ae(0.80471895621705018730)\\n    # Standard case, degree 1\\n    assert f(1,0,-1.5).ae(0.2070784343255752810 - 2.3561944901923449288j)\\n    assert f(1,0,-0.5).ae(-0.72534692783297257715)\\n    assert f(1,0,0).ae(-1)\\n    assert f(1,0,0.5).ae(-0.72534692783297257715)\\n    assert f(1,0,1.5).ae(0.2070784343255752810 - 2.3561944901923449288j)\\n    # Standard case, degree 2\\n    assert f(2,0,-1.5).ae(-0.0635669991240192885 + 4.5160394395353277803j)\\n    assert f(2,0,-0.5).ae(0.81866326804175685571)\\n    assert f(2,0,0,zeroprec=200).ae(0)\\n    assert f(2,0,0.5).ae(-0.81866326804175685571)\\n    assert f(2,0,1.5).ae(0.0635669991240192885 - 4.5160394395353277803j)\\n    # Misc orders and degrees\\n    assert f(2,3,1.5,type=2).ae(-5.7243340223994616228j)\\n    assert f(2,3,1.5,type=3).ae(-5.7243340223994616228)\\n    assert f(2,3,0.5,type=2).ae(-12.316805742712016310)\\n    assert f(2,3,0.5,type=3).ae(-12.316805742712016310j)\\n    assert f(2,3,-1.5,type=2).ae(-5.7243340223994616228j)\\n    assert f(2,3,-1.5,type=3).ae(5.7243340223994616228)\\n    assert f(2,3,-0.5,type=2).ae(-12.316805742712016310)\\n    assert f(2,3,-0.5,type=3).ae(-12.316805742712016310j)\\n    assert f(2+3j, 3+4j, 0.5, type=3).ae(0.0016119404873235186807 - 0.0005885900510718119836j)\\n    assert f(2+3j, 3+4j, -1.5, type=3).ae(0.008451400254138808670 + 0.020645193304593235298j)\\n    assert f(-2.5,1,-1.5).ae(3.9553395527435335749j)\\n    assert f(-2.5,1,-0.5).ae(1.9290561746445456908)\\n    assert f(-2.5,1,0).ae(1.2708196271909686299)\\n    assert f(-2.5,1,0.5).ae(-0.31584812990742202869)\\n    assert f(-2.5,1,1.5).ae(-3.9553395527435335742 + 0.2993235655044701706j)\\n    assert f(-2.5,1,-1.5,type=3).ae(0.29932356550447017254j)\\n    assert f(-2.5,1,-0.5,type=3).ae(-0.3158481299074220287 - 1.9290561746445456908j)\\n    assert f(-2.5,1,0,type=3).ae(1.2708196271909686292 - 1.2708196271909686299j)\\n    assert f(-2.5,1,0.5,type=3).ae(1.9290561746445456907 + 0.3158481299074220287j)\\n    assert f(-2.5,1,1.5,type=3).ae(-0.29932356550447017254)\\n\\ndef test_agm():\\n    mp.dps = 15\\n    assert agm(0,0) == 0\\n    assert agm(0,1) == 0\\n    assert agm(1,1) == 1\\n    assert agm(7,7) == 7\\n    assert agm(j,j) == j\\n    assert (1/agm(1,sqrt(2))).ae(0.834626841674073186)\\n    assert agm(1,2).ae(1.4567910310469068692)\\n    assert agm(1,3).ae(1.8636167832448965424)\\n    assert agm(1,j).ae(0.599070117367796104+0.599070117367796104j)\\n    assert agm(2) == agm(1,2)\\n    assert agm(-3,4).ae(0.63468509766550907+1.3443087080896272j)\\n\\ndef test_gammainc():\\n    mp.dps = 15\\n    assert gammainc(2,5).ae(6*exp(-5))\\n    assert gammainc(2,0,5).ae(1-6*exp(-5))\\n    assert gammainc(2,3,5).ae(-6*exp(-5)+4*exp(-3))\\n    assert gammainc(-2.5,-0.5).ae(-0.9453087204829418812-5.3164237738936178621j)\\n    assert gammainc(0,2,4).ae(0.045121158298212213088)\\n    assert gammainc(0,3).ae(0.013048381094197037413)\\n    assert gammainc(0,2+j,1-j).ae(0.00910653685850304839-0.22378752918074432574j)\\n    assert gammainc(0,1-j).ae(0.00028162445198141833+0.17932453503935894015j)\\n    assert gammainc(3,4,5,True).ae(0.11345128607046320253)\\n    assert gammainc(3.5,0,inf).ae(gamma(3.5))\\n    assert gammainc(-150.5,500).ae('6.9825435345798951153e-627')\\n    assert gammainc(-150.5,800).ae('4.6885137549474089431e-788')\\n    assert gammainc(-3.5, -20.5).ae(0.27008820585226911 - 1310.31447140574997636j)\\n    assert gammainc(-3.5, -200.5).ae(0.27008820585226911 - 5.3264597096208368435e76j) # XXX real part\\n    assert gammainc(0,0,2) == inf\\n    assert gammainc(1,b=1).ae(0.6321205588285576784)\\n    assert gammainc(3,2,2) == 0\\n    assert gammainc(2,3+j,3-j).ae(-0.28135485191849314194j)\\n    assert gammainc(4+0j,1).ae(5.8860710587430771455)\\n    # GH issue #301\\n    assert gammainc(-1,-1).ae(-0.8231640121031084799 + 3.1415926535897932385j)\\n    assert gammainc(-2,-1).ae(1.7707229202810768576 - 1.5707963267948966192j)\\n    assert gammainc(-3,-1).ae(-1.4963349162467073643 + 0.5235987755982988731j)\\n    assert gammainc(-4,-1).ae(1.05365418617643814992 - 0.13089969389957471827j)\\n    # Regularized upper gamma\\n    assert isnan(gammainc(0, 0, regularized=True))\\n    assert gammainc(-1, 0, regularized=True) == inf\\n    assert gammainc(1, 0, regularized=True) == 1\\n    assert gammainc(0, 5, regularized=True) == 0\\n    assert gammainc(0, 2+3j, regularized=True) == 0\\n    assert gammainc(0, 5000, regularized=True) == 0\\n    assert gammainc(0, 10**30, regularized=True) == 0\\n    assert gammainc(-1, 5, regularized=True) == 0\\n    assert gammainc(-1, 5000, regularized=True) == 0\\n    assert gammainc(-1, 10**30, regularized=True) == 0\\n    assert gammainc(-1, -5, regularized=True) == 0\\n    assert gammainc(-1, -5000, regularized=True) == 0\\n    assert gammainc(-1, -10**30, regularized=True) == 0\\n    assert gammainc(-1, 3+4j, regularized=True) == 0\\n    assert gammainc(1, 5, regularized=True).ae(exp(-5))\\n    assert gammainc(1, 5000, regularized=True).ae(exp(-5000))\\n    assert gammainc(1, 10**30, regularized=True).ae(exp(-10**30))\\n    assert gammainc(1, 3+4j, regularized=True).ae(exp(-3-4j))\\n    assert gammainc(-1000000,2).ae('1.3669297209397347754e-301037', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-1000000,2,regularized=True) == 0\\n    assert gammainc(-1000000,3+4j).ae('-1.322575609404222361e-698979 - 4.9274570591854533273e-698978j', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-1000000,3+4j,regularized=True) == 0\\n    assert gammainc(2+3j, 4+5j, regularized=True).ae(0.085422013530993285774-0.052595379150390078503j)\\n    assert gammainc(1000j, 1000j, regularized=True).ae(0.49702647628921131761 + 0.00297355675013575341j)\\n    # Generalized\\n    assert gammainc(3,4,2) == -gammainc(3,2,4)\\n    assert gammainc(4, 2, 3).ae(1.2593494302978947396)\\n    assert gammainc(4, 2, 3, regularized=True).ae(0.20989157171631578993)\\n    assert gammainc(0, 2, 3).ae(0.035852129613864082155)\\n    assert gammainc(0, 2, 3, regularized=True) == 0\\n    assert gammainc(-1, 2, 3).ae(0.015219822548487616132)\\n    assert gammainc(-1, 2, 3, regularized=True) == 0\\n    assert gammainc(0, 2, 3).ae(0.035852129613864082155)\\n    assert gammainc(0, 2, 3, regularized=True) == 0\\n    # Should use upper gammas\\n    assert gammainc(5, 10000, 12000).ae('1.1359381951461801687e-4327', abs_eps=0, rel_eps=8*eps)\\n    # Should use lower gammas\\n    assert gammainc(10000, 2, 3).ae('8.1244514125995785934e4765')\\n    # GH issue 306\\n    assert gammainc(3,-1-1j) == 0\\n    assert gammainc(3,-1+1j) == 0\\n    assert gammainc(2,-1) == 0\\n    assert gammainc(2,-1+0j) == 0\\n    assert gammainc(2+0j,-1) == 0\\n\\ndef test_gammainc_expint_n():\\n    # These tests are intended to check all cases of the low-level code\\n    # for upper gamma and expint with small integer index.\\n    # Need to cover positive/negative arguments; small/large/huge arguments\\n    # for both positive and negative indices, as well as indices 0 and 1\\n    # which may be special-cased\\n    mp.dps = 15\\n    assert expint(-3,3.5).ae(0.021456366563296693987)\\n    assert expint(-2,3.5).ae(0.014966633183073309405)\\n    assert expint(-1,3.5).ae(0.011092916359219041088)\\n    assert expint(0,3.5).ae(0.0086278238349481430685)\\n    assert expint(1,3.5).ae(0.0069701398575483929193)\\n    assert expint(2,3.5).ae(0.0058018939208991255223)\\n    assert expint(3,3.5).ae(0.0049453773495857807058)\\n    assert expint(-3,-3.5).ae(-4.6618170604073311319)\\n    assert expint(-2,-3.5).ae(-5.5996974157555515963)\\n    assert expint(-1,-3.5).ae(-6.7582555017739415818)\\n    assert expint(0,-3.5).ae(-9.4615577024835182145)\\n    assert expint(1,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j)\\n    assert expint(2,-3.5).ae(-15.62328702434085977 - 10.995574287564276335j)\\n    assert expint(3,-3.5).ae(-10.783026313250347722 - 19.242255003237483586j)\\n    assert expint(-3,350).ae(2.8614825451252838069e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(-2,350).ae(2.8532837224504675901e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(-1,350).ae(2.8451316155828634555e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(0,350).ae(2.8370258275042797989e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(1,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(2,350).ae(2.8209516419468505006e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(3,350).ae(2.8129824725501272171e-155, abs_eps=0, rel_eps=8*eps)\\n    assert expint(-3,-350).ae(-2.8528796154044839443e+149)\\n    assert expint(-2,-350).ae(-2.8610072121701264351e+149)\\n    assert expint(-1,-350).ae(-2.8691813842677537647e+149)\\n    assert expint(0,-350).ae(-2.8774025343659421709e+149)\\n    u = expint(1,-350)\\n    assert u.ae(-2.8856710698020863568e+149)\\n    assert u.imag.ae(-3.1415926535897932385)\\n    u = expint(2,-350)\\n    assert u.ae(-2.8939874026504650534e+149)\\n    assert u.imag.ae(-1099.5574287564276335)\\n    u = expint(3,-350)\\n    assert u.ae(-2.9023519497915044349e+149)\\n    assert u.imag.ae(-192422.55003237483586)\\n    assert expint(-3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(-2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(-1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert expint(-3,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')\\n    assert expint(-2,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')\\n    assert expint(-1,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')\\n    assert expint(0,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')\\n    u = expint(1,-350000000000000000000000)\\n    assert u.ae('-3.7805306852415755699e+152003068666138139677871')\\n    assert u.imag.ae(-3.1415926535897932385)\\n    u = expint(2,-350000000000000000000000)\\n    assert u.imag.ae(-1.0995574287564276335e+24)\\n    assert u.ae('-3.7805306852415755699e+152003068666138139677871')\\n    u = expint(3,-350000000000000000000000)\\n    assert u.imag.ae(-1.9242255003237483586e+47)\\n    assert u.ae('-3.7805306852415755699e+152003068666138139677871')\\n    # Small case; no branch cut\\n    assert gammainc(-3,3.5).ae(0.00010020262545203707109)\\n    assert gammainc(-2,3.5).ae(0.00040370427343557393517)\\n    assert gammainc(-1,3.5).ae(0.0016576839773997501492)\\n    assert gammainc(0,3.5).ae(0.0069701398575483929193)\\n    assert gammainc(1,3.5).ae(0.03019738342231850074)\\n    assert gammainc(2,3.5).ae(0.13588822540043325333)\\n    assert gammainc(3,3.5).ae(0.64169439772426814072)\\n    # Small case; with branch cut\\n    assert gammainc(-3,-3.5).ae(0.03595832954467563286 + 0.52359877559829887308j)\\n    assert gammainc(-2,-3.5).ae(-0.88024704597962022221 - 1.5707963267948966192j)\\n    assert gammainc(-1,-3.5).ae(4.4637962926688170771 + 3.1415926535897932385j)\\n    assert gammainc(0,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j)\\n    assert gammainc(1,-3.5).ae(33.115451958692313751)\\n    assert gammainc(2,-3.5).ae(-82.788629896730784377)\\n    assert gammainc(3,-3.5).ae(240.08702670051927469)\\n    # Asymptotic case; no branch cut\\n    assert gammainc(-3,350).ae(6.5424095113340358813e-163, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-2,350).ae(2.296312222489899769e-160, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-1,350).ae(8.059861834133858573e-158, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(0,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(1,350).ae(9.9295903962649792963e-153, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(2,350).ae(3.485286229089007733e-150, abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(3,350).ae(1.2233453960006379793e-147, abs_eps=0, rel_eps=8*eps)\\n    # Asymptotic case; branch cut\\n    u = gammainc(-3,-350)\\n    assert u.ae(6.7889565783842895085e+141)\\n    assert u.imag.ae(0.52359877559829887308)\\n    u = gammainc(-2,-350)\\n    assert u.ae(-2.3692668977889832121e+144)\\n    assert u.imag.ae(-1.5707963267948966192)\\n    u = gammainc(-1,-350)\\n    assert u.ae(8.2685354361441858669e+146)\\n    assert u.imag.ae(3.1415926535897932385)\\n    u = gammainc(0,-350)\\n    assert u.ae(-2.8856710698020863568e+149)\\n    assert u.imag.ae(-3.1415926535897932385)\\n    u = gammainc(1,-350)\\n    assert u.ae(1.0070908870280797598e+152)\\n    assert u.imag == 0\\n    u = gammainc(2,-350)\\n    assert u.ae(-3.5147471957279983618e+154)\\n    assert u.imag == 0\\n    u = gammainc(3,-350)\\n    assert u.ae(1.2266568422179417091e+157)\\n    assert u.imag == 0\\n    # Extreme asymptotic case\\n    assert gammainc(-3,350000000000000000000000).ae('5.0362468738874738859e-152003068666138139677990', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-2,350000000000000000000000).ae('1.7626864058606158601e-152003068666138139677966', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(-1,350000000000000000000000).ae('6.1694024205121555102e-152003068666138139677943', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(1,350000000000000000000000).ae('7.5575179651273905e-152003068666138139677896', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(2,350000000000000000000000).ae('2.645131287794586675e-152003068666138139677872', abs_eps=0, rel_eps=8*eps)\\n    assert gammainc(3,350000000000000000000000).ae('9.2579595072810533625e-152003068666138139677849', abs_eps=0, rel_eps=8*eps)\\n    u = gammainc(-3,-350000000000000000000000)\\n    assert u.ae('8.8175642804468234866e+152003068666138139677800')\\n    assert u.imag.ae(0.52359877559829887308)\\n    u = gammainc(-2,-350000000000000000000000)\\n    assert u.ae('-3.0861474981563882203e+152003068666138139677824')\\n    assert u.imag.ae(-1.5707963267948966192)\\n    u = gammainc(-1,-350000000000000000000000)\\n    assert u.ae('1.0801516243547358771e+152003068666138139677848')\\n    assert u.imag.ae(3.1415926535897932385)\\n    u = gammainc(0,-350000000000000000000000)\\n    assert u.ae('-3.7805306852415755699e+152003068666138139677871')\\n    assert u.imag.ae(-3.1415926535897932385)\\n    assert gammainc(1,-350000000000000000000000).ae('1.3231857398345514495e+152003068666138139677895')\\n    assert gammainc(2,-350000000000000000000000).ae('-4.6311500894209300731e+152003068666138139677918')\\n    assert gammainc(3,-350000000000000000000000).ae('1.6209025312973255256e+152003068666138139677942')\\n\\ndef test_incomplete_beta():\\n    mp.dps = 15\\n    assert betainc(-2,-3,0.5,0.75).ae(63.4305673311255413583969)\\n    assert betainc(4.5,0.5+2j,2.5,6).ae(0.2628801146130621387903065 + 0.5162565234467020592855378j)\\n    assert betainc(4,5,0,6).ae(90747.77142857142857142857)\\n\\ndef test_erf():\\n    mp.dps = 15\\n    assert erf(0) == 0\\n    assert erf(1).ae(0.84270079294971486934)\\n    assert erf(3+4j).ae(-120.186991395079444098 - 27.750337293623902498j)\\n    assert erf(-4-3j).ae(-0.99991066178539168236 + 0.00004972026054496604j)\\n    assert erf(pi).ae(0.99999112385363235839)\\n    assert erf(1j).ae(1.6504257587975428760j)\\n    assert erf(-1j).ae(-1.6504257587975428760j)\\n    assert isinstance(erf(1), mpf)\\n    assert isinstance(erf(-1), mpf)\\n    assert isinstance(erf(0), mpf)\\n    assert isinstance(erf(0j), mpc)\\n    assert erf(inf) == 1\\n    assert erf(-inf) == -1\\n    assert erfi(0) == 0\\n    assert erfi(1/pi).ae(0.371682698493894314)\\n    assert erfi(inf) == inf\\n    assert erfi(-inf) == -inf\\n    assert erf(1+0j) == erf(1)\\n    assert erfc(1+0j) == erfc(1)\\n    assert erf(0.2+0.5j).ae(1 - erfc(0.2+0.5j))\\n    assert erfc(0) == 1\\n    assert erfc(1).ae(1-erf(1))\\n    assert erfc(-1).ae(1-erf(-1))\\n    assert erfc(1/pi).ae(1-erf(1/pi))\\n    assert erfc(-10) == 2\\n    assert erfc(-1000000) == 2\\n    assert erfc(-inf) == 2\\n    assert erfc(inf) == 0\\n    assert isnan(erfc(nan))\\n    assert (erfc(10**4)*mpf(10)**43429453).ae('3.63998738656420')\\n    assert erf(8+9j).ae(-1072004.2525062051158 + 364149.91954310255423j)\\n    assert erfc(8+9j).ae(1072005.2525062051158 - 364149.91954310255423j)\\n    assert erfc(-8-9j).ae(-1072003.2525062051158 + 364149.91954310255423j)\\n    mp.dps = 50\\n    # This one does not use the asymptotic series\\n    assert (erfc(10)*10**45).ae('2.0884875837625447570007862949577886115608181193212')\\n    # This one does\\n    assert (erfc(50)*10**1088).ae('2.0709207788416560484484478751657887929322509209954')\\n    mp.dps = 15\\n    assert str(erfc(10**50)) == '3.66744826532555e-4342944819032518276511289189166050822943970058036665661144537831658646492088707747292249493384317534'\\n    assert erfinv(0) == 0\\n    assert erfinv(0.5).ae(0.47693627620446987338)\\n    assert erfinv(-0.5).ae(-0.47693627620446987338)\\n    assert erfinv(1) == inf\\n    assert erfinv(-1) == -inf\\n    assert erf(erfinv(0.95)).ae(0.95)\\n    assert erf(erfinv(0.999999999995)).ae(0.999999999995)\\n    assert erf(erfinv(-0.999999999995)).ae(-0.999999999995)\\n    mp.dps = 50\\n    assert erf(erfinv('0.99999999999999999999999999999995')).ae('0.99999999999999999999999999999995')\\n    assert erf(erfinv('0.999999999999999999999999999999995')).ae('0.999999999999999999999999999999995')\\n    assert erf(erfinv('-0.999999999999999999999999999999995')).ae('-0.999999999999999999999999999999995')\\n    mp.dps = 15\\n    # Complex asymptotic expansions\\n    v = erfc(50j)\\n    assert v.real == 1\\n    assert v.imag.ae('-6.1481820666053078736e+1083')\\n    assert erfc(-100+5j).ae(2)\\n    assert (erfc(100+5j)*10**4335).ae(2.3973567853824133572 - 3.9339259530609420597j)\\n    assert erfc(100+100j).ae(0.00065234366376857698698 - 0.0039357263629214118437j)\\n\\ndef test_pdf():\\n    mp.dps = 15\\n    assert npdf(-inf) == 0\\n    assert npdf(inf) == 0\\n    assert npdf(5,0,2).ae(npdf(5+4,4,2))\\n    assert quadts(lambda x: npdf(x,-0.5,0.8), [-inf, inf]) == 1\\n    assert ncdf(0) == 0.5\\n    assert ncdf(3,3) == 0.5\\n    assert ncdf(-inf) == 0\\n    assert ncdf(inf) == 1\\n    assert ncdf(10) == 1\\n    # Verify that this is computed accurately\\n    assert (ncdf(-10)*10**24).ae(7.619853024160526)\\n\\ndef test_lambertw():\\n    mp.dps = 15\\n    assert lambertw(0) == 0\\n    assert lambertw(0+0j) == 0\\n    assert lambertw(inf) == inf\\n    assert isnan(lambertw(nan))\\n    assert lambertw(inf,1).real == inf\\n    assert lambertw(inf,1).imag.ae(2*pi)\\n    assert lambertw(-inf,1).real == inf\\n    assert lambertw(-inf,1).imag.ae(3*pi)\\n    assert lambertw(0,-1) == -inf\\n    assert lambertw(0,1) == -inf\\n    assert lambertw(0,3) == -inf\\n    assert lambertw(e).ae(1)\\n    assert lambertw(1).ae(0.567143290409783873)\\n    assert lambertw(-pi/2).ae(j*pi/2)\\n    assert lambertw(-log(2)/2).ae(-log(2))\\n    assert lambertw(0.25).ae(0.203888354702240164)\\n    assert lambertw(-0.25).ae(-0.357402956181388903)\\n    assert lambertw(-1./10000,0).ae(-0.000100010001500266719)\\n    assert lambertw(-0.25,-1).ae(-2.15329236411034965)\\n    assert lambertw(0.25,-1).ae(-3.00899800997004620-4.07652978899159763j)\\n    assert lambertw(-0.25,-1).ae(-2.15329236411034965)\\n    assert lambertw(0.25,1).ae(-3.00899800997004620+4.07652978899159763j)\\n    assert lambertw(-0.25,1).ae(-3.48973228422959210+7.41405453009603664j)\\n    assert lambertw(-4).ae(0.67881197132094523+1.91195078174339937j)\\n    assert lambertw(-4,1).ae(-0.66743107129800988+7.76827456802783084j)\\n    assert lambertw(-4,-1).ae(0.67881197132094523-1.91195078174339937j)\\n    assert lambertw(1000).ae(5.24960285240159623)\\n    assert lambertw(1000,1).ae(4.91492239981054535+5.44652615979447070j)\\n    assert lambertw(1000,-1).ae(4.91492239981054535-5.44652615979447070j)\\n    assert lambertw(1000,5).ae(3.5010625305312892+29.9614548941181328j)\\n    assert lambertw(3+4j).ae(1.281561806123775878+0.533095222020971071j)\\n    assert lambertw(-0.4+0.4j).ae(-0.10396515323290657+0.61899273315171632j)\\n    assert lambertw(3+4j,1).ae(-0.11691092896595324+5.61888039871282334j)\\n    assert lambertw(3+4j,-1).ae(0.25856740686699742-3.85211668616143559j)\\n    assert lambertw(-0.5,-1).ae(-0.794023632344689368-0.770111750510379110j)\\n    assert lambertw(-1./10000,1).ae(-11.82350837248724344+6.80546081842002101j)\\n    assert lambertw(-1./10000,-1).ae(-11.6671145325663544)\\n    assert lambertw(-1./10000,-2).ae(-11.82350837248724344-6.80546081842002101j)\\n    assert lambertw(-1./100000,4).ae(-14.9186890769540539+26.1856750178782046j)\\n    assert lambertw(-1./100000,5).ae(-15.0931437726379218666+32.5525721210262290086j)\\n    assert lambertw((2+j)/10).ae(0.173704503762911669+0.071781336752835511j)\\n    assert lambertw((2+j)/10,1).ae(-3.21746028349820063+4.56175438896292539j)\\n    assert lambertw((2+j)/10,-1).ae(-3.03781405002993088-3.53946629633505737j)\\n    assert lambertw((2+j)/10,4).ae(-4.6878509692773249+23.8313630697683291j)\\n    assert lambertw(-(2+j)/10).ae(-0.226933772515757933-0.164986470020154580j)\\n    assert lambertw(-(2+j)/10,1).ae(-2.43569517046110001+0.76974067544756289j)\\n    assert lambertw(-(2+j)/10,-1).ae(-3.54858738151989450-6.91627921869943589j)\\n    assert lambertw(-(2+j)/10,4).ae(-4.5500846928118151+20.6672982215434637j)\\n    mp.dps = 50\\n    assert lambertw(pi).ae('1.073658194796149172092178407024821347547745350410314531')\\n    mp.dps = 15\\n    # Former bug in generated branch\\n    assert lambertw(-0.5+0.002j).ae(-0.78917138132659918344 + 0.76743539379990327749j)\\n    assert lambertw(-0.5-0.002j).ae(-0.78917138132659918344 - 0.76743539379990327749j)\\n    assert lambertw(-0.448+0.4j).ae(-0.11855133765652382241 + 0.66570534313583423116j)\\n    assert lambertw(-0.448-0.4j).ae(-0.11855133765652382241 - 0.66570534313583423116j)\\n    assert lambertw(-0.65475+0.0001j).ae(-0.61053421111385310898+1.0396534993944097723803j)\\n    # Huge branch index\\n    w = lambertw(1,10**20)\\n    assert w.real.ae(-47.889578926290259164)\\n    assert w.imag.ae(6.2831853071795864769e+20)\\n\\ndef test_lambertw_hard():\\n    def check(x,y):\\n        y = convert(y)\\n        type_ok = True\\n        if isinstance(y, mpf):\\n            type_ok = isinstance(x, mpf)\\n        real_ok = abs(x.real-y.real) <= abs(y.real)*8*eps\\n        imag_ok = abs(x.imag-y.imag) <= abs(y.imag)*8*eps\\n        #print x, y, abs(x.real-y.real), abs(x.imag-y.imag)\\n        return real_ok and imag_ok\\n    # Evaluation near 0\\n    mp.dps = 15\\n    assert check(lambertw(1e-10), 9.999999999000000000e-11)\\n    assert check(lambertw(-1e-10), -1.000000000100000000e-10)\\n    assert check(lambertw(1e-10j), 9.999999999999999999733e-21 + 9.99999999999999999985e-11j)\\n    assert check(lambertw(-1e-10j), 9.999999999999999999733e-21 - 9.99999999999999999985e-11j)\\n    assert check(lambertw(1e-10,1), -26.303186778379041559 + 3.265093911703828397j)\\n    assert check(lambertw(-1e-10,1), -26.326236166739163892 + 6.526183280686333315j)\\n    assert check(lambertw(1e-10j,1), -26.312931726911421551 + 4.896366881798013421j)\\n    assert check(lambertw(-1e-10j,1), -26.297238779529035066 + 1.632807161345576513j)\\n    assert check(lambertw(1e-10,-1), -26.303186778379041559 - 3.265093911703828397j)\\n    assert check(lambertw(-1e-10,-1), -26.295238819246925694)\\n    assert check(lambertw(1e-10j,-1), -26.297238779529035028 - 1.6328071613455765135j)\\n    assert check(lambertw(-1e-10j,-1), -26.312931726911421551 - 4.896366881798013421j)\\n    # Test evaluation very close to the branch point -1/e\\n    # on the -1, 0, and 1 branches\\n    add = lambda x, y: fadd(x,y,exact=True)\\n    sub = lambda x, y: fsub(x,y,exact=True)\\n    addj = lambda x, y: fadd(x,fmul(y,1j,exact=True),exact=True)\\n    subj = lambda x, y: fadd(x,fmul(y,-1j,exact=True),exact=True)\\n    mp.dps = 1500\\n    a = -1/e + 10*eps\\n    d3 = mpf('1e-3')\\n    d10 = mpf('1e-10')\\n    d20 = mpf('1e-20')\\n    d40 = mpf('1e-40')\\n    d80 = mpf('1e-80')\\n    d300 = mpf('1e-300')\\n    d1000 = mpf('1e-1000')\\n    mp.dps = 15\\n    # ---- Branch 0 ----\\n    # -1/e + eps\\n    assert check(lambertw(add(a,d3)), -0.92802015005456704876)\\n    assert check(lambertw(add(a,d10)), -0.99997668374140088071)\\n    assert check(lambertw(add(a,d20)), -0.99999999976683560186)\\n    assert lambertw(add(a,d40)) == -1\\n    assert lambertw(add(a,d80)) == -1\\n    assert lambertw(add(a,d300)) == -1\\n    assert lambertw(add(a,d1000)) == -1\\n    # -1/e - eps\\n    assert check(lambertw(sub(a,d3)), -0.99819016149860989001+0.07367191188934638577j)\\n    assert check(lambertw(sub(a,d10)), -0.9999999998187812114595992+0.0000233164398140346109194j)\\n    assert check(lambertw(sub(a,d20)), -0.99999999999999999998187+2.331643981597124203344e-10j)\\n    assert check(lambertw(sub(a,d40)), -1.0+2.33164398159712420336e-20j)\\n    assert check(lambertw(sub(a,d80)), -1.0+2.33164398159712420336e-40j)\\n    assert check(lambertw(sub(a,d300)), -1.0+2.33164398159712420336e-150j)\\n    assert check(lambertw(sub(a,d1000)), mpc(-1,'2.33164398159712420336e-500'))\\n    # -1/e + eps*j\\n    assert check(lambertw(addj(a,d3)), -0.94790387486938526634+0.05036819639190132490j)\\n    assert check(lambertw(addj(a,d10)), -0.9999835127872943680999899+0.0000164870314895821225256j)\\n    assert check(lambertw(addj(a,d20)), -0.999999999835127872929987+1.64872127051890935830e-10j)\\n    assert check(lambertw(addj(a,d40)), -0.9999999999999999999835+1.6487212707001281468305e-20j)\\n    assert check(lambertw(addj(a,d80)), -1.0 + 1.64872127070012814684865e-40j)\\n    assert check(lambertw(addj(a,d300)), -1.0 + 1.64872127070012814684865e-150j)\\n    assert check(lambertw(addj(a,d1000)), mpc(-1.0,'1.64872127070012814684865e-500'))\\n    # -1/e - eps*j\\n    assert check(lambertw(subj(a,d3)), -0.94790387486938526634-0.05036819639190132490j)\\n    assert check(lambertw(subj(a,d10)), -0.9999835127872943680999899-0.0000164870314895821225256j)\\n    assert check(lambertw(subj(a,d20)), -0.999999999835127872929987-1.64872127051890935830e-10j)\\n    assert check(lambertw(subj(a,d40)), -0.9999999999999999999835-1.6487212707001281468305e-20j)\\n    assert check(lambertw(subj(a,d80)), -1.0 - 1.64872127070012814684865e-40j)\\n    assert check(lambertw(subj(a,d300)), -1.0 - 1.64872127070012814684865e-150j)\\n    assert check(lambertw(subj(a,d1000)), mpc(-1.0,'-1.64872127070012814684865e-500'))\\n    # ---- Branch 1 ----\\n    assert check(lambertw(addj(a,d3),1), -3.088501303219933378005990 + 7.458676867597474813950098j)\\n    assert check(lambertw(addj(a,d80),1), -3.088843015613043855957087 + 7.461489285654254556906117j)\\n    assert check(lambertw(addj(a,d300),1), -3.088843015613043855957087 + 7.461489285654254556906117j)\\n    assert check(lambertw(addj(a,d1000),1), -3.088843015613043855957087 + 7.461489285654254556906117j)\\n    assert check(lambertw(subj(a,d3),1), -1.0520914180450129534365906 + 0.0539925638125450525673175j)\\n    assert check(lambertw(subj(a,d10),1), -1.0000164872127056318529390 + 0.000016487393927159250398333077j)\\n    assert check(lambertw(subj(a,d20),1), -1.0000000001648721270700128 + 1.64872127088134693542628e-10j)\\n    assert check(lambertw(subj(a,d40),1), -1.000000000000000000016487 + 1.64872127070012814686677e-20j)\\n    assert check(lambertw(subj(a,d80),1), -1.0 + 1.64872127070012814684865e-40j)\\n    assert check(lambertw(subj(a,d300),1), -1.0 + 1.64872127070012814684865e-150j)\\n    assert check(lambertw(subj(a,d1000),1), mpc(-1.0, '1.64872127070012814684865e-500'))\\n    # ---- Branch -1 ----\\n    # -1/e + eps\\n    assert check(lambertw(add(a,d3),-1), -1.075608941186624989414945)\\n    assert check(lambertw(add(a,d10),-1), -1.000023316621036696460620)\\n    assert check(lambertw(add(a,d20),-1), -1.000000000233164398177834)\\n    assert lambertw(add(a,d40),-1) == -1\\n    assert lambertw(add(a,d80),-1) == -1\\n    assert lambertw(add(a,d300),-1) == -1\\n    assert lambertw(add(a,d1000),-1) == -1\\n    # -1/e - eps\\n    assert check(lambertw(sub(a,d3),-1), -0.99819016149860989001-0.07367191188934638577j)\\n    assert check(lambertw(sub(a,d10),-1), -0.9999999998187812114595992-0.0000233164398140346109194j)\\n    assert check(lambertw(sub(a,d20),-1), -0.99999999999999999998187-2.331643981597124203344e-10j)\\n    assert check(lambertw(sub(a,d40),-1), -1.0-2.33164398159712420336e-20j)\\n    assert check(lambertw(sub(a,d80),-1), -1.0-2.33164398159712420336e-40j)\\n    assert check(lambertw(sub(a,d300),-1), -1.0-2.33164398159712420336e-150j)\\n    assert check(lambertw(sub(a,d1000),-1), mpc(-1,'-2.33164398159712420336e-500'))\\n    # -1/e + eps*j\\n    assert check(lambertw(addj(a,d3),-1), -1.0520914180450129534365906 - 0.0539925638125450525673175j)\\n    assert check(lambertw(addj(a,d10),-1), -1.0000164872127056318529390 - 0.0000164873939271592503983j)\\n    assert check(lambertw(addj(a,d20),-1), -1.0000000001648721270700 - 1.64872127088134693542628e-10j)\\n    assert check(lambertw(addj(a,d40),-1), -1.00000000000000000001648 - 1.6487212707001281468667726e-20j)\\n    assert check(lambertw(addj(a,d80),-1), -1.0 - 1.64872127070012814684865e-40j)\\n    assert check(lambertw(addj(a,d300),-1), -1.0 - 1.64872127070012814684865e-150j)\\n    assert check(lambertw(addj(a,d1000),-1), mpc(-1.0,'-1.64872127070012814684865e-500'))\\n    # -1/e - eps*j\\n    assert check(lambertw(subj(a,d3),-1), -3.088501303219933378005990-7.458676867597474813950098j)\\n    assert check(lambertw(subj(a,d10),-1), -3.088843015579260686911033-7.461489285372968780020716j)\\n    assert check(lambertw(subj(a,d20),-1), -3.088843015613043855953708-7.461489285654254556877988j)\\n    assert check(lambertw(subj(a,d40),-1), -3.088843015613043855957087-7.461489285654254556906117j)\\n    assert check(lambertw(subj(a,d80),-1), -3.088843015613043855957087 - 7.461489285654254556906117j)\\n    assert check(lambertw(subj(a,d300),-1), -3.088843015613043855957087 - 7.461489285654254556906117j)\\n    assert check(lambertw(subj(a,d1000),-1), -3.088843015613043855957087 - 7.461489285654254556906117j)\\n    # One more case, testing higher precision\\n    mp.dps = 500\\n    x = -1/e + mpf('1e-13')\\n    ans = \\\"-0.99999926266961377166355784455394913638782494543377383\\\"\\\\\\n    \\\"744978844374498153493943725364881490261187530235150668593869563\\\"\\\\\\n    \\\"168276697689459394902153960200361935311512317183678882\\\"\\n    mp.dps = 15\\n    assert lambertw(x).ae(ans)\\n    mp.dps = 50\\n    assert lambertw(x).ae(ans)\\n    mp.dps = 150\\n    assert lambertw(x).ae(ans)\\n\\ndef test_meijerg():\\n    mp.dps = 15\\n    assert meijerg([[2,3],[1]],[[0.5,2],[3,4]], 2.5).ae(4.2181028074787439386)\\n    assert meijerg([[],[1+j]],[[1],[1]], 3+4j).ae(271.46290321152464592 - 703.03330399954820169j)\\n    assert meijerg([[0.25],[1]],[[0.5],[2]],0) == 0\\n    assert meijerg([[0],[]],[[0,0,'1/3','2/3'], []], '2/27').ae(2.2019391389653314120)\\n    # Verify 1/z series being used\\n    assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -0.5).ae(-1.338096165935754898687431)\\n    assert meijerg([[1-(-1)],[1-(-2.5)]], [[1-(-3)],[1-(-0.5)]], -2.0).ae(-1.338096165935754898687431)\\n    assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -1).ae(-(pi+4)/(4*pi))\\n    a = 2.5\\n    b = 1.25\\n    for z in [mpf(0.25), mpf(2)]:\\n        x1 = hyp1f1(a,b,z)\\n        x2 = gamma(b)/gamma(a)*meijerg([[1-a],[]],[[0],[1-b]],-z)\\n        x3 = gamma(b)/gamma(a)*meijerg([[1-0],[1-(1-b)]],[[1-(1-a)],[]],-1/z)\\n        assert x1.ae(x2)\\n        assert x1.ae(x3)\\n\\ndef test_appellf1():\\n    mp.dps = 15\\n    assert appellf1(2,-2,1,1,2,3).ae(-1.75)\\n    assert appellf1(2,1,-2,1,2,3).ae(-8)\\n    assert appellf1(2,1,-2,1,0.5,0.25).ae(1.5)\\n    assert appellf1(-2,1,3,2,3,3).ae(19)\\n    assert appellf1(1,2,3,4,0.5,0.125).ae( 1.53843285792549786518)\\n\\ndef test_coulomb():\\n    # Note: most tests are doctests\\n    # Test for a bug:\\n    mp.dps = 15\\n    assert coulombg(mpc(-5,0),2,3).ae(20.087729487721430394)\\n\\ndef test_hyper_param_accuracy():\\n    mp.dps = 15\\n    As = [n+1e-10 for n in range(-5,-1)]\\n    Bs = [n+1e-10 for n in range(-12,-5)]\\n    assert hyper(As,Bs,10).ae(-381757055858.652671927)\\n    assert legenp(0.5, 100, 0.25).ae(-2.4124576567211311755e+144)\\n    assert (hyp1f1(1000,1,-100)*10**24).ae(5.2589445437370169113)\\n    assert (hyp2f1(10, -900, 10.5, 0.99)*10**24).ae(1.9185370579660768203)\\n    assert (hyp2f1(1000,1.5,-3.5,-1.5)*10**385).ae(-2.7367529051334000764)\\n    assert hyp2f1(-5, 10, 3, 0.5, zeroprec=500) == 0\\n    assert (hyp1f1(-10000, 1000, 100)*10**424).ae(-3.1046080515824859974)\\n    assert (hyp2f1(1000,1.5,-3.5,-0.75,maxterms=100000)*10**231).ae(-4.0534790813913998643)\\n    assert legenp(2, 3, 0.25) == 0\\n    pytest.raises(ValueError, lambda: hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3]))\\n    assert hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3], infprec=200) == inf\\n    assert meijerg([[],[]],[[0,0,0,0],[]],0.1).ae(1.5680822343832351418)\\n    assert (besselk(400,400)*10**94).ae(1.4387057277018550583)\\n    mp.dps = 5\\n    (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522)\\n    (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311)\\n    mp.dps = 15\\n    (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522)\\n    (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311)\\n    assert hyp0f1(fadd(-20,'1e-100',exact=True), 0.25).ae(1.85014429040102783e+49)\\n    assert hyp0f1((-20*10**100+1, 10**100), 0.25).ae(1.85014429040102783e+49)\\n\\ndef test_hypercomb_zero_pow():\\n    # check that 0^0 = 1\\n    assert hypercomb(lambda a: (([0],[a],[],[],[],[],0),), [0]) == 1\\n    assert meijerg([[-1.5],[]],[[0],[-0.75]],0).ae(1.4464090846320771425)\\n\\ndef test_spherharm():\\n    mp.dps = 15\\n    t = 0.5; r = 0.25\\n    assert spherharm(0,0,t,r).ae(0.28209479177387814347)\\n    assert spherharm(1,-1,t,r).ae(0.16048941205971996369 - 0.04097967481096344271j)\\n    assert spherharm(1,0,t,r).ae(0.42878904414183579379)\\n    assert spherharm(1,1,t,r).ae(-0.16048941205971996369 - 0.04097967481096344271j)\\n    assert spherharm(2,-2,t,r).ae(0.077915886919031181734 - 0.042565643022253962264j)\\n    assert spherharm(2,-1,t,r).ae(0.31493387233497459884 - 0.08041582001959297689j)\\n    assert spherharm(2,0,t,r).ae(0.41330596756220761898)\\n    assert spherharm(2,1,t,r).ae(-0.31493387233497459884 - 0.08041582001959297689j)\\n    assert spherharm(2,2,t,r).ae(0.077915886919031181734 + 0.042565643022253962264j)\\n    assert spherharm(3,-3,t,r).ae(0.033640236589690881646 - 0.031339125318637082197j)\\n    assert spherharm(3,-2,t,r).ae(0.18091018743101461963 - 0.09883168583167010241j)\\n    assert spherharm(3,-1,t,r).ae(0.42796713930907320351 - 0.10927795157064962317j)\\n    assert spherharm(3,0,t,r).ae(0.27861659336351639787)\\n    assert spherharm(3,1,t,r).ae(-0.42796713930907320351 - 0.10927795157064962317j)\\n    assert spherharm(3,2,t,r).ae(0.18091018743101461963 + 0.09883168583167010241j)\\n    assert spherharm(3,3,t,r).ae(-0.033640236589690881646 - 0.031339125318637082197j)\\n    assert spherharm(0,-1,t,r) == 0\\n    assert spherharm(0,-2,t,r) == 0\\n    assert spherharm(0,1,t,r) == 0\\n    assert spherharm(0,2,t,r) == 0\\n    assert spherharm(1,2,t,r) == 0\\n    assert spherharm(1,3,t,r) == 0\\n    assert spherharm(1,-2,t,r) == 0\\n    assert spherharm(1,-3,t,r) == 0\\n    assert spherharm(2,3,t,r) == 0\\n    assert spherharm(2,4,t,r) == 0\\n    assert spherharm(2,-3,t,r) == 0\\n    assert spherharm(2,-4,t,r) == 0\\n    assert spherharm(3,4.5,0.5,0.25).ae(-22.831053442240790148 + 10.910526059510013757j)\\n    assert spherharm(2+3j, 1-j, 1+j, 3+4j).ae(-2.6582752037810116935 - 1.0909214905642160211j)\\n    assert spherharm(-6,2.5,t,r).ae(0.39383644983851448178 + 0.28414687085358299021j)\\n    assert spherharm(-3.5, 3, 0.5, 0.25).ae(0.014516852987544698924 - 0.015582769591477628495j)\\n    assert spherharm(-3, 3, 0.5, 0.25) == 0\\n    assert spherharm(-6, 3, 0.5, 0.25).ae(-0.16544349818782275459 - 0.15412657723253924562j)\\n    assert spherharm(-6, 1.5, 0.5, 0.25).ae(0.032208193499767402477 + 0.012678000924063664921j)\\n    assert spherharm(3,0,0,1).ae(0.74635266518023078283)\\n    assert spherharm(3,-2,0,1) == 0\\n    assert spherharm(3,-2,1,1).ae(-0.16270707338254028971 - 0.35552144137546777097j)\\n\\ndef test_qfunctions():\\n    mp.dps = 15\\n    assert qp(2,3,100).ae('2.7291482267247332183e2391')\\n\\ndef test_issue_239():\\n    mp.prec = 150\\n    x = ldexp(2476979795053773,-52)\\n    assert betainc(206, 385, 0, 0.55, 1).ae('0.99999999999999999999996570910644857895771110649954')\\n    mp.dps = 15\\n    pytest.raises(ValueError, lambda: hyp2f1(-5,5,0.5,0.5))\\n\\n# Extra stress testing for Bessel functions\\n# Reference zeros generated with the aid of scipy.special\\n# jn_zero, jnp_zero, yn_zero, ynp_zero\\n\\nV = 15\\nM = 15\\n\\njn_small_zeros = \\\\\\n[[2.4048255576957728,\\n  5.5200781102863106,\\n  8.6537279129110122,\\n  11.791534439014282,\\n  14.930917708487786,\\n  18.071063967910923,\\n  21.211636629879259,\\n  24.352471530749303,\\n  27.493479132040255,\\n  30.634606468431975,\\n  33.775820213573569,\\n  36.917098353664044,\\n  40.058425764628239,\\n  43.19979171317673,\\n  46.341188371661814],\\n [3.8317059702075123,\\n  7.0155866698156188,\\n  10.173468135062722,\\n  13.323691936314223,\\n  16.470630050877633,\\n  19.615858510468242,\\n  22.760084380592772,\\n  25.903672087618383,\\n  29.046828534916855,\\n  32.189679910974404,\\n  35.332307550083865,\\n  38.474766234771615,\\n  41.617094212814451,\\n  44.759318997652822,\\n  47.901460887185447],\\n [5.1356223018406826,\\n  8.4172441403998649,\\n  11.619841172149059,\\n  14.795951782351261,\\n  17.959819494987826,\\n  21.116997053021846,\\n  24.270112313573103,\\n  27.420573549984557,\\n  30.569204495516397,\\n  33.7165195092227,\\n  36.86285651128381,\\n  40.008446733478192,\\n  43.153453778371463,\\n  46.297996677236919,\\n  49.442164110416873],\\n [6.3801618959239835,\\n  9.7610231299816697,\\n  13.015200721698434,\\n  16.223466160318768,\\n  19.409415226435012,\\n  22.582729593104442,\\n  25.748166699294978,\\n  28.908350780921758,\\n  32.064852407097709,\\n  35.218670738610115,\\n  38.370472434756944,\\n  41.520719670406776,\\n  44.669743116617253,\\n  47.817785691533302,\\n  50.965029906205183],\\n [7.5883424345038044,\\n  11.064709488501185,\\n  14.37253667161759,\\n  17.615966049804833,\\n  20.826932956962388,\\n  24.01901952477111,\\n  27.199087765981251,\\n  30.371007667117247,\\n  33.537137711819223,\\n  36.699001128744649,\\n  39.857627302180889,\\n  43.01373772335443,\\n  46.167853512924375,\\n  49.320360686390272,\\n  52.471551398458023],\\n [8.771483815959954,\\n  12.338604197466944,\\n  15.700174079711671,\\n  18.980133875179921,\\n  22.217799896561268,\\n  25.430341154222704,\\n  28.626618307291138,\\n  31.811716724047763,\\n  34.988781294559295,\\n  38.159868561967132,\\n  41.326383254047406,\\n  44.489319123219673,\\n  47.649399806697054,\\n  50.80716520300633,\\n  53.963026558378149],\\n [9.9361095242176849,\\n  13.589290170541217,\\n  17.003819667816014,\\n  20.320789213566506,\\n  23.58608443558139,\\n  26.820151983411405,\\n  30.033722386570469,\\n  33.233041762847123,\\n  36.422019668258457,\\n  39.603239416075404,\\n  42.778481613199507,\\n  45.949015998042603,\\n  49.11577372476426,\\n  52.279453903601052,\\n  55.440592068853149],\\n [11.086370019245084,\\n  14.821268727013171,\\n  18.287582832481726,\\n  21.641541019848401,\\n  24.934927887673022,\\n  28.191188459483199,\\n  31.42279419226558,\\n  34.637089352069324,\\n  37.838717382853611,\\n  41.030773691585537,\\n  44.21540850526126,\\n  47.394165755570512,\\n  50.568184679795566,\\n  53.738325371963291,\\n  56.905249991978781],\\n [12.225092264004655,\\n  16.037774190887709,\\n  19.554536430997055,\\n  22.94517313187462,\\n  26.266814641176644,\\n  29.54565967099855,\\n  32.795800037341462,\\n  36.025615063869571,\\n  39.240447995178135,\\n  42.443887743273558,\\n  45.638444182199141,\\n  48.825930381553857,\\n  52.007691456686903,\\n  55.184747939289049,\\n  58.357889025269694],\\n [13.354300477435331,\\n  17.241220382489128,\\n  20.807047789264107,\\n  24.233885257750552,\\n  27.583748963573006,\\n  30.885378967696675,\\n  34.154377923855096,\\n  37.400099977156589,\\n  40.628553718964528,\\n  43.843801420337347,\\n  47.048700737654032,\\n  50.245326955305383,\\n  53.435227157042058,\\n  56.619580266508436,\\n  59.799301630960228],\\n [14.475500686554541,\\n  18.433463666966583,\\n  22.046985364697802,\\n  25.509450554182826,\\n  28.887375063530457,\\n  32.211856199712731,\\n  35.499909205373851,\\n  38.761807017881651,\\n  42.004190236671805,\\n  45.231574103535045,\\n  48.447151387269394,\\n  51.653251668165858,\\n  54.851619075963349,\\n  58.043587928232478,\\n  61.230197977292681],\\n [15.589847884455485,\\n  19.61596690396692,\\n  23.275853726263409,\\n  26.773322545509539,\\n  30.17906117878486,\\n  33.526364075588624,\\n  36.833571341894905,\\n  40.111823270954241,\\n  43.368360947521711,\\n  46.608132676274944,\\n  49.834653510396724,\\n  53.050498959135054,\\n  56.257604715114484,\\n  59.457456908388002,\\n  62.651217388202912],\\n [16.698249933848246,\\n  20.789906360078443,\\n  24.494885043881354,\\n  28.026709949973129,\\n  31.45996003531804,\\n  34.829986990290238,\\n  38.156377504681354,\\n  41.451092307939681,\\n  44.721943543191147,\\n  47.974293531269048,\\n  51.211967004101068,\\n  54.437776928325074,\\n  57.653844811906946,\\n  60.8618046824805,\\n  64.062937824850136],\\n [17.801435153282442,\\n  21.95624406783631,\\n  25.705103053924724,\\n  29.270630441874802,\\n  32.731053310978403,\\n  36.123657666448762,\\n  39.469206825243883,\\n  42.780439265447158,\\n  46.06571091157561,\\n  49.330780096443524,\\n  52.579769064383396,\\n  55.815719876305778,\\n  59.040934037249271,\\n  62.257189393731728,\\n  65.465883797232125],\\n [18.899997953174024,\\n  23.115778347252756,\\n  26.907368976182104,\\n  30.505950163896036,\\n  33.993184984781542,\\n  37.408185128639695,\\n  40.772827853501868,\\n  44.100590565798301,\\n  47.400347780543231,\\n  50.678236946479898,\\n  53.93866620912693,\\n  57.184898598119301,\\n  60.419409852130297,\\n  63.644117508962281,\\n  66.860533012260103]]\\n\\njnp_small_zeros = \\\\\\n[[0.0,\\n  3.8317059702075123,\\n  7.0155866698156188,\\n  10.173468135062722,\\n  13.323691936314223,\\n  16.470630050877633,\\n  19.615858510468242,\\n  22.760084380592772,\\n  25.903672087618383,\\n  29.046828534916855,\\n  32.189679910974404,\\n  35.332307550083865,\\n  38.474766234771615,\\n  41.617094212814451,\\n  44.759318997652822],\\n [1.8411837813406593,\\n  5.3314427735250326,\\n  8.5363163663462858,\\n  11.706004902592064,\\n  14.863588633909033,\\n  18.015527862681804,\\n  21.16436985918879,\\n  24.311326857210776,\\n  27.457050571059246,\\n  30.601922972669094,\\n  33.746182898667383,\\n  36.889987409236811,\\n  40.033444053350675,\\n  43.176628965448822,\\n  46.319597561173912],\\n [3.0542369282271403,\\n  6.7061331941584591,\\n  9.9694678230875958,\\n  13.170370856016123,\\n  16.347522318321783,\\n  19.512912782488205,\\n  22.671581772477426,\\n  25.826037141785263,\\n  28.977672772993679,\\n  32.127327020443474,\\n  35.275535050674691,\\n  38.422654817555906,\\n  41.568934936074314,\\n  44.714553532819734,\\n  47.859641607992093],\\n [4.2011889412105285,\\n  8.0152365983759522,\\n  11.345924310743006,\\n  14.585848286167028,\\n  17.78874786606647,\\n  20.9724769365377,\\n  24.144897432909265,\\n  27.310057930204349,\\n  30.470268806290424,\\n  33.626949182796679,\\n  36.781020675464386,\\n  39.933108623659488,\\n  43.083652662375079,\\n  46.232971081836478,\\n  49.381300092370349],\\n [5.3175531260839944,\\n  9.2823962852416123,\\n  12.681908442638891,\\n  15.964107037731551,\\n  19.196028800048905,\\n  22.401032267689004,\\n  25.589759681386733,\\n  28.767836217666503,\\n  31.938539340972783,\\n  35.103916677346764,\\n  38.265316987088158,\\n  41.423666498500732,\\n  44.579623137359257,\\n  47.733667523865744,\\n  50.886159153182682],\\n [6.4156163757002403,\\n  10.519860873772308,\\n  13.9871886301403,\\n  17.312842487884625,\\n  20.575514521386888,\\n  23.803581476593863,\\n  27.01030789777772,\\n  30.20284907898166,\\n  33.385443901010121,\\n  36.560777686880356,\\n  39.730640230067416,\\n  42.896273163494417,\\n  46.058566273567043,\\n  49.218174614666636,\\n  52.375591529563596],\\n [7.501266144684147,\\n  11.734935953042708,\\n  15.268181461097873,\\n  18.637443009666202,\\n  21.931715017802236,\\n  25.183925599499626,\\n  28.409776362510085,\\n  31.617875716105035,\\n  34.81339298429743,\\n  37.999640897715301,\\n  41.178849474321413,\\n  44.352579199070217,\\n  47.521956905768113,\\n  50.687817781723741,\\n  53.85079463676896],\\n [8.5778364897140741,\\n  12.932386237089576,\\n  16.529365884366944,\\n  19.941853366527342,\\n  23.268052926457571,\\n  26.545032061823576,\\n  29.790748583196614,\\n  33.015178641375142,\\n  36.224380548787162,\\n  39.422274578939259,\\n  42.611522172286684,\\n  45.793999658055002,\\n  48.971070951900596,\\n  52.143752969301988,\\n  55.312820330403446],\\n [9.6474216519972168,\\n  14.115518907894618,\\n  17.774012366915256,\\n  21.229062622853124,\\n  24.587197486317681,\\n  27.889269427955092,\\n  31.155326556188325,\\n  34.39662855427218,\\n  37.620078044197086,\\n  40.830178681822041,\\n  44.030010337966153,\\n  47.221758471887113,\\n  50.407020967034367,\\n  53.586995435398319,\\n  56.762598475105272],\\n [10.711433970699945,\\n  15.28673766733295,\\n  19.004593537946053,\\n  22.501398726777283,\\n  25.891277276839136,\\n  29.218563499936081,\\n  32.505247352375523,\\n  35.763792928808799,\\n  39.001902811514218,\\n  42.224638430753279,\\n  45.435483097475542,\\n  48.636922645305525,\\n  51.830783925834728,\\n  55.01844255063594,\\n  58.200955824859509],\\n [11.770876674955582,\\n  16.447852748486498,\\n  20.223031412681701,\\n  23.760715860327448,\\n  27.182021527190532,\\n  30.534504754007074,\\n  33.841965775135715,\\n  37.118000423665604,\\n  40.371068905333891,\\n  43.606764901379516,\\n  46.828959446564562,\\n  50.040428970943456,\\n  53.243223214220535,\\n  56.438892058982552,\\n  59.628631306921512],\\n [12.826491228033465,\\n  17.600266557468326,\\n  21.430854238060294,\\n  25.008518704644261,\\n  28.460857279654847,\\n  31.838424458616998,\\n  35.166714427392629,\\n  38.460388720328256,\\n  41.728625562624312,\\n  44.977526250903469,\\n  48.211333836373288,\\n  51.433105171422278,\\n  54.645106240447105,\\n  57.849056857839799,\\n  61.046288512821078],\\n [13.878843069697276,\\n  18.745090916814406,\\n  22.629300302835503,\\n  26.246047773946584,\\n  29.72897816891134,\\n  33.131449953571661,\\n  36.480548302231658,\\n  39.791940718940855,\\n  43.075486800191012,\\n  46.337772104541405,\\n  49.583396417633095,\\n  52.815686826850452,\\n  56.037118687012179,\\n  59.249577075517968,\\n  62.454525995970462],\\n [14.928374492964716,\\n  19.88322436109951,\\n  23.81938909003628,\\n  27.474339750968247,\\n  30.987394331665278,\\n  34.414545662167183,\\n  37.784378506209499,\\n  41.113512376883377,\\n  44.412454519229281,\\n  47.688252845993366,\\n  50.945849245830813,\\n  54.188831071035124,\\n  57.419876154678179,\\n  60.641030026538746,\\n  63.853885828967512],\\n [15.975438807484321,\\n  21.015404934568315,\\n  25.001971500138194,\\n  28.694271223110755,\\n  32.236969407878118,\\n  35.688544091185301,\\n  39.078998185245057,\\n  42.425854432866141,\\n  45.740236776624833,\\n  49.029635055514276,\\n  52.299319390331728,\\n  55.553127779547459,\\n  58.793933759028134,\\n  62.02393848337554,\\n  65.244860767043859]]\\n\\nyn_small_zeros = \\\\\\n[[0.89357696627916752,\\n  3.9576784193148579,\\n  7.0860510603017727,\\n  10.222345043496417,\\n  13.361097473872763,\\n  16.500922441528091,\\n  19.64130970088794,\\n  22.782028047291559,\\n  25.922957653180923,\\n  29.064030252728398,\\n  32.205204116493281,\\n  35.346452305214321,\\n  38.487756653081537,\\n  41.629104466213808,\\n  44.770486607221993],\\n [2.197141326031017,\\n  5.4296810407941351,\\n  8.5960058683311689,\\n  11.749154830839881,\\n  14.897442128336725,\\n  18.043402276727856,\\n  21.188068934142213,\\n  24.331942571356912,\\n  27.475294980449224,\\n  30.618286491641115,\\n  33.761017796109326,\\n  36.90355531614295,\\n  40.045944640266876,\\n  43.188218097393211,\\n  46.330399250701687],\\n [3.3842417671495935,\\n  6.7938075132682675,\\n  10.023477979360038,\\n  13.209986710206416,\\n  16.378966558947457,\\n  19.539039990286384,\\n  22.69395593890929,\\n  25.845613720902269,\\n  28.995080395650151,\\n  32.143002257627551,\\n  35.289793869635804,\\n  38.435733485446343,\\n  41.581014867297885,\\n  44.725777117640461,\\n  47.870122696676504],\\n [4.5270246611496439,\\n  8.0975537628604907,\\n  11.396466739595867,\\n  14.623077742393873,\\n  17.81845523294552,\\n  20.997284754187761,\\n  24.166235758581828,\\n  27.328799850405162,\\n  30.486989604098659,\\n  33.642049384702463,\\n  36.794791029185579,\\n  39.945767226378749,\\n  43.095367507846703,\\n  46.2438744334407,\\n  49.391498015725107],\\n [5.6451478942208959,\\n  9.3616206152445429,\\n  12.730144474090465,\\n  15.999627085382479,\\n  19.22442895931681,\\n  22.424810599698521,\\n  25.610267054939328,\\n  28.785893657666548,\\n  31.954686680031668,\\n  35.118529525584828,\\n  38.278668089521758,\\n  41.435960629910073,\\n  44.591018225353424,\\n  47.744288086361052,\\n  50.896105199722123],\\n [6.7471838248710219,\\n  10.597176726782031,\\n  14.033804104911233,\\n  17.347086393228382,\\n  20.602899017175335,\\n  23.826536030287532,\\n  27.030134937138834,\\n  30.220335654231385,\\n  33.401105611047908,\\n  36.574972486670962,\\n  39.743627733020277,\\n  42.908248189569535,\\n  46.069679073215439,\\n  49.228543693445843,\\n  52.385312123112282],\\n [7.8377378223268716,\\n  11.811037107609447,\\n  15.313615118517857,\\n  18.670704965906724,\\n  21.958290897126571,\\n  25.206207715021249,\\n  28.429037095235496,\\n  31.634879502950644,\\n  34.828638524084437,\\n  38.013473399691765,\\n  41.19151880917741,\\n  44.364272633271975,\\n  47.53281875312084,\\n  50.697961822183806,\\n  53.860312300118388],\\n [8.919605734873789,\\n  13.007711435388313,\\n  16.573915129085334,\\n  19.974342312352426,\\n  23.293972585596648,\\n  26.5667563757203,\\n  29.809531451608321,\\n  33.031769327150685,\\n  36.239265816598239,\\n  39.435790312675323,\\n  42.623910919472727,\\n  45.805442883111651,\\n  48.981708325514764,\\n  52.153694518185572,\\n  55.322154420959698],\\n [9.9946283820824834,\\n  14.190361295800141,\\n  17.817887841179873,\\n  21.26093227125945,\\n  24.612576377421522,\\n  27.910524883974868,\\n  31.173701563441602,\\n  34.412862242025045,\\n  37.634648706110989,\\n  40.843415321050884,\\n  44.04214994542435,\\n  47.232978012841169,\\n  50.417456447370186,\\n  53.596753874948731,\\n  56.771765754432457],\\n [11.064090256031013,\\n  15.361301343575925,\\n  19.047949646361388,\\n  22.532765416313869,\\n  25.91620496332662,\\n  29.2394205079349,\\n  32.523270869465881,\\n  35.779715464475261,\\n  39.016196664616095,\\n  42.237627509803703,\\n  45.4474001519274,\\n  48.647941127433196,\\n  51.841036928216499,\\n  55.028034667184916,\\n  58.209970905250097],\\n [12.128927704415439,\\n  16.522284394784426,\\n  20.265984501212254,\\n  23.791669719454272,\\n  27.206568881574774,\\n  30.555020011020762,\\n  33.859683872746356,\\n  37.133649760307504,\\n  40.385117593813002,\\n  43.619533085646856,\\n  46.840676630553575,\\n  50.051265851897857,\\n  53.253310556711732,\\n  56.448332488918971,\\n  59.637507005589829],\\n [13.189846995683845,\\n  17.674674253171487,\\n  21.473493977824902,\\n  25.03913093040942,\\n  28.485081336558058,\\n  31.858644293774859,\\n  35.184165245422787,\\n  38.475796636190897,\\n  41.742455848758449,\\n  44.990096293791186,\\n  48.222870660068338,\\n  51.443777308699826,\\n  54.655042589416311,\\n  57.858358441436511,\\n  61.055036135780528],\\n [14.247395665073945,\\n  18.819555894710682,\\n  22.671697117872794,\\n  26.276375544903892,\\n  29.752925495549038,\\n  33.151412708998983,\\n  36.497763772987645,\\n  39.807134090704376,\\n  43.089121522203808,\\n  46.350163579538652,\\n  49.594769786270069,\\n  52.82620892320143,\\n  56.046916910756961,\\n  59.258751140598783,\\n  62.463155567737854],\\n [15.30200785858925,\\n  19.957808654258601,\\n  23.861599172945054,\\n  27.504429642227545,\\n  31.011103429019229,\\n  34.434283425782942,\\n  37.801385632318459,\\n  41.128514139788358,\\n  44.425913324440663,\\n  47.700482714581842,\\n  50.957073905278458,\\n  54.199216028087261,\\n  57.429547607017405,\\n  60.65008661807661,\\n  63.862406280068586],\\n [16.354034360047551,\\n  21.090156519983806,\\n  25.044040298785627,\\n  28.724161640881914,\\n  32.260472459522644,\\n  35.708083982611664,\\n  39.095820003878235,\\n  42.440684315990936,\\n  45.75353669045622,\\n  49.041718113283529,\\n  52.310408280968073,\\n  55.56338698149062,\\n  58.803488508906895,\\n  62.032886550960831,\\n  65.253280088312461]]\\n\\nynp_small_zeros = \\\\\\n[[2.197141326031017,\\n  5.4296810407941351,\\n  8.5960058683311689,\\n  11.749154830839881,\\n  14.897442128336725,\\n  18.043402276727856,\\n  21.188068934142213,\\n  24.331942571356912,\\n  27.475294980449224,\\n  30.618286491641115,\\n  33.761017796109326,\\n  36.90355531614295,\\n  40.045944640266876,\\n  43.188218097393211,\\n  46.330399250701687],\\n [3.6830228565851777,\\n  6.9414999536541757,\\n  10.123404655436613,\\n  13.285758156782854,\\n  16.440058007293282,\\n  19.590241756629495,\\n  22.738034717396327,\\n  25.884314618788867,\\n  29.029575819372535,\\n  32.174118233366201,\\n  35.318134458192094,\\n  38.461753870997549,\\n  41.605066618873108,\\n  44.74813744908079,\\n  47.891014070791065],\\n [5.0025829314460639,\\n  8.3507247014130795,\\n  11.574195465217647,\\n  14.760909306207676,\\n  17.931285939466855,\\n  21.092894504412739,\\n  24.249231678519058,\\n  27.402145837145258,\\n  30.552708880564553,\\n  33.70158627151572,\\n  36.849213419846257,\\n  39.995887376143356,\\n  43.141817835750686,\\n  46.287157097544201,\\n  49.432018469138281],\\n [6.2536332084598136,\\n  9.6987879841487711,\\n  12.972409052292216,\\n  16.19044719506921,\\n  19.38238844973613,\\n  22.559791857764261,\\n  25.728213194724094,\\n  28.890678419054777,\\n  32.048984005266337,\\n  35.204266606440635,\\n  38.357281675961019,\\n  41.508551443818436,\\n  44.658448731963676,\\n  47.807246956681162,\\n  50.95515126455207],\\n [7.4649217367571329,\\n  11.005169149809189,\\n  14.3317235192331,\\n  17.58443601710272,\\n  20.801062338411128,\\n  23.997004122902644,\\n  27.179886689853435,\\n  30.353960608554323,\\n  33.521797098666792,\\n  36.685048382072301,\\n  39.844826969405863,\\n  43.001910515625288,\\n  46.15685955107263,\\n  49.310088614282257,\\n  52.461911043685864],\\n [8.6495562436971983,\\n  12.280868725807848,\\n  15.660799304540377,\\n  18.949739756016503,\\n  22.192841809428241,\\n  25.409072788867674,\\n  28.608039283077593,\\n  31.795195353138159,\\n  34.973890634255288,\\n  38.14630522169358,\\n  41.313923188794905,\\n  44.477791768537617,\\n  47.638672065035628,\\n  50.797131066967842,\\n  53.953600129601663],\\n [9.8147970120105779,\\n  13.532811875789828,\\n  16.965526446046053,\\n  20.291285512443867,\\n  23.56186260680065,\\n  26.799499736027237,\\n  30.015665481543419,\\n  33.216968050039509,\\n  36.407516858984748,\\n  39.590015243560459,\\n  42.766320595957378,\\n  45.937754257017323,\\n  49.105283450953203,\\n  52.269633324547373,\\n  55.431358715604255],\\n [10.965152105242974,\\n  14.765687379508912,\\n  18.250123150217555,\\n  21.612750053384621,\\n  24.911310600813573,\\n  28.171051927637585,\\n  31.40518108895689,\\n  34.621401012564177,\\n  37.824552065973114,\\n  41.017847386464902,\\n  44.203512240871601,\\n  47.3831408366063,\\n  50.557907466622796,\\n  53.728697478957026,\\n  56.896191727313342],\\n [12.103641941939539,\\n  15.982840905145284,\\n  19.517731005559611,\\n  22.916962141504605,\\n  26.243700855690533,\\n  29.525960140695407,\\n  32.778568197561124,\\n  36.010261572392516,\\n  39.226578757802172,\\n  42.43122493258747,\\n  45.626783824134354,\\n  48.815117837929515,\\n  51.997606404328863,\\n  55.175294723956816,\\n  58.348990221754937],\\n [13.232403808592215,\\n  17.186756572616758,\\n  20.770762917490496,\\n  24.206152448722253,\\n  27.561059462697153,\\n  30.866053571250639,\\n  34.137476603379774,\\n  37.385039772270268,\\n  40.614946085165892,\\n  43.831373184731238,\\n  47.037251786726299,\\n  50.234705848765229,\\n  53.425316228549359,\\n  56.610286079882087,\\n  59.790548623216652],\\n [14.35301374369987,\\n  18.379337301642568,\\n  22.011118775283494,\\n  25.482116178696707,\\n  28.865046588695164,\\n  32.192853922166294,\\n  35.483296655830277,\\n  38.747005493021857,\\n  41.990815194320955,\\n  45.219355876831731,\\n  48.435892856078888,\\n  51.642803925173029,\\n  54.84186659475857,\\n  58.034439083840155,\\n  61.221578745109862],\\n [15.466672066554263,\\n  19.562077985759503,\\n  23.240325531101082,\\n  26.746322986645901,\\n  30.157042415639891,\\n  33.507642948240263,\\n  36.817212798512775,\\n  40.097251300178642,\\n  43.355193847719752,\\n  46.596103410173672,\\n  49.823567279972794,\\n  53.040208868780832,\\n  56.247996968470062,\\n  59.448441365714251,\\n  62.642721301357187],\\n [16.574317035530872,\\n  20.73617763753932,\\n  24.459631728238804,\\n  27.999993668839644,\\n  31.438208790267783,\\n  34.811512070805535,\\n  38.140243708611251,\\n  41.436725143893739,\\n  44.708963264433333,\\n  47.962435051891027,\\n  51.201037321915983,\\n  54.427630745992975,\\n  57.644369734615238,\\n  60.852911791989989,\\n  64.054555435720397],\\n [17.676697936439624,\\n  21.9026148697762,\\n  25.670073356263225,\\n  29.244155124266438,\\n  32.709534477396028,\\n  36.105399554497548,\\n  39.453272918267025,\\n  42.766255701958017,\\n  46.052899215578358,\\n  49.319076602061401,\\n  52.568982147952547,\\n  55.805705507386287,\\n  59.031580956740466,\\n  62.248409689597653,\\n  65.457606670836759],\\n [18.774423978290318,\\n  23.06220035979272,\\n  26.872520985976736,\\n  30.479680663499762,\\n  33.971869047372436,\\n  37.390118854896324,\\n  40.757072537673599,\\n  44.086572292170345,\\n  47.387688809191869,\\n  50.66667461073936,\\n  53.928009929563275,\\n  57.175005343085052,\\n  60.410169281219877,\\n  63.635442539153021,\\n  66.85235358587768]]\\n\\n@pytest.mark.slow\\ndef test_bessel_zeros_extra():\\n    mp.dps = 15\\n    for v in range(V):\\n        for m in range(1,M+1):\\n            print(v, m, \\\"of\\\", V, M)\\n            # Twice to test cache (if used)\\n            assert besseljzero(v,m).ae(jn_small_zeros[v][m-1])\\n            assert besseljzero(v,m).ae(jn_small_zeros[v][m-1])\\n            assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1])\\n            assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1])\\n            assert besselyzero(v,m).ae(yn_small_zeros[v][m-1])\\n            assert besselyzero(v,m).ae(yn_small_zeros[v][m-1])\\n            assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1])\\n            assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1])\\n\\n\\nimport pytest\\nimport sys\\nfrom mpmath import *\\n\\ndef test_matrix_basic():\\n    A1 = matrix(3)\\n    for i in range(3):\\n        A1[i,i] = 1\\n    assert A1 == eye(3)\\n    assert A1 == matrix(A1)\\n    A2 = matrix(3, 2)\\n    assert not A2._matrix__data\\n    A3 = matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\\n    assert list(A3) == list(range(1, 10))\\n    A3[1,1] = 0\\n    assert not (1, 1) in A3._matrix__data\\n    A4 = matrix([[1, 2, 3], [4, 5, 6]])\\n    A5 = matrix([[6, -1], [3, 2], [0, -3]])\\n    assert A4 * A5 == matrix([[12, -6], [39, -12]])\\n    assert A1 * A3 == A3 * A1 == A3\\n    pytest.raises(ValueError, lambda: A2*A2)\\n    l = [[10, 20, 30], [40, 0, 60], [70, 80, 90]]\\n    A6 = matrix(l)\\n    assert A6.tolist() == l\\n    assert A6 == eval(repr(A6))\\n    A6 = fp.matrix(A6)\\n    assert A6 == eval(repr(A6))\\n    assert A6*1j == eval(repr(A6*1j))\\n    assert A3 * 10 == 10 * A3 == A6\\n    assert A2.rows == 3\\n    assert A2.cols == 2\\n    A3.rows = 2\\n    A3.cols = 2\\n    assert len(A3._matrix__data) == 3\\n    assert A4 + A4 == 2*A4\\n    pytest.raises(ValueError, lambda: A4 + A2)\\n    assert sum(A1 - A1) == 0\\n    A7 = matrix([[1, 2], [3, 4], [5, 6], [7, 8]])\\n    x = matrix([10, -10])\\n    assert A7*x == matrix([-10, -10, -10, -10])\\n    A8 = ones(5)\\n    assert sum((A8 + 1) - (2 - zeros(5))) == 0\\n    assert (1 + ones(4)) / 2 - 1 == zeros(4)\\n    assert eye(3)**10 == eye(3)\\n    pytest.raises(ValueError, lambda: A7**2)\\n    A9 = randmatrix(3)\\n    A10 = matrix(A9)\\n    A9[0,0] = -100\\n    assert A9 != A10\\n    assert nstr(A9)\\n\\ndef test_matmul():\\n    \\\"\\\"\\\"\\n    Test the PEP465 \\\"@\\\" matrix multiplication syntax.\\n    To avoid syntax errors when importing this file in Python 3.5 and below, we have to use exec() - sorry for that.\\n    \\\"\\\"\\\"\\n    # TODO remove exec() wrapper as soon as we drop support for Python <= 3.5\\n    if sys.hexversion < 0x30500f0:\\n        # we are on Python < 3.5\\n        pytest.skip(\\\"'@' (__matmul__) is only supported in Python 3.5 or newer\\\")\\n    A4 = matrix([[1, 2, 3], [4, 5, 6]])\\n    A5 = matrix([[6, -1], [3, 2], [0, -3]])\\n    exec(\\\"assert A4 @ A5 == A4 * A5\\\")\\n\\ndef test_matrix_slices():\\n    A = matrix([    [1, 2, 3],\\n                        [4, 5 ,6],\\n                        [7, 8 ,9]])\\n    V = matrix([1,2,3,4,5])\\n\\n    # Get slice\\n    assert A[:,:] == A\\n    assert A[:,1] == matrix([[2],[5],[8]])\\n    assert A[2,:] == matrix([[7, 8 ,9]])\\n    assert A[1:3,1:3] == matrix([[5,6],[8,9]])\\n    assert V[2:4] == matrix([3,4])\\n    pytest.raises(IndexError, lambda: A[:,1:6])\\n\\n    # Assign slice with matrix\\n    A1 = matrix(3)\\n    A1[:,:] = A\\n    assert A1[:,:] == matrix([[1, 2, 3],\\n                                        [4, 5 ,6],\\n                                        [7, 8 ,9]])\\n    A1[0,:] = matrix([[10, 11, 12]])\\n    assert A1 == matrix([ [10, 11, 12],\\n                                    [4, 5 ,6],\\n                                    [7, 8 ,9]])\\n    A1[:,2] = matrix([[13], [14], [15]])\\n    assert A1 == matrix([ [10, 11, 13],\\n                                    [4, 5 ,14],\\n                                    [7, 8 ,15]])\\n    A1[:2,:2] = matrix([[16, 17], [18 , 19]])\\n    assert A1 == matrix([ [16, 17, 13],\\n                                    [18, 19 ,14],\\n                                    [7, 8 ,15]])\\n    V[1:3] = 10\\n    assert V == matrix([1,10,10,4,5])\\n    with pytest.raises(ValueError):\\n        A1[2,:] = A[:,1]\\n\\n    with pytest.raises(IndexError):\\n        A1[2,1:20] = A[:,:]\\n\\n    # Assign slice with scalar\\n    A1[:,2] = 10\\n    assert A1 == matrix([ [16, 17, 10],\\n                                    [18, 19 ,10],\\n                                    [7, 8 ,10]])\\n    A1[:,:] = 40\\n    for x in A1:\\n        assert x == 40\\n\\n\\ndef test_matrix_power():\\n    A = matrix([[1, 2], [3, 4]])\\n    assert A**2 == A*A\\n    assert A**3 == A*A*A\\n    assert A**-1 == inverse(A)\\n    assert A**-2 == inverse(A*A)\\n\\ndef test_matrix_transform():\\n    A = matrix([[1, 2], [3, 4], [5, 6]])\\n    assert A.T == A.transpose() == matrix([[1, 3, 5], [2, 4, 6]])\\n    swap_row(A, 1, 2)\\n    assert A == matrix([[1, 2], [5, 6], [3, 4]])\\n    l = [1, 2]\\n    swap_row(l, 0, 1)\\n    assert l == [2, 1]\\n    assert extend(eye(3), [1,2,3]) == matrix([[1,0,0,1],[0,1,0,2],[0,0,1,3]])\\n\\ndef test_matrix_conjugate():\\n    A = matrix([[1 + j, 0], [2, j]])\\n    assert A.conjugate() == matrix([[mpc(1, -1), 0], [2, mpc(0, -1)]])\\n    assert A.transpose_conj() == A.H == matrix([[mpc(1, -1), 2],\\n                                                [0, mpc(0, -1)]])\\n\\ndef test_matrix_creation():\\n    assert diag([1, 2, 3]) == matrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]])\\n    A1 = ones(2, 3)\\n    assert A1.rows == 2 and A1.cols == 3\\n    for a in A1:\\n        assert a == 1\\n    A2 = zeros(3, 2)\\n    assert A2.rows == 3 and A2.cols == 2\\n    for a in A2:\\n        assert a == 0\\n    assert randmatrix(10) != randmatrix(10)\\n    one = mpf(1)\\n    assert hilbert(3) == matrix([[one, one/2, one/3],\\n                                 [one/2, one/3, one/4],\\n                                 [one/3, one/4, one/5]])\\n\\ndef test_norms():\\n    # matrix norms\\n    A = matrix([[1, -2], [-3, -1], [2, 1]])\\n    assert mnorm(A,1) == 6\\n    assert mnorm(A,inf) == 4\\n    assert mnorm(A,'F') == sqrt(20)\\n    # vector norms\\n    assert norm(-3) == 3\\n    x = [1, -2, 7, -12]\\n    assert norm(x, 1) == 22\\n    assert round(norm(x, 2), 10) == 14.0712472795\\n    assert round(norm(x, 10), 10) == 12.0054633727\\n    assert norm(x, inf) == 12\\n\\ndef test_vector():\\n    x = matrix([0, 1, 2, 3, 4])\\n    assert x == matrix([[0], [1], [2], [3], [4]])\\n    assert x[3] == 3\\n    assert len(x._matrix__data) == 4\\n    assert list(x) == list(range(5))\\n    x[0] = -10\\n    x[4] = 0\\n    assert x[0] == -10\\n    assert len(x) == len(x.T) == 5\\n    assert x.T*x == matrix([[114]])\\n\\ndef test_matrix_copy():\\n    A = ones(6)\\n    B = A.copy()\\n    C = +A\\n    assert A == B\\n    assert A == C\\n    B[0,0] = 0\\n    assert A != B\\n    C[0,0] = 42\\n    assert A != C\\n\\ndef test_matrix_numpy():\\n    try:\\n        import numpy\\n    except ImportError:\\n        return\\n    l = [[1, 2], [3, 4], [5, 6]]\\n    a = numpy.array(l)\\n    assert matrix(l) == matrix(a)\\n\\ndef test_interval_matrix_scalar_mult():\\n    \\\"\\\"\\\"Multiplication of iv.matrix and any scalar type\\\"\\\"\\\"\\n    a = mpi(-1, 1)\\n    b = a + a * 2j\\n    c = mpf(42)\\n    d = c + c * 2j\\n    e = 1.234\\n    f = fp.convert(e)\\n    g = e + e * 3j\\n    h = fp.convert(g)\\n    M = iv.ones(1)\\n    for x in [a, b, c, d, e, f, g, h]:\\n        assert x * M == iv.matrix([x])\\n        assert M * x == iv.matrix([x])\\n\\n@pytest.mark.xfail()\\ndef test_interval_matrix_matrix_mult():\\n    \\\"\\\"\\\"Multiplication of iv.matrix and other matrix types\\\"\\\"\\\"\\n    A = ones(1)\\n    B = fp.ones(1)\\n    M = iv.ones(1)\\n    for X in [A, B, M]:\\n        assert X * M == iv.matrix(X)\\n        assert X * M == X\\n        assert M * X == iv.matrix(X)\\n        assert M * X == X\\n\\ndef test_matrix_conversion_to_iv():\\n    # Test that matrices with foreign datatypes are properly converted\\n    for other_type_eye in [eye(3), fp.eye(3), iv.eye(3)]:\\n        A = iv.matrix(other_type_eye)\\n        B = iv.eye(3)\\n        assert type(A[0,0]) == type(B[0,0])\\n        assert A.tolist() == B.tolist()\\n\\ndef test_interval_matrix_mult_bug():\\n    # regression test for interval matrix multiplication:\\n    # result must be nonzero-width and contain the exact result\\n    x = convert('1.00000000000001') # note: this is implicitly rounded to some near mpf float value\\n    A = matrix([[x]])\\n    B = iv.matrix(A)\\n    C = iv.matrix([[x]])\\n    assert B == C\\n    B = B * B\\n    C = C * C\\n    assert B == C\\n    assert B[0, 0].delta > 1e-16\\n    assert B[0, 0].delta < 3e-16\\n    assert C[0, 0].delta > 1e-16\\n    assert C[0, 0].delta < 3e-16\\n    assert mp.mpf('1.00000000000001998401444325291756783368705994138804689654') in B[0, 0]\\n    assert mp.mpf('1.00000000000001998401444325291756783368705994138804689654') in C[0, 0]\\n    # the following caused an error before the bug was fixed\\n    assert iv.matrix(mp.eye(2)) * (iv.ones(2) + mpi(1, 2)) == iv.matrix([[mpi(2, 3), mpi(2, 3)], [mpi(2, 3), mpi(2, 3)]])\\n\\n\\nfrom mpmath import zetazero\\nfrom timeit import default_timer as clock\\n\\ndef test_zetazero():\\n    cases = [\\\\\\n    (399999999, 156762524.6750591511),\\n    (241389216, 97490234.2276711795),\\n    (526196239, 202950727.691229534),\\n    (542964976, 209039046.578535272),\\n    (1048449112, 388858885.231056486),\\n    (1048449113, 388858885.384337406),\\n    (1048449114, 388858886.002285122),\\n    (1048449115, 388858886.00239369),\\n    (1048449116, 388858886.690745053)\\n    ]\\n    for n, v in cases:\\n        print(n, v)\\n        t1 = clock()\\n        ok = zetazero(n).ae(complex(0.5,v))\\n        t2 = clock()\\n        print(\\\"ok =\\\", ok, (\\\"(time = %s)\\\" % round(t2-t1,3)))\\n    print(\\\"Now computing two huge zeros (this may take hours)\\\")\\n    print(\\\"Computing zetazero(8637740722917)\\\")\\n    ok = zetazero(8637740722917).ae(complex(0.5,2124447368584.39296466152))\\n    print(\\\"ok =\\\", ok)\\n    ok = zetazero(8637740722918).ae(complex(0.5,2124447368584.39298170604))\\n    print(\\\"ok =\\\", ok)\\n\\nif __name__ == \\\"__main__\\\":\\n    test_zetazero()\\n\\n\\nfrom mpmath import nstr, matrix, inf\\n\\ndef test_nstr():\\n    m = matrix([[0.75, 0.190940654, -0.0299195971],\\n                [0.190940654, 0.65625, 0.205663228],\\n                [-0.0299195971, 0.205663228, 0.64453125e-20]])\\n    assert nstr(m, 4, min_fixed=-inf) == \\\\\\n    '''[    0.75  0.1909                    -0.02992]\\n[  0.1909  0.6563                      0.2057]\\n[-0.02992  0.2057  0.000000000000000000006445]'''\\n    assert nstr(m, 4) == \\\\\\n    '''[    0.75  0.1909   -0.02992]\\n[  0.1909  0.6563     0.2057]\\n[-0.02992  0.2057  6.445e-21]'''\\n\\n\\nimport os\\nimport tempfile\\nimport pickle\\n\\nfrom mpmath import *\\n\\ndef pickler(obj):\\n    fn = tempfile.mktemp()\\n\\n    f = open(fn, 'wb')\\n    pickle.dump(obj, f)\\n    f.close()\\n\\n    f = open(fn, 'rb')\\n    obj2 = pickle.load(f)\\n    f.close()\\n    os.remove(fn)\\n\\n    return obj2\\n\\ndef test_pickle():\\n\\n    obj = mpf('0.5')\\n    assert obj == pickler(obj)\\n\\n    obj = mpc('0.5','0.2')\\n    assert obj == pickler(obj)\\n\\n\\n# TODO: don't use round\\n\\nfrom __future__ import division\\n\\nimport pytest\\nfrom mpmath import *\\nxrange = libmp.backend.xrange\\n\\n# XXX: these shouldn't be visible(?)\\nLU_decomp = mp.LU_decomp\\nL_solve = mp.L_solve\\nU_solve = mp.U_solve\\nhouseholder = mp.householder\\nimprove_solution = mp.improve_solution\\n\\nA1 = matrix([[3, 1, 6],\\n             [2, 1, 3],\\n             [1, 1, 1]])\\nb1 = [2, 7, 4]\\n\\nA2 = matrix([[ 2, -1, -1,  2],\\n             [ 6, -2,  3, -1],\\n             [-4,  2,  3, -2],\\n             [ 2,  0,  4, -3]])\\nb2 = [3, -3, -2, -1]\\n\\nA3 = matrix([[ 1,  0, -1, -1,  0],\\n             [ 0,  1,  1,  0, -1],\\n             [ 4, -5,  2,  0,  0],\\n             [ 0,  0, -2,  9,-12],\\n             [ 0,  5,  0,  0, 12]])\\nb3 = [0, 0, 0, 0, 50]\\n\\nA4 = matrix([[10.235, -4.56,   0.,   -0.035,  5.67],\\n             [-2.463,  1.27,   3.97, -8.63,   1.08],\\n             [-6.58,   0.86,  -0.257, 9.32, -43.6 ],\\n             [ 9.83,   7.39, -17.25,  0.036, 24.86],\\n             [-9.31,  34.9,   78.56,  1.07,  65.8 ]])\\nb4 = [8.95, 20.54, 7.42, 5.60, 58.43]\\n\\nA5 = matrix([[ 1,  2, -4],\\n             [-2, -3,  5],\\n             [ 3,  5, -8]])\\n\\nA6 = matrix([[ 1.377360,  2.481400,   5.359190],\\n             [ 2.679280, -1.229560,  25.560210],\\n             [-1.225280+1.e6,  9.910180, -35.049900-1.e6]])\\nb6 = [23.500000, -15.760000, 2.340000]\\n\\nA7 = matrix([[1, -0.5],\\n             [2, 1],\\n             [-2, 6]])\\nb7 = [3, 2, -4]\\n\\nA8 = matrix([[1, 2, 3],\\n             [-1, 0, 1],\\n             [-1, -2, -1],\\n             [1, 0, -1]])\\nb8 = [1, 2, 3, 4]\\n\\nA9 = matrix([[ 4,  2, -2],\\n             [ 2,  5, -4],\\n             [-2, -4, 5.5]])\\nb9 = [10, 16, -15.5]\\n\\nA10 = matrix([[1.0 + 1.0j, 2.0, 2.0],\\n            [4.0, 5.0, 6.0],\\n            [7.0, 8.0, 9.0]])\\nb10 = [1.0, 1.0 + 1.0j, 1.0]\\n\\n\\ndef test_LU_decomp():\\n    A = A3.copy()\\n    b = b3\\n    A, p = LU_decomp(A)\\n    y = L_solve(A, b, p)\\n    x = U_solve(A, y)\\n    assert p == [2, 1, 2, 3]\\n    assert [round(i, 14) for i in x] == [3.78953107960742, 2.9989094874591098,\\n            -0.081788440567070006, 3.8713195201744801, 2.9171210468920399]\\n    A = A4.copy()\\n    b = b4\\n    A, p = LU_decomp(A)\\n    y = L_solve(A, b, p)\\n    x = U_solve(A, y)\\n    assert p == [0, 3, 4, 3]\\n    assert [round(i, 14) for i in x] == [2.6383625899619201, 2.6643834462368399,\\n            0.79208015947958998, -2.5088376454101899, -1.0567657691375001]\\n    A = randmatrix(3)\\n    bak = A.copy()\\n    LU_decomp(A, overwrite=1)\\n    assert A != bak\\n\\ndef test_inverse():\\n    for A in [A1, A2, A5]:\\n        inv = inverse(A)\\n        assert mnorm(A*inv - eye(A.rows), 1) < 1.e-14\\n\\ndef test_householder():\\n    mp.dps = 15\\n    A, b = A8, b8\\n    H, p, x, r = householder(extend(A, b))\\n    assert H == matrix(\\n    [[mpf('3.0'), mpf('-2.0'), mpf('-1.0'), 0],\\n     [-1.0,mpf('3.333333333333333'),mpf('-2.9999999999999991'),mpf('2.0')],\\n     [-1.0, mpf('-0.66666666666666674'),mpf('2.8142135623730948'),\\n      mpf('-2.8284271247461898')],\\n     [1.0, mpf('-1.3333333333333333'),mpf('-0.20000000000000018'),\\n      mpf('4.2426406871192857')]])\\n    assert p == [-2, -2, mpf('-1.4142135623730949')]\\n    assert round(norm(r, 2), 10) == 4.2426406870999998\\n\\n    y = [102.102, 58.344, 36.463, 24.310, 17.017, 12.376, 9.282, 7.140, 5.610,\\n         4.488, 3.6465, 3.003]\\n\\n    def coeff(n):\\n        # similiar to Hilbert matrix\\n        A = []\\n        for i in range(1, 13):\\n            A.append([1. / (i + j - 1) for j in range(1, n + 1)])\\n        return matrix(A)\\n\\n    residuals = []\\n    refres = []\\n    for n in range(2, 7):\\n        A = coeff(n)\\n        H, p, x, r = householder(extend(A, y))\\n        x = matrix(x)\\n        y = matrix(y)\\n        residuals.append(norm(r, 2))\\n        refres.append(norm(residual(A, x, y), 2))\\n    assert [round(res, 10) for res in residuals] == [15.1733888877,\\n           0.82378073210000002, 0.302645887, 0.0260109244,\\n           0.00058653999999999998]\\n    assert norm(matrix(residuals) - matrix(refres), inf) < 1.e-13\\n\\n    def hilbert_cmplx(n):\\n        # Complexified  Hilbert matrix\\n        A = hilbert(2*n,n)\\n        v = randmatrix(2*n, 2, min=-1, max=1)\\n        v = v.apply(lambda x: exp(1J*pi()*x))\\n        A = diag(v[:,0])*A*diag(v[:n,1])\\n        return A\\n\\n    residuals_cmplx = []\\n    refres_cmplx = []\\n    for n in range(2, 10):\\n        A = hilbert_cmplx(n)\\n        H, p, x, r = householder(A.copy())\\n        residuals_cmplx.append(norm(r, 2))\\n        refres_cmplx.append(norm(residual(A[:,:n-1], x, A[:,n-1]), 2))\\n    assert norm(matrix(residuals_cmplx) - matrix(refres_cmplx), inf) < 1.e-13\\n\\ndef test_factorization():\\n    A = randmatrix(5)\\n    P, L, U = lu(A)\\n    assert mnorm(P*A - L*U, 1) < 1.e-15\\n\\ndef test_solve():\\n    assert norm(residual(A6, lu_solve(A6, b6), b6), inf) < 1.e-10\\n    assert norm(residual(A7, lu_solve(A7, b7), b7), inf) < 1.5\\n    assert norm(residual(A8, lu_solve(A8, b8), b8), inf) <= 3 + 1.e-10\\n    assert norm(residual(A6, qr_solve(A6, b6)[0], b6), inf) < 1.e-10\\n    assert norm(residual(A7, qr_solve(A7, b7)[0], b7), inf) < 1.5\\n    assert norm(residual(A8, qr_solve(A8, b8)[0], b8), 2) <= 4.3\\n    assert norm(residual(A10, lu_solve(A10, b10), b10), 2) < 1.e-10\\n    assert norm(residual(A10, qr_solve(A10, b10)[0], b10), 2) < 1.e-10\\n\\ndef test_solve_overdet_complex():\\n    A = matrix([[1, 2j], [3, 4j], [5, 6]])\\n    b = matrix([1 + j, 2, -j])\\n    assert norm(residual(A, lu_solve(A, b), b)) < 1.0208\\n\\ndef test_singular():\\n    mp.dps = 15\\n    A = [[5.6, 1.2], [7./15, .1]]\\n    B = repr(zeros(2))\\n    b = [1, 2]\\n    for i in ['lu_solve(%s, %s)' % (A, b), 'lu_solve(%s, %s)' % (B, b),\\n              'qr_solve(%s, %s)' % (A, b), 'qr_solve(%s, %s)' % (B, b)]:\\n        pytest.raises((ZeroDivisionError, ValueError), lambda: eval(i))\\n\\ndef test_cholesky():\\n    assert fp.cholesky(fp.matrix(A9)) == fp.matrix([[2, 0, 0], [1, 2, 0], [-1, -3/2, 3/2]])\\n    x = fp.cholesky_solve(A9, b9)\\n    assert fp.norm(fp.residual(A9, x, b9), fp.inf) == 0\\n\\ndef test_det():\\n    assert det(A1) == 1\\n    assert round(det(A2), 14) == 8\\n    assert round(det(A3)) == 1834\\n    assert round(det(A4)) == 4443376\\n    assert det(A5) == 1\\n    assert round(det(A6)) == 78356463\\n    assert det(zeros(3)) == 0\\n\\ndef test_cond():\\n    mp.dps = 15\\n    A = matrix([[1.2969, 0.8648], [0.2161, 0.1441]])\\n    assert cond(A, lambda x: mnorm(x,1)) == mpf('327065209.73817754')\\n    assert cond(A, lambda x: mnorm(x,inf)) == mpf('327065209.73817754')\\n    assert cond(A, lambda x: mnorm(x,'F')) == mpf('249729266.80008656')\\n\\n@extradps(50)\\ndef test_precision():\\n    A = randmatrix(10, 10)\\n    assert mnorm(inverse(inverse(A)) - A, 1) < 1.e-45\\n\\ndef test_interval_matrix():\\n    mp.dps = 15\\n    iv.dps = 15\\n    a = iv.matrix([['0.1','0.3','1.0'],['7.1','5.5','4.8'],['3.2','4.4','5.6']])\\n    b = iv.matrix(['4','0.6','0.5'])\\n    c = iv.lu_solve(a, b)\\n    assert c[0].delta < 1e-13\\n    assert c[1].delta < 1e-13\\n    assert c[2].delta < 1e-13\\n    assert 5.25823271130625686059275 in c[0]\\n    assert -13.155049396267837541163 in c[1]\\n    assert 7.42069154774972557628979 in c[2]\\n\\ndef test_LU_cache():\\n    A = randmatrix(3)\\n    LU = LU_decomp(A)\\n    assert A._LU == LU_decomp(A)\\n    A[0,0] = -1000\\n    assert A._LU is None\\n\\ndef test_improve_solution():\\n    A = randmatrix(5, min=1e-20, max=1e20)\\n    b = randmatrix(5, 1, min=-1000, max=1000)\\n    x1 = lu_solve(A, b) + randmatrix(5, 1, min=-1e-5, max=1.e-5)\\n    x2 = improve_solution(A, x1, b)\\n    assert norm(residual(A, x2, b), 2) < norm(residual(A, x1, b), 2)\\n\\ndef test_exp_pade():\\n    for i in range(3):\\n        dps = 15\\n        extra = 15\\n        mp.dps = dps + extra\\n        dm = 0\\n        N = 3\\n        dg = range(1,N+1)\\n        a = diag(dg)\\n        expa = diag([exp(x) for x in dg])\\n        # choose a random matrix not close to be singular\\n        # to avoid adding too much extra precision in computing\\n        # m**-1 * M * m\\n        while abs(dm) < 0.01:\\n            m = randmatrix(N)\\n            dm = det(m)\\n        m = m/dm\\n        a1 = m**-1 * a * m\\n        e2 = m**-1 * expa * m\\n        mp.dps = dps\\n        e1 = expm(a1, method='pade')\\n        mp.dps = dps + extra\\n        d = e2 - e1\\n        #print d\\n        mp.dps = dps\\n        assert norm(d, inf).ae(0)\\n    mp.dps = 15\\n\\ndef test_qr():\\n    mp.dps = 15                     # used default value for dps\\n    lowlimit = -9                   # lower limit of matrix element value\\n    uplimit = 9                     # uppter limit of matrix element value\\n    maxm = 4                        # max matrix size\\n    flg = False                     # toggle to create real vs complex matrix\\n    zero = mpf('0.0')\\n\\n    for k in xrange(0,10):\\n        exdps = 0\\n        mode = 'full'\\n        flg = bool(k % 2)\\n\\n        # generate arbitrary matrix size (2 to maxm)\\n        num1 = nint(maxm*rand())\\n        num2 = nint(maxm*rand())\\n        m = int(max(num1, num2))\\n        n = int(min(num1, num2))\\n\\n        # create matrix\\n        A = mp.matrix(m,n)\\n\\n        # populate matrix values with arbitrary integers\\n        if flg:\\n            flg = False\\n            dtype = 'complex'\\n            for j in xrange(0,n):\\n                for i in xrange(0,m):\\n                    val = nint(lowlimit + (uplimit-lowlimit)*rand())\\n                    val2 = nint(lowlimit + (uplimit-lowlimit)*rand())\\n                    A[i,j] = mpc(val, val2)\\n        else:\\n            flg = True\\n            dtype = 'real'\\n            for j in xrange(0,n):\\n                for i in xrange(0,m):\\n                    val = nint(lowlimit + (uplimit-lowlimit)*rand())\\n                    A[i,j] = mpf(val)\\n\\n        # perform A -> QR decomposition\\n        Q, R = qr(A, mode, edps = exdps)\\n\\n        #print('\\\\n\\\\n A = \\\\n', nstr(A, 4))\\n        #print('\\\\n Q = \\\\n', nstr(Q, 4))\\n        #print('\\\\n R = \\\\n', nstr(R, 4))\\n        #print('\\\\n Q*R = \\\\n', nstr(Q*R, 4))\\n\\n        maxnorm = mpf('1.0E-11')\\n        n1 = norm(A - Q * R)\\n        #print '\\\\n Norm of A - Q * R = ', n1\\n        assert n1 <= maxnorm\\n\\n        if dtype == 'real':\\n            n1 = norm(eye(m) - Q.T * Q)\\n            #print ' Norm of I - Q.T * Q = ', n1\\n            assert n1 <= maxnorm\\n\\n            n1 = norm(eye(m) - Q * Q.T)\\n            #print ' Norm of I - Q * Q.T = ', n1\\n            assert n1 <= maxnorm\\n\\n        if dtype == 'complex':\\n            n1 = norm(eye(m) - Q.T * Q.conjugate())\\n            #print ' Norm of I - Q.T * Q.conjugate() = ', n1\\n            assert n1 <= maxnorm\\n\\n            n1 = norm(eye(m) - Q.conjugate() * Q.T)\\n            #print ' Norm of I - Q.conjugate() * Q.T = ', n1\\n            assert n1 <= maxnorm\\n\\n\\n\\\"\\\"\\\"\\nLimited tests of the visualization module. Right now it just makes\\nsure that passing custom Axes works.\\n\\n\\\"\\\"\\\"\\n\\nfrom mpmath import mp, fp\\n\\ndef test_axes():\\n    try:\\n        import matplotlib\\n        version = matplotlib.__version__.split(\\\"-\\\")[0]\\n        version = version.split(\\\".\\\")[:2]\\n        if [int(_) for _ in version] < [0,99]:\\n            raise ImportError\\n        import pylab\\n    except ImportError:\\n        print(\\\"\\\\nSkipping test (pylab not available or too old version)\\\\n\\\")\\n        return\\n    fig = pylab.figure()\\n    axes = fig.add_subplot(111)\\n    for ctx in [mp, fp]:\\n        ctx.plot(lambda x: x**2, [0, 3], axes=axes)\\n        assert axes.get_xlabel() == 'x'\\n        assert axes.get_ylabel() == 'f(x)'\\n\\n    fig = pylab.figure()\\n    axes = fig.add_subplot(111)\\n    for ctx in [mp, fp]:\\n        ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes)\\n    assert axes.get_xlabel() == 'Re(z)'\\n    assert axes.get_ylabel() == 'Im(z)'\\n\\n\\nfrom mpmath import *\\nfrom mpmath.libmp import *\\n\\nimport random\\n\\ndef test_fractional_pow():\\n    mp.dps = 15\\n    assert mpf(16) ** 2.5 == 1024\\n    assert mpf(64) ** 0.5 == 8\\n    assert mpf(64) ** -0.5 == 0.125\\n    assert mpf(16) ** -2.5 == 0.0009765625\\n    assert (mpf(10) ** 0.5).ae(3.1622776601683791)\\n    assert (mpf(10) ** 2.5).ae(316.2277660168379)\\n    assert (mpf(10) ** -0.5).ae(0.31622776601683794)\\n    assert (mpf(10) ** -2.5).ae(0.0031622776601683794)\\n    assert (mpf(10) ** 0.3).ae(1.9952623149688795)\\n    assert (mpf(10) ** -0.3).ae(0.50118723362727224)\\n\\ndef test_pow_integer_direction():\\n    \\\"\\\"\\\"\\n    Test that inexact integer powers are rounded in the right\\n    direction.\\n    \\\"\\\"\\\"\\n    random.seed(1234)\\n    for prec in [10, 53, 200]:\\n        for i in range(50):\\n            a = random.randint(1<<(prec-1), 1<<prec)\\n            b = random.randint(2, 100)\\n            ab = a**b\\n            # note: could actually be exact, but that's very unlikely!\\n            assert to_int(mpf_pow(from_int(a), from_int(b), prec, round_down)) < ab\\n            assert to_int(mpf_pow(from_int(a), from_int(b), prec, round_up)) > ab\\n\\n\\ndef test_pow_epsilon_rounding():\\n    \\\"\\\"\\\"\\n    Stress test directed rounding for powers with integer exponents.\\n    Basically, we look at the following cases:\\n\\n    >>> 1.0001 ** -5 # doctest: +SKIP\\n    0.99950014996500702\\n    >>> 0.9999 ** -5 # doctest: +SKIP\\n    1.000500150035007\\n    >>> (-1.0001) ** -5 # doctest: +SKIP\\n    -0.99950014996500702\\n    >>> (-0.9999) ** -5 # doctest: +SKIP\\n    -1.000500150035007\\n\\n    >>> 1.0001 ** -6 # doctest: +SKIP\\n    0.99940020994401269\\n    >>> 0.9999 ** -6 # doctest: +SKIP\\n    1.0006002100560125\\n    >>> (-1.0001) ** -6 # doctest: +SKIP\\n    0.99940020994401269\\n    >>> (-0.9999) ** -6 # doctest: +SKIP\\n    1.0006002100560125\\n\\n    etc.\\n\\n    We run the tests with values a very small epsilon away from 1:\\n    small enough that the result is indistinguishable from 1 when\\n    rounded to nearest at the output precision. We check that the\\n    result is not erroneously rounded to 1 in cases where the\\n    rounding should be done strictly away from 1.\\n    \\\"\\\"\\\"\\n\\n    def powr(x, n, r):\\n        return make_mpf(mpf_pow_int(x._mpf_, n, mp.prec, r))\\n\\n    for (inprec, outprec) in [(100, 20), (5000, 3000)]:\\n\\n        mp.prec = inprec\\n\\n        pos10001 = mpf(1) + mpf(2)**(-inprec+5)\\n        pos09999 = mpf(1) - mpf(2)**(-inprec+5)\\n        neg10001 = -pos10001\\n        neg09999 = -pos09999\\n\\n        mp.prec = outprec\\n        r = round_up\\n        assert powr(pos10001, 5, r) > 1\\n        assert powr(pos09999, 5, r) == 1\\n        assert powr(neg10001, 5, r) < -1\\n        assert powr(neg09999, 5, r) == -1\\n        assert powr(pos10001, 6, r) > 1\\n        assert powr(pos09999, 6, r) == 1\\n        assert powr(neg10001, 6, r) > 1\\n        assert powr(neg09999, 6, r) == 1\\n\\n        assert powr(pos10001, -5, r) == 1\\n        assert powr(pos09999, -5, r) > 1\\n        assert powr(neg10001, -5, r) == -1\\n        assert powr(neg09999, -5, r) < -1\\n        assert powr(pos10001, -6, r) == 1\\n        assert powr(pos09999, -6, r) > 1\\n        assert powr(neg10001, -6, r) == 1\\n        assert powr(neg09999, -6, r) > 1\\n\\n        r = round_down\\n        assert powr(pos10001, 5, r) == 1\\n        assert powr(pos09999, 5, r) < 1\\n        assert powr(neg10001, 5, r) == -1\\n        assert powr(neg09999, 5, r) > -1\\n        assert powr(pos10001, 6, r) == 1\\n        assert powr(pos09999, 6, r) < 1\\n        assert powr(neg10001, 6, r) == 1\\n        assert powr(neg09999, 6, r) < 1\\n\\n        assert powr(pos10001, -5, r) < 1\\n        assert powr(pos09999, -5, r) == 1\\n        assert powr(neg10001, -5, r) > -1\\n        assert powr(neg09999, -5, r) == -1\\n        assert powr(pos10001, -6, r) < 1\\n        assert powr(pos09999, -6, r) == 1\\n        assert powr(neg10001, -6, r) < 1\\n        assert powr(neg09999, -6, r) == 1\\n\\n        r = round_ceiling\\n        assert powr(pos10001, 5, r) > 1\\n        assert powr(pos09999, 5, r) == 1\\n        assert powr(neg10001, 5, r) == -1\\n        assert powr(neg09999, 5, r) > -1\\n        assert powr(pos10001, 6, r) > 1\\n        assert powr(pos09999, 6, r) == 1\\n        assert powr(neg10001, 6, r) > 1\\n        assert powr(neg09999, 6, r) == 1\\n\\n        assert powr(pos10001, -5, r) == 1\\n        assert powr(pos09999, -5, r) > 1\\n        assert powr(neg10001, -5, r) > -1\\n        assert powr(neg09999, -5, r) == -1\\n        assert powr(pos10001, -6, r) == 1\\n        assert powr(pos09999, -6, r) > 1\\n        assert powr(neg10001, -6, r) == 1\\n        assert powr(neg09999, -6, r) > 1\\n\\n        r = round_floor\\n        assert powr(pos10001, 5, r) == 1\\n        assert powr(pos09999, 5, r) < 1\\n        assert powr(neg10001, 5, r) < -1\\n        assert powr(neg09999, 5, r) == -1\\n        assert powr(pos10001, 6, r) == 1\\n        assert powr(pos09999, 6, r) < 1\\n        assert powr(neg10001, 6, r) == 1\\n        assert powr(neg09999, 6, r) < 1\\n\\n        assert powr(pos10001, -5, r) < 1\\n        assert powr(pos09999, -5, r) == 1\\n        assert powr(neg10001, -5, r) == -1\\n        assert powr(neg09999, -5, r) < -1\\n        assert powr(pos10001, -6, r) < 1\\n        assert powr(pos09999, -6, r) == 1\\n        assert powr(neg10001, -6, r) < 1\\n        assert powr(neg09999, -6, r) == 1\\n\\n    mp.dps = 15\\n\\n\\n\\\"\\\"\\\"\\nLimited tests of the elliptic functions module.  A full suite of\\nextensive testing can be found in elliptic_torture_tests.py\\n\\nAuthor of the first version: M.T. Taschuk\\n\\nReferences:\\n\\n[1] Abramowitz & Stegun. 'Handbook of Mathematical Functions, 9th Ed.',\\n    (Dover duplicate of 1972 edition)\\n[2] Whittaker 'A Course of Modern Analysis, 4th Ed.', 1946,\\n    Cambridge University Press\\n\\n\\\"\\\"\\\"\\n\\nimport mpmath\\nimport random\\nimport pytest\\n\\nfrom mpmath import *\\n\\ndef mpc_ae(a, b, eps=eps):\\n    res = True\\n    res = res and a.real.ae(b.real, eps)\\n    res = res and a.imag.ae(b.imag, eps)\\n    return res\\n\\nzero = mpf(0)\\none = mpf(1)\\n\\njsn = ellipfun('sn')\\njcn = ellipfun('cn')\\njdn = ellipfun('dn')\\n\\ncalculate_nome = lambda k: qfrom(k=k)\\n\\ndef test_ellipfun():\\n    mp.dps = 15\\n    assert ellipfun('ss', 0, 0) == 1\\n    assert ellipfun('cc', 0, 0) == 1\\n    assert ellipfun('dd', 0, 0) == 1\\n    assert ellipfun('nn', 0, 0) == 1\\n    assert ellipfun('sn', 0.25, 0).ae(sin(0.25))\\n    assert ellipfun('cn', 0.25, 0).ae(cos(0.25))\\n    assert ellipfun('dn', 0.25, 0).ae(1)\\n    assert ellipfun('ns', 0.25, 0).ae(csc(0.25))\\n    assert ellipfun('nc', 0.25, 0).ae(sec(0.25))\\n    assert ellipfun('nd', 0.25, 0).ae(1)\\n    assert ellipfun('sc', 0.25, 0).ae(tan(0.25))\\n    assert ellipfun('sd', 0.25, 0).ae(sin(0.25))\\n    assert ellipfun('cd', 0.25, 0).ae(cos(0.25))\\n    assert ellipfun('cs', 0.25, 0).ae(cot(0.25))\\n    assert ellipfun('dc', 0.25, 0).ae(sec(0.25))\\n    assert ellipfun('ds', 0.25, 0).ae(csc(0.25))\\n    assert ellipfun('sn', 0.25, 1).ae(tanh(0.25))\\n    assert ellipfun('cn', 0.25, 1).ae(sech(0.25))\\n    assert ellipfun('dn', 0.25, 1).ae(sech(0.25))\\n    assert ellipfun('ns', 0.25, 1).ae(coth(0.25))\\n    assert ellipfun('nc', 0.25, 1).ae(cosh(0.25))\\n    assert ellipfun('nd', 0.25, 1).ae(cosh(0.25))\\n    assert ellipfun('sc', 0.25, 1).ae(sinh(0.25))\\n    assert ellipfun('sd', 0.25, 1).ae(sinh(0.25))\\n    assert ellipfun('cd', 0.25, 1).ae(1)\\n    assert ellipfun('cs', 0.25, 1).ae(csch(0.25))\\n    assert ellipfun('dc', 0.25, 1).ae(1)\\n    assert ellipfun('ds', 0.25, 1).ae(csch(0.25))\\n    assert ellipfun('sn', 0.25, 0.5).ae(0.24615967096986145833)\\n    assert ellipfun('cn', 0.25, 0.5).ae(0.96922928989378439337)\\n    assert ellipfun('dn', 0.25, 0.5).ae(0.98473484156599474563)\\n    assert ellipfun('ns', 0.25, 0.5).ae(4.0624038700573130369)\\n    assert ellipfun('nc', 0.25, 0.5).ae(1.0317476065024692949)\\n    assert ellipfun('nd', 0.25, 0.5).ae(1.0155017958029488665)\\n    assert ellipfun('sc', 0.25, 0.5).ae(0.25397465134058993408)\\n    assert ellipfun('sd', 0.25, 0.5).ae(0.24997558792415733063)\\n    assert ellipfun('cd', 0.25, 0.5).ae(0.98425408443195497052)\\n    assert ellipfun('cs', 0.25, 0.5).ae(3.9374008182374110826)\\n    assert ellipfun('dc', 0.25, 0.5).ae(1.0159978158253033913)\\n    assert ellipfun('ds', 0.25, 0.5).ae(4.0003906313579720593)\\n\\n\\n\\n\\ndef test_calculate_nome():\\n    mp.dps = 100\\n\\n    q = calculate_nome(zero)\\n    assert(q == zero)\\n\\n    mp.dps = 25\\n    # used Mathematica's EllipticNomeQ[m]\\n    math1 = [(mpf(1)/10, mpf('0.006584651553858370274473060')),\\n             (mpf(2)/10, mpf('0.01394285727531826872146409')),\\n             (mpf(3)/10, mpf('0.02227743615715350822901627')),\\n             (mpf(4)/10, mpf('0.03188334731336317755064299')),\\n             (mpf(5)/10, mpf('0.04321391826377224977441774')),\\n             (mpf(6)/10, mpf('0.05702025781460967637754953')),\\n             (mpf(7)/10, mpf('0.07468994353717944761143751')),\\n             (mpf(8)/10, mpf('0.09927369733882489703607378')),\\n             (mpf(9)/10, mpf('0.1401731269542615524091055')),\\n             (mpf(9)/10, mpf('0.1401731269542615524091055'))]\\n\\n    for i in math1:\\n        m = i[0]\\n        q = calculate_nome(sqrt(m))\\n        assert q.ae(i[1])\\n\\n    mp.dps = 15\\n\\ndef test_jtheta():\\n    mp.dps = 25\\n\\n    z = q = zero\\n    for n in range(1,5):\\n        value = jtheta(n, z, q)\\n        assert(value == (n-1)//2)\\n\\n    for q in [one, mpf(2)]:\\n        for n in range(1,5):\\n            pytest.raises(ValueError, lambda: jtheta(n, z, q))\\n\\n    z = one/10\\n    q = one/11\\n\\n    # Mathematical N[EllipticTheta[1, 1/10, 1/11], 25]\\n    res = mpf('0.1069552990104042681962096')\\n    result = jtheta(1, z, q)\\n    assert(result.ae(res))\\n\\n    # Mathematica N[EllipticTheta[2, 1/10, 1/11], 25]\\n    res = mpf('1.101385760258855791140606')\\n    result = jtheta(2, z, q)\\n    assert(result.ae(res))\\n\\n    # Mathematica N[EllipticTheta[3, 1/10, 1/11], 25]\\n    res = mpf('1.178319743354331061795905')\\n    result = jtheta(3, z, q)\\n    assert(result.ae(res))\\n\\n    # Mathematica N[EllipticTheta[4, 1/10, 1/11], 25]\\n    res = mpf('0.8219318954665153577314573')\\n    result = jtheta(4, z, q)\\n    assert(result.ae(res))\\n\\n    # test for sin zeros for jtheta(1, z, q)\\n    # test for cos zeros for jtheta(2, z, q)\\n    z1 = pi\\n    z2 = pi/2\\n    for i in range(10):\\n        qstring = str(random.random())\\n        q = mpf(qstring)\\n        result = jtheta(1, z1, q)\\n        assert(result.ae(0))\\n        result = jtheta(2, z2, q)\\n        assert(result.ae(0))\\n    mp.dps = 15\\n\\n\\ndef test_jtheta_issue_79():\\n    # near the circle of covergence |q| = 1 the convergence slows\\n    # down; for |q| > Q_LIM the theta functions raise ValueError\\n    mp.dps = 30\\n    mp.dps += 30\\n    q = mpf(6)/10 - one/10**6 - mpf(8)/10 * j\\n    mp.dps -= 30\\n    # Mathematica run first\\n    # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 2000]\\n    # then it works:\\n    # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 30]\\n    res = mpf('32.0031009628901652627099524264') + \\\\\\n          mpf('16.6153027998236087899308935624') * j\\n    result = jtheta(3, 1, q)\\n    # check that for abs(q) > Q_LIM a ValueError exception is raised\\n    mp.dps += 30\\n    q = mpf(6)/10 - one/10**7 - mpf(8)/10 * j\\n    mp.dps -= 30\\n    pytest.raises(ValueError, lambda: jtheta(3, 1, q))\\n\\n    # bug reported in issue 79\\n    mp.dps = 100\\n    z = (1+j)/3\\n    q = mpf(368983957219251)/10**15 + mpf(636363636363636)/10**15 * j\\n    # Mathematica N[EllipticTheta[1, z, q], 35]\\n    res = mpf('2.4439389177990737589761828991467471') + \\\\\\n          mpf('0.5446453005688226915290954851851490') *j\\n    mp.dps = 30\\n    result = jtheta(1, z, q)\\n    assert(result.ae(res))\\n    mp.dps = 80\\n    z = 3 + 4*j\\n    q = 0.5 + 0.5*j\\n    r1 = jtheta(1, z, q)\\n    mp.dps = 15\\n    r2 = jtheta(1, z, q)\\n    assert r1.ae(r2)\\n    mp.dps = 80\\n    z = 3 + j\\n    q1 = exp(j*3)\\n    # longer test\\n    # for n in range(1, 6)\\n    for n in range(1, 2):\\n        mp.dps = 80\\n        q = q1*(1 - mpf(1)/10**n)\\n        r1 = jtheta(1, z, q)\\n        mp.dps = 15\\n        r2 = jtheta(1, z, q)\\n    assert r1.ae(r2)\\n    mp.dps = 15\\n    # issue 79 about high derivatives\\n    assert jtheta(3, 4.5, 0.25, 9).ae(1359.04892680683)\\n    assert jtheta(3, 4.5, 0.25, 50).ae(-6.14832772630905e+33)\\n    mp.dps = 50\\n    r = jtheta(3, 4.5, 0.25, 9)\\n    assert r.ae('1359.048926806828939547859396600218966947753213803')\\n    r = jtheta(3, 4.5, 0.25, 50)\\n    assert r.ae('-6148327726309051673317975084654262.4119215720343656')\\n\\ndef test_jtheta_identities():\\n    \\\"\\\"\\\"\\n    Tests the some of the jacobi identidies found in Abramowitz,\\n    Sec. 16.28, Pg. 576. The identities are tested to 1 part in 10^98.\\n    \\\"\\\"\\\"\\n    mp.dps = 110\\n    eps1 = ldexp(eps, 30)\\n\\n    for i in range(10):\\n        qstring = str(random.random())\\n        q = mpf(qstring)\\n\\n        zstring = str(10*random.random())\\n        z = mpf(zstring)\\n        # Abramowitz 16.28.1\\n        # v_1(z, q)**2 * v_4(0, q)**2 =   v_3(z, q)**2 * v_2(0, q)**2\\n        #                               - v_2(z, q)**2 * v_3(0, q)**2\\n        term1 = (jtheta(1, z, q)**2) * (jtheta(4, zero, q)**2)\\n        term2 = (jtheta(3, z, q)**2) * (jtheta(2, zero, q)**2)\\n        term3 = (jtheta(2, z, q)**2) * (jtheta(3, zero, q)**2)\\n        equality = term1 - term2 + term3\\n        assert(equality.ae(0, eps1))\\n\\n        zstring = str(100*random.random())\\n        z = mpf(zstring)\\n        # Abramowitz 16.28.2\\n        # v_2(z, q)**2 * v_4(0, q)**2 =   v_4(z, q)**2 * v_2(0, q)**2\\n        #                               - v_1(z, q)**2 * v_3(0, q)**2\\n        term1 = (jtheta(2, z, q)**2) * (jtheta(4, zero, q)**2)\\n        term2 = (jtheta(4, z, q)**2) * (jtheta(2, zero, q)**2)\\n        term3 = (jtheta(1, z, q)**2) * (jtheta(3, zero, q)**2)\\n        equality = term1 - term2 + term3\\n        assert(equality.ae(0, eps1))\\n\\n        # Abramowitz 16.28.3\\n        # v_3(z, q)**2 * v_4(0, q)**2 =   v_4(z, q)**2 * v_3(0, q)**2\\n        #                               - v_1(z, q)**2 * v_2(0, q)**2\\n        term1 = (jtheta(3, z, q)**2) * (jtheta(4, zero, q)**2)\\n        term2 = (jtheta(4, z, q)**2) * (jtheta(3, zero, q)**2)\\n        term3 = (jtheta(1, z, q)**2) * (jtheta(2, zero, q)**2)\\n        equality = term1 - term2 + term3\\n        assert(equality.ae(0, eps1))\\n\\n        # Abramowitz 16.28.4\\n        # v_4(z, q)**2 * v_4(0, q)**2 =   v_3(z, q)**2 * v_3(0, q)**2\\n        #                               - v_2(z, q)**2 * v_2(0, q)**2\\n        term1 = (jtheta(4, z, q)**2) * (jtheta(4, zero, q)**2)\\n        term2 = (jtheta(3, z, q)**2) * (jtheta(3, zero, q)**2)\\n        term3 = (jtheta(2, z, q)**2) * (jtheta(2, zero, q)**2)\\n        equality = term1 - term2 + term3\\n        assert(equality.ae(0, eps1))\\n\\n        # Abramowitz 16.28.5\\n        # v_2(0, q)**4 + v_4(0, q)**4 == v_3(0, q)**4\\n        term1 = (jtheta(2, zero, q))**4\\n        term2 = (jtheta(4, zero, q))**4\\n        term3 = (jtheta(3, zero, q))**4\\n        equality = term1 + term2 - term3\\n        assert(equality.ae(0, eps1))\\n    mp.dps = 15\\n\\ndef test_jtheta_complex():\\n    mp.dps = 30\\n    z = mpf(1)/4 + j/8\\n    q = mpf(1)/3 + j/7\\n    # Mathematica N[EllipticTheta[1, 1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('0.31618034835986160705729105731678285') + \\\\\\n          mpf('0.07542013825835103435142515194358975') * j\\n    r = jtheta(1, z, q)\\n    assert(mpc_ae(r, res))\\n\\n    # Mathematica N[EllipticTheta[2, 1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('1.6530986428239765928634711417951828') + \\\\\\n          mpf('0.2015344864707197230526742145361455') * j\\n    r = jtheta(2, z, q)\\n    assert(mpc_ae(r, res))\\n\\n    # Mathematica N[EllipticTheta[3, 1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('1.6520564411784228184326012700348340') + \\\\\\n          mpf('0.1998129119671271328684690067401823') * j\\n    r = jtheta(3, z, q)\\n    assert(mpc_ae(r, res))\\n\\n    # Mathematica N[EllipticTheta[4, 1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('0.37619082382228348252047624089973824') - \\\\\\n          mpf('0.15623022130983652972686227200681074') * j\\n    r = jtheta(4, z, q)\\n    assert(mpc_ae(r, res))\\n\\n    # check some theta function identities\\n    mp.dos = 100\\n    z = mpf(1)/4 + j/8\\n    q = mpf(1)/3 + j/7\\n    mp.dps += 10\\n    a = [0,0, jtheta(2, 0, q), jtheta(3, 0, q), jtheta(4, 0, q)]\\n    t = [0, jtheta(1, z, q), jtheta(2, z, q), jtheta(3, z, q), jtheta(4, z, q)]\\n    r = [(t[2]*a[4])**2 - (t[4]*a[2])**2 + (t[1] *a[3])**2,\\n        (t[3]*a[4])**2 - (t[4]*a[3])**2 + (t[1] *a[2])**2,\\n        (t[1]*a[4])**2 - (t[3]*a[2])**2 + (t[2] *a[3])**2,\\n        (t[4]*a[4])**2 - (t[3]*a[3])**2 + (t[2] *a[2])**2,\\n        a[2]**4 + a[4]**4 - a[3]**4]\\n    mp.dps -= 10\\n    for x in r:\\n        assert(mpc_ae(x, mpc(0)))\\n    mp.dps = 15\\n\\ndef test_djtheta():\\n    mp.dps = 30\\n\\n    z = one/7 + j/3\\n    q = one/8 + j/5\\n    # Mathematica N[EllipticThetaPrime[1, 1/7 + I/3, 1/8 + I/5], 35]\\n    res = mpf('1.5555195883277196036090928995803201') - \\\\\\n          mpf('0.02439761276895463494054149673076275') * j\\n    result = jtheta(1, z, q, 1)\\n    assert(mpc_ae(result, res))\\n\\n    # Mathematica N[EllipticThetaPrime[2, 1/7 + I/3, 1/8 + I/5], 35]\\n    res = mpf('0.19825296689470982332701283509685662') - \\\\\\n          mpf('0.46038135182282106983251742935250009') * j\\n    result = jtheta(2, z, q, 1)\\n    assert(mpc_ae(result, res))\\n\\n    # Mathematica N[EllipticThetaPrime[3, 1/7 + I/3, 1/8 + I/5], 35]\\n    res = mpf('0.36492498415476212680896699407390026') - \\\\\\n          mpf('0.57743812698666990209897034525640369') * j\\n    result = jtheta(3, z, q, 1)\\n    assert(mpc_ae(result, res))\\n\\n    # Mathematica N[EllipticThetaPrime[4, 1/7 + I/3, 1/8 + I/5], 35]\\n    res = mpf('-0.38936892528126996010818803742007352') + \\\\\\n          mpf('0.66549886179739128256269617407313625') * j\\n    result = jtheta(4, z, q, 1)\\n    assert(mpc_ae(result, res))\\n\\n    for i in range(10):\\n        q = (one*random.random() + j*random.random())/2\\n        # identity in Wittaker, Watson &21.41\\n        a = jtheta(1, 0, q, 1)\\n        b = jtheta(2, 0, q)*jtheta(3, 0, q)*jtheta(4, 0, q)\\n        assert(a.ae(b))\\n\\n    # test higher derivatives\\n    mp.dps = 20\\n    for q,z in [(one/3, one/5), (one/3 + j/8, one/5),\\n        (one/3, one/5 + j/8), (one/3 + j/7, one/5 + j/8)]:\\n        for n in [1, 2, 3, 4]:\\n            r = jtheta(n, z, q, 2)\\n            r1 = diff(lambda zz: jtheta(n, zz, q), z, n=2)\\n            assert r.ae(r1)\\n            r = jtheta(n, z, q, 3)\\n            r1 = diff(lambda zz: jtheta(n, zz, q), z, n=3)\\n            assert r.ae(r1)\\n\\n    # identity in Wittaker, Watson &21.41\\n    q = one/3\\n    z = zero\\n    a = [0]*5\\n    a[1] = jtheta(1, z, q, 3)/jtheta(1, z, q, 1)\\n    for n in [2,3,4]:\\n        a[n] = jtheta(n, z, q, 2)/jtheta(n, z, q)\\n    equality = a[2] + a[3] + a[4] - a[1]\\n    assert(equality.ae(0))\\n    mp.dps = 15\\n\\ndef test_jsn():\\n    \\\"\\\"\\\"\\n    Test some special cases of the sn(z, q) function.\\n    \\\"\\\"\\\"\\n    mp.dps = 100\\n\\n    # trival case\\n    result = jsn(zero, zero)\\n    assert(result == zero)\\n\\n    # Abramowitz Table 16.5\\n    #\\n    # sn(0, m) = 0\\n\\n    for i in range(10):\\n        qstring = str(random.random())\\n        q = mpf(qstring)\\n\\n        equality = jsn(zero, q)\\n        assert(equality.ae(0))\\n\\n    # Abramowitz Table 16.6.1\\n    #\\n    # sn(z, 0) = sin(z), m == 0\\n    #\\n    # sn(z, 1) = tanh(z), m == 1\\n    #\\n    # It would be nice to test these, but I find that they run\\n    # in to numerical trouble.  I'm currently treating as a boundary\\n    # case for sn function.\\n\\n    mp.dps = 25\\n    arg = one/10\\n    #N[JacobiSN[1/10, 2^-100], 25]\\n    res = mpf('0.09983341664682815230681420')\\n    m = ldexp(one, -100)\\n    result = jsn(arg, m)\\n    assert(result.ae(res))\\n\\n    # N[JacobiSN[1/10, 1/10], 25]\\n    res = mpf('0.09981686718599080096451168')\\n    result = jsn(arg, arg)\\n    assert(result.ae(res))\\n    mp.dps = 15\\n\\ndef test_jcn():\\n    \\\"\\\"\\\"\\n    Test some special cases of the cn(z, q) function.\\n    \\\"\\\"\\\"\\n    mp.dps = 100\\n\\n    # Abramowitz Table 16.5\\n    # cn(0, q) = 1\\n    qstring = str(random.random())\\n    q = mpf(qstring)\\n    cn = jcn(zero, q)\\n    assert(cn.ae(one))\\n\\n    # Abramowitz Table 16.6.2\\n    #\\n    # cn(u, 0) = cos(u), m == 0\\n    #\\n    # cn(u, 1) = sech(z), m == 1\\n    #\\n    # It would be nice to test these, but I find that they run\\n    # in to numerical trouble.  I'm currently treating as a boundary\\n    # case for cn function.\\n\\n    mp.dps = 25\\n    arg = one/10\\n    m = ldexp(one, -100)\\n    #N[JacobiCN[1/10, 2^-100], 25]\\n    res = mpf('0.9950041652780257660955620')\\n    result = jcn(arg, m)\\n    assert(result.ae(res))\\n\\n    # N[JacobiCN[1/10, 1/10], 25]\\n    res = mpf('0.9950058256237368748520459')\\n    result = jcn(arg, arg)\\n    assert(result.ae(res))\\n    mp.dps = 15\\n\\ndef test_jdn():\\n    \\\"\\\"\\\"\\n    Test some special cases of the dn(z, q) function.\\n    \\\"\\\"\\\"\\n    mp.dps = 100\\n\\n    # Abramowitz Table 16.5\\n    # dn(0, q) = 1\\n    mstring = str(random.random())\\n    m = mpf(mstring)\\n\\n    dn = jdn(zero, m)\\n    assert(dn.ae(one))\\n\\n    mp.dps = 25\\n    # N[JacobiDN[1/10, 1/10], 25]\\n    res = mpf('0.9995017055025556219713297')\\n    arg = one/10\\n    result = jdn(arg, arg)\\n    assert(result.ae(res))\\n    mp.dps = 15\\n\\n\\ndef test_sn_cn_dn_identities():\\n    \\\"\\\"\\\"\\n    Tests the some of the jacobi elliptic function identities found\\n    on Mathworld. Haven't found in Abramowitz.\\n    \\\"\\\"\\\"\\n    mp.dps = 100\\n    N = 5\\n    for i in range(N):\\n        qstring = str(random.random())\\n        q = mpf(qstring)\\n        zstring = str(100*random.random())\\n        z = mpf(zstring)\\n\\n        # MathWorld\\n        # sn(z, q)**2 + cn(z, q)**2 == 1\\n        term1 = jsn(z, q)**2\\n        term2 = jcn(z, q)**2\\n        equality = one - term1 - term2\\n        assert(equality.ae(0))\\n\\n    # MathWorld\\n    # k**2 * sn(z, m)**2 + dn(z, m)**2 == 1\\n    for i in range(N):\\n        mstring = str(random.random())\\n        m = mpf(qstring)\\n        k = m.sqrt()\\n        zstring = str(10*random.random())\\n        z = mpf(zstring)\\n        term1 = k**2 * jsn(z, m)**2\\n        term2 = jdn(z, m)**2\\n        equality = one - term1 - term2\\n        assert(equality.ae(0))\\n\\n\\n    for i in range(N):\\n        mstring = str(random.random())\\n        m = mpf(mstring)\\n        k = m.sqrt()\\n        zstring = str(random.random())\\n        z = mpf(zstring)\\n\\n        # MathWorld\\n        # k**2 * cn(z, m)**2 + (1 - k**2) = dn(z, m)**2\\n        term1 = k**2 * jcn(z, m)**2\\n        term2 = 1 - k**2\\n        term3 = jdn(z, m)**2\\n        equality = term3 - term1 - term2\\n        assert(equality.ae(0))\\n\\n        K = ellipk(k**2)\\n        # Abramowitz Table 16.5\\n        # sn(K, m) = 1; K is K(k), first complete elliptic integral\\n        r = jsn(K, m)\\n        assert(r.ae(one))\\n\\n        # Abramowitz Table 16.5\\n        # cn(K, q) = 0; K is K(k), first complete elliptic integral\\n        equality = jcn(K, m)\\n        assert(equality.ae(0))\\n\\n        # Abramowitz Table 16.6.3\\n        # dn(z, 0) = 1, m == 0\\n        z = m\\n        value = jdn(z, zero)\\n        assert(value.ae(one))\\n\\n    mp.dps = 15\\n\\ndef test_sn_cn_dn_complex():\\n    mp.dps = 30\\n    # N[JacobiSN[1/4 + I/8, 1/3 + I/7], 35] in Mathematica\\n    res = mpf('0.2495674401066275492326652143537') + \\\\\\n          mpf('0.12017344422863833381301051702823') * j\\n    u = mpf(1)/4 + j/8\\n    m = mpf(1)/3 + j/7\\n    r = jsn(u, m)\\n    assert(mpc_ae(r, res))\\n\\n    #N[JacobiCN[1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('0.9762691700944007312693721148331') - \\\\\\n          mpf('0.0307203994181623243583169154824')*j\\n    r = jcn(u, m)\\n    #assert r.real.ae(res.real)\\n    #assert r.imag.ae(res.imag)\\n    assert(mpc_ae(r, res))\\n\\n    #N[JacobiDN[1/4 + I/8, 1/3 + I/7], 35]\\n    res = mpf('0.99639490163039577560547478589753039') - \\\\\\n          mpf('0.01346296520008176393432491077244994')*j\\n    r = jdn(u, m)\\n    assert(mpc_ae(r, res))\\n    mp.dps = 15\\n\\ndef test_elliptic_integrals():\\n    # Test cases from Carlson's paper\\n    mp.dps = 15\\n    assert elliprd(0,2,1).ae(1.7972103521033883112)\\n    assert elliprd(2,3,4).ae(0.16510527294261053349)\\n    assert elliprd(j,-j,2).ae(0.65933854154219768919)\\n    assert elliprd(0,j,-j).ae(1.2708196271909686299 + 2.7811120159520578777j)\\n    assert elliprd(0,j-1,j).ae(-1.8577235439239060056 - 0.96193450888838559989j)\\n    assert elliprd(-2-j,-j,-1+j).ae(1.8249027393703805305 - 1.2218475784827035855j)\\n    # extra test cases\\n    assert elliprg(0,0,0) == 0\\n    assert elliprg(0,0,16).ae(2)\\n    assert elliprg(0,16,0).ae(2)\\n    assert elliprg(16,0,0).ae(2)\\n    assert elliprg(1,4,0).ae(1.2110560275684595248036)\\n    assert elliprg(1,0,4).ae(1.2110560275684595248036)\\n    assert elliprg(0,4,1).ae(1.2110560275684595248036)\\n    # should be symmetric -- fixes a bug present in the paper\\n    x,y,z = 1,1j,-1+1j\\n    assert elliprg(x,y,z).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n    assert elliprg(x,z,y).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n    assert elliprg(y,x,z).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n    assert elliprg(y,z,x).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n    assert elliprg(z,x,y).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n    assert elliprg(z,y,x).ae(0.64139146875812627545 + 0.58085463774808290907j)\\n\\n    for n in [5, 15, 30, 60, 100]:\\n        mp.dps = n\\n        assert elliprf(1,2,0).ae('1.3110287771460599052324197949455597068413774757158115814084108519003952935352071251151477664807145467230678763')\\n        assert elliprf(0.5,1,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871')\\n        assert elliprf(j,-j,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871')\\n        assert elliprf(j-1,j,0).ae(mpc('0.79612586584233913293056938229563057846592264089185680214929401744498956943287031832657642790719940442165621412',\\n            '-1.2138566698364959864300942567386038975419875860741507618279563735753073152507112254567291141460317931258599889'))\\n        assert elliprf(2,3,4).ae('0.58408284167715170669284916892566789240351359699303216166309375305508295130412919665541330837704050454472379308')\\n        assert elliprf(j,-j,2).ae('1.0441445654064360931078658361850779139591660747973017593275012615517220315993723776182276555339288363064476126')\\n        assert elliprf(j-1,j,1-j).ae(mpc('0.93912050218619371196624617169781141161485651998254431830645241993282941057500174238125105410055253623847335313',\\n            '-0.53296252018635269264859303449447908970360344322834582313172115220559316331271520508208025270300138589669326136'))\\n        assert elliprc(0,0.25).ae(+pi)\\n        assert elliprc(2.25,2).ae(+ln2)\\n        assert elliprc(0,j).ae(mpc('1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532',\\n            '-1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532'))\\n        assert elliprc(-j,j).ae(mpc('1.2260849569072198222319655083097718755633725139745941606203839524036426936825652935738621522906572884239069297',\\n            '-0.34471136988767679699935618332997956653521218571295874986708834375026550946053920574015526038040124556716711353'))\\n        assert elliprc(0.25,-2).ae(ln2/3)\\n        assert elliprc(j,-1).ae(mpc('0.77778596920447389875196055840799837589537035343923012237628610795937014001905822029050288316217145443865649819',\\n            '0.1983248499342877364755170948292130095921681309577950696116251029742793455964385947473103628983664877025779304'))\\n        assert elliprj(0,1,2,3).ae('0.77688623778582332014190282640545501102298064276022952731669118325952563819813258230708177398475643634103990878')\\n        assert elliprj(2,3,4,5).ae('0.14297579667156753833233879421985774801466647854232626336218889885463800128817976132826443904216546421431528308')\\n        assert elliprj(2,3,4,-1+j).ae(mpc('0.13613945827770535203521374457913768360237593025944342652613569368333226052158214183059386307242563164036672709',\\n            '-0.38207561624427164249600936454845112611060375760094156571007648297226090050927156176977091273224510621553615189'))\\n        assert elliprj(j,-j,0,2).ae('1.6490011662710884518243257224860232300246792717163891216346170272567376981346412066066050103935109581019055806')\\n        assert elliprj(-1+j,-1-j,1,2).ae('0.94148358841220238083044612133767270187474673547917988681610772381758628963408843935027667916713866133196845063')\\n        assert elliprj(j,-j,0,1-j).ae(mpc('1.8260115229009316249372594065790946657011067182850435297162034335356430755397401849070610280860044610878657501',\\n            '1.2290661908643471500163617732957042849283739403009556715926326841959667290840290081010472716420690899886276961'))\\n        assert elliprj(-1+j,-1-j,1,-3+j).ae(mpc('-0.61127970812028172123588152373622636829986597243716610650831553882054127570542477508023027578037045504958619422',\\n            '-1.0684038390006807880182112972232562745485871763154040245065581157751693730095703406209466903752930797510491155'))\\n        assert elliprj(-1+j,-2-j,-j,-1+j).ae(mpc('1.8249027393703805304622013339009022294368078659619988943515764258335975852685224202567854526307030593012768954',\\n            '-1.2218475784827035854568450371590419833166777535029296025352291308244564398645467465067845461070602841312456831'))\\n\\n        assert elliprg(0,16,16).ae(+pi)\\n        assert elliprg(2,3,4).ae('1.7255030280692277601061148835701141842692457170470456590515892070736643637303053506944907685301315299153040991')\\n        assert elliprg(0,j,-j).ae('0.42360654239698954330324956174109581824072295516347109253028968632986700241706737986160014699730561497106114281')\\n        assert elliprg(j-1,j,0).ae(mpc('0.44660591677018372656731970402124510811555212083508861036067729944477855594654762496407405328607219895053798354',\\n            '0.70768352357515390073102719507612395221369717586839400605901402910893345301718731499237159587077682267374159282'))\\n        assert elliprg(-j,j-1,j).ae(mpc('0.36023392184473309033675652092928695596803358846377334894215349632203382573844427952830064383286995172598964266',\\n            '0.40348623401722113740956336997761033878615232917480045914551915169013722542827052849476969199578321834819903921'))\\n        assert elliprg(0, mpf('0.0796'), 4).ae('1.0284758090288040009838871385180217366569777284430590125081211090574701293154645750017813190805144572673802094')\\n    mp.dps = 15\\n\\n    # more test cases for the branch of ellippi / elliprj\\n    assert elliprj(-1-0.5j, -10-6j, -10-3j, -5+10j).ae(0.128470516743927699 + 0.102175950778504625j, abs_eps=1e-8)\\n    assert elliprj(1.987, 4.463 - 1.614j, 0, -3.965).ae(-0.341575118513811305 - 0.394703757004268486j, abs_eps=1e-8)\\n    assert elliprj(0.3068, -4.037+0.632j, 1.654, -0.9609).ae(-1.14735199581485639 - 0.134450158867472264j, abs_eps=1e-8)\\n    assert elliprj(0.3068, -4.037-0.632j, 1.654, -0.9609).ae(1.758765901861727 - 0.161002343366626892j, abs_eps=1e-5)\\n    assert elliprj(0.3068, -4.037+0.0632j, 1.654, -0.9609).ae(-1.17157627949475577 - 0.069182614173988811j, abs_eps=1e-8)\\n    assert elliprj(0.3068, -4.037+0.00632j, 1.654, -0.9609).ae(-1.17337595670549633 - 0.0623069224526925j, abs_eps=1e-8)\\n\\n    # these require accurate integration\\n    assert elliprj(0.3068, -4.037-0.0632j, 1.654, -0.9609).ae(1.77940452391261626 + 0.0388711305592447234j)\\n    assert elliprj(0.3068, -4.037-0.00632j, 1.654, -0.9609).ae(1.77806722756403055 + 0.0592749824572262329j)\\n    # issue #571\\n    assert ellippi(2.1 + 0.94j, 2.3 + 0.98j, 2.5 + 0.01j).ae(-0.40652414240811963438 + 2.1547659461404749309j)\\n\\n    assert ellippi(2.0-1.0j, 2.0+1.0j).ae(1.8578723151271115 - 1.18642180609983531j)\\n    assert ellippi(2.0-0.5j, 0.5+1.0j).ae(0.936761970766645807 - 1.61876787838890786j)\\n    assert ellippi(2.0, 1.0+1.0j).ae(0.999881420735506708 - 2.4139272867045391j)\\n    assert ellippi(2.0+1.0j, 2.0-1.0j).ae(1.8578723151271115 + 1.18642180609983531j)\\n    assert ellippi(2.0+1.0j, 2.0).ae(2.78474654927885845 + 2.02204728966993314j)\\n\\ndef test_issue_238():\\n    assert isnan(qfrom(m=nan))\\n\\n\\nfrom mpmath import *\\n\\ndef test_sumem():\\n    mp.dps = 15\\n    assert sumem(lambda k: 1/k**2.5, [50, 100]).ae(0.0012524505324784962)\\n    assert sumem(lambda k: k**4 + 3*k + 1, [10, 100]).ae(2050333103)\\n\\ndef test_nsum():\\n    mp.dps = 15\\n    assert nsum(lambda x: x**2, [1, 3]) == 14\\n    assert nsum(lambda k: 1/factorial(k), [0, inf]).ae(e)\\n    assert nsum(lambda k: (-1)**(k+1) / k, [1, inf]).ae(log(2))\\n    assert nsum(lambda k: (-1)**(k+1) / k**2, [1, inf]).ae(pi**2 / 12)\\n    assert nsum(lambda k: (-1)**k / log(k), [2, inf]).ae(0.9242998972229388)\\n    assert nsum(lambda k: 1/k**2, [1, inf]).ae(pi**2 / 6)\\n    assert nsum(lambda k: 2**k/fac(k), [0, inf]).ae(exp(2))\\n    assert nsum(lambda k: 1/k**2, [4, inf], method='e').ae(0.2838229557371153)\\n    assert abs(fp.nsum(lambda k: 1/k**4, [1, fp.inf]) - 1.082323233711138) < 1e-5\\n    assert abs(fp.nsum(lambda k: 1/k**4, [1, fp.inf], method='e') - 1.082323233711138) < 1e-4\\n\\ndef test_nprod():\\n    mp.dps = 15\\n    assert nprod(lambda k: exp(1/k**2), [1,inf], method='r').ae(exp(pi**2/6))\\n    assert nprod(lambda x: x**2, [1, 3]) == 36\\n\\ndef test_fsum():\\n    mp.dps = 15\\n    assert fsum([]) == 0\\n    assert fsum([-4]) == -4\\n    assert fsum([2,3]) == 5\\n    assert fsum([1e-100,1]) == 1\\n    assert fsum([1,1e-100]) == 1\\n    assert fsum([1e100,1]) == 1e100\\n    assert fsum([1,1e100]) == 1e100\\n    assert fsum([1e-100,0]) == 1e-100\\n    assert fsum([1e-100,1e100,1e-100]) == 1e100\\n    assert fsum([2,1+1j,1]) == 4+1j\\n    assert fsum([2,inf,3]) == inf\\n    assert fsum([2,-1], absolute=1) == 3\\n    assert fsum([2,-1], squared=1) == 5\\n    assert fsum([1,1+j], squared=1) == 1+2j\\n    assert fsum([1,3+4j], absolute=1) == 6\\n    assert fsum([1,2+3j], absolute=1, squared=1) == 14\\n    assert isnan(fsum([inf,-inf]))\\n    assert fsum([inf,-inf], absolute=1) == inf\\n    assert fsum([inf,-inf], squared=1) == inf\\n    assert fsum([inf,-inf], absolute=1, squared=1) == inf\\n    assert iv.fsum([1,mpi(2,3)]) == mpi(3,4)\\n\\ndef test_fprod():\\n    mp.dps = 15\\n    assert fprod([]) == 1\\n    assert fprod([2,3]) == 6\\n\\n\\nimport pytest\\nfrom mpmath import *\\n\\ndef test_approximation():\\n    mp.dps = 15\\n    f = lambda x: cos(2-2*x)/x\\n    p, err = chebyfit(f, [2, 4], 8, error=True)\\n    assert err < 1e-5\\n    for i in range(10):\\n        x = 2 + i/5.\\n        assert abs(polyval(p, x) - f(x)) < err\\n\\ndef test_limits():\\n    mp.dps = 15\\n    assert limit(lambda x: (x-sin(x))/x**3, 0).ae(mpf(1)/6)\\n    assert limit(lambda n: (1+1/n)**n, inf).ae(e)\\n\\ndef test_polyval():\\n    assert polyval([], 3) == 0\\n    assert polyval([0], 3) == 0\\n    assert polyval([5], 3) == 5\\n    # 4x^3 - 2x + 5\\n    p = [4, 0, -2, 5]\\n    assert polyval(p,4) == 253\\n    assert polyval(p,4,derivative=True) == (253, 190)\\n\\ndef test_polyroots():\\n    p = polyroots([1,-4])\\n    assert p[0].ae(4)\\n    p, q = polyroots([1,2,3])\\n    assert p.ae(-1 - sqrt(2)*j)\\n    assert q.ae(-1 + sqrt(2)*j)\\n    #this is not a real test, it only tests a specific case\\n    assert polyroots([1]) == []\\n    pytest.raises(ValueError, lambda: polyroots([0]))\\n\\ndef test_polyroots_legendre():\\n    n = 64\\n    coeffs = [11975573020964041433067793888190275875, 0,\\n        -190100434726484311252477736051902332000, 0,\\n        1437919688271127330313741595496589239248, 0,\\n        -6897338342113537600691931230430793911840, 0,\\n        23556405536185284408974715545252277554280, 0,\\n        -60969520211303089058522793175947071316960, 0,\\n        124284021969194758465450309166353645376880, 0,\\n        -204721258548015217049921875719981284186016, 0,\\n        277415422258095841688223780704620656114900, 0,\\n        -313237834141273382807123548182995095192800, 0,\\n        297432255354328395601259515935229287637200, 0,\\n        -239057700565161140389797367947941296605600, 0,\\n        163356095386193445933028201431093219347160, 0,\\n        -95158890516229191805647495979277603503200, 0,\\n        47310254620162038075933656063247634556400, 0,\\n        -20071017111583894941305187420771723751200, 0,\\n        7255051932731034189479516844750603752850, 0,\\n        -2228176940331017311443863996901733412640, 0,\\n        579006552594977616773047095969088431600, 0,\\n        -126584428502545713788439446082310831200, 0,\\n        23112325428835593809686977515028663000, 0,\\n        -3491517141958743235617737161547844000, 0,\\n        431305058712550634988073414073557200, 0,\\n        -42927166660756742088912492757452000, 0,\\n        3378527005707706553294038781836500, 0,\\n        -205277590220215081719131470288800, 0,\\n        9330799555464321896324157740400, 0,\\n        -304114948474392713657972548576, 0,\\n        6695289961520387531608984680, 0,\\n        -91048139350447232095702560, 0,\\n        659769125727878493447120, 0,\\n        -1905929106580294155360, 0,\\n        916312070471295267]\\n\\n    with mp.workdps(3):\\n        with pytest.raises(mp.NoConvergence):\\n            polyroots(coeffs, maxsteps=5, cleanup=True, error=False,\\n                      extraprec=n*10)\\n\\n        roots = polyroots(coeffs, maxsteps=50, cleanup=True, error=False,\\n                    extraprec=n*10)\\n        roots = [str(r) for r in roots]\\n        assert roots == \\\\\\n            ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961',\\n            '-0.946', '-0.93', '-0.911', '-0.889', '-0.866', '-0.841',\\n            '-0.813', '-0.784', '-0.753', '-0.72', '-0.685', '-0.649',\\n            '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402',\\n            '-0.357', '-0.311', '-0.265', '-0.217', '-0.17', '-0.121',\\n            '-0.073', '-0.0243', '0.0243', '0.073', '0.121', '0.17', '0.217',\\n            '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531',\\n            '0.572', '0.611', '0.649', '0.685', '0.72', '0.753', '0.784',\\n            '0.813', '0.841', '0.866', '0.889', '0.911', '0.93', '0.946',\\n            '0.961', '0.973', '0.983', '0.991', '0.996', '0.999']\\n\\ndef test_polyroots_legendre_init():\\n    extra_prec = 100\\n    coeffs = [11975573020964041433067793888190275875, 0,\\n        -190100434726484311252477736051902332000, 0,\\n        1437919688271127330313741595496589239248, 0,\\n        -6897338342113537600691931230430793911840, 0,\\n        23556405536185284408974715545252277554280, 0,\\n        -60969520211303089058522793175947071316960, 0,\\n        124284021969194758465450309166353645376880, 0,\\n        -204721258548015217049921875719981284186016, 0,\\n        277415422258095841688223780704620656114900, 0,\\n        -313237834141273382807123548182995095192800, 0,\\n        297432255354328395601259515935229287637200, 0,\\n        -239057700565161140389797367947941296605600, 0,\\n        163356095386193445933028201431093219347160, 0,\\n        -95158890516229191805647495979277603503200, 0,\\n        47310254620162038075933656063247634556400, 0,\\n        -20071017111583894941305187420771723751200, 0,\\n        7255051932731034189479516844750603752850, 0,\\n        -2228176940331017311443863996901733412640, 0,\\n        579006552594977616773047095969088431600, 0,\\n        -126584428502545713788439446082310831200, 0,\\n        23112325428835593809686977515028663000, 0,\\n        -3491517141958743235617737161547844000, 0,\\n        431305058712550634988073414073557200, 0,\\n        -42927166660756742088912492757452000, 0,\\n        3378527005707706553294038781836500, 0,\\n        -205277590220215081719131470288800, 0,\\n        9330799555464321896324157740400, 0,\\n        -304114948474392713657972548576, 0,\\n        6695289961520387531608984680, 0,\\n        -91048139350447232095702560, 0,\\n        659769125727878493447120, 0,\\n        -1905929106580294155360, 0,\\n        916312070471295267]\\n\\n    roots_init =  matrix(['-0.999', '-0.996',  '-0.991', '-0.983', '-0.973',\\n                          '-0.961', '-0.946',  '-0.93',  '-0.911', '-0.889',\\n                          '-0.866', '-0.841',  '-0.813', '-0.784', '-0.753',\\n                          '-0.72',  '-0.685',  '-0.649', '-0.611', '-0.572',\\n                          '-0.531', '-0.489',  '-0.446', '-0.402', '-0.357',\\n                          '-0.311', '-0.265',  '-0.217', '-0.17',  '-0.121',\\n                          '-0.073', '-0.0243',  '0.0243', '0.073',  '0.121',\\n                          '0.17',    '0.217',   '0.265', ' 0.311',  '0.357',\\n                          '0.402',   '0.446',   '0.489',  '0.531',  '0.572',\\n                          '0.611',   '0.649',   '0.685',  '0.72',   '0.753',\\n                          '0.784',   '0.813',   '0.841',  '0.866',  '0.889',\\n                          '0.911',   '0.93',    '0.946',  '0.961',  '0.973',\\n                          '0.983',   '0.991',   '0.996',  '0.999',  '1.0'])\\n    with mp.workdps(2*mp.dps):\\n        roots_exact = polyroots(coeffs, maxsteps=50, cleanup=True, error=False,\\n                                extraprec=2*extra_prec)\\n    with pytest.raises(mp.NoConvergence):\\n        polyroots(coeffs, maxsteps=5, cleanup=True, error=False,\\n                  extraprec=extra_prec)\\n    roots,err = polyroots(coeffs, maxsteps=5, cleanup=True, error=True,\\n                          extraprec=extra_prec,roots_init=roots_init)\\n    assert max(matrix(roots_exact)-matrix(roots).apply(abs)) < err\\n    roots1,err1 = polyroots(coeffs, maxsteps=25, cleanup=True, error=True,\\n                            extraprec=extra_prec,roots_init=roots_init[:60])\\n    assert max(matrix(roots_exact)-matrix(roots1).apply(abs)) < err1\\n\\ndef test_pade():\\n    one = mpf(1)\\n    mp.dps = 20\\n    N = 10\\n    a = [one]\\n    k = 1\\n    for i in range(1, N+1):\\n        k *= i\\n        a.append(one/k)\\n    p, q = pade(a, N//2, N//2)\\n    for x in arange(0, 1, 0.1):\\n        r = polyval(p[::-1], x)/polyval(q[::-1], x)\\n        assert(r.ae(exp(x), 1.0e-10))\\n    mp.dps = 15\\n\\ndef test_fourier():\\n    mp.dps = 15\\n    c, s = fourier(lambda x: x+1, [-1, 2], 2)\\n    #plot([lambda x: x+1, lambda x: fourierval((c, s), [-1, 2], x)], [-1, 2])\\n    assert c[0].ae(1.5)\\n    assert c[1].ae(-3*sqrt(3)/(2*pi))\\n    assert c[2].ae(3*sqrt(3)/(4*pi))\\n    assert s[0] == 0\\n    assert s[1].ae(3/(2*pi))\\n    assert s[2].ae(3/(4*pi))\\n    assert fourierval((c, s), [-1, 2], 1).ae(1.9134966715663442)\\n\\ndef test_differint():\\n    mp.dps = 15\\n    assert differint(lambda t: t, 2, -0.5).ae(8*sqrt(2/pi)/3)\\n\\ndef test_invlap():\\n    mp.dps = 15\\n    t = 0.01\\n    fp = lambda p: 1/(p+1)**2\\n    ft = lambda t: t*exp(-t)\\n    ftt = ft(t)\\n    assert invertlaplace(fp,t,method='talbot').ae(ftt)\\n    assert invertlaplace(fp,t,method='stehfest').ae(ftt)\\n    assert invertlaplace(fp,t,method='dehoog').ae(ftt)\\n    assert invertlaplace(fp,t,method='cohen').ae(ftt)\\n    t = 1.0\\n    ftt = ft(t)\\n    assert invertlaplace(fp,t,method='talbot').ae(ftt)\\n    assert invertlaplace(fp,t,method='stehfest').ae(ftt)\\n    assert invertlaplace(fp,t,method='dehoog').ae(ftt)\\n    assert invertlaplace(fp,t,method='cohen').ae(ftt)\\n\\n    t = 0.01\\n    fp = lambda p: log(p)/p\\n    ft = lambda t: -euler-log(t)\\n    ftt = ft(t)\\n    assert invertlaplace(fp,t,method='talbot').ae(ftt)\\n    assert invertlaplace(fp,t,method='stehfest').ae(ftt)\\n    assert invertlaplace(fp,t,method='dehoog').ae(ftt)\\n    assert invertlaplace(fp,t,method='cohen').ae(ftt)\\n    t = 1.0\\n    ftt = ft(t)\\n    assert invertlaplace(fp,t,method='talbot').ae(ftt)\\n    assert invertlaplace(fp,t,method='stehfest').ae(ftt)\\n    assert invertlaplace(fp,t,method='dehoog').ae(ftt)\\n    assert invertlaplace(fp,t,method='cohen').ae(ftt)\\n\\n\\n#!/usr/bin/python\\n# -*- coding: utf-8 -*-\\n\\nfrom mpmath import mp\\nfrom mpmath import libmp\\n\\nxrange = libmp.backend.xrange\\n\\ndef run_hessenberg(A, verbose = 0):\\n    if verbose > 1:\\n        print(\\\"original matrix (hessenberg):\\\\n\\\", A)\\n\\n    n = A.rows\\n\\n    Q, H = mp.hessenberg(A)\\n\\n    if verbose > 1:\\n        print(\\\"Q:\\\\n\\\",Q)\\n        print(\\\"H:\\\\n\\\",H)\\n\\n    B = Q * H * Q.transpose_conj()\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    err0 = 0\\n    for x in xrange(n):\\n        for y in xrange(n):\\n            err0 += abs(A[y,x] - B[y,x])\\n    err0 /= n * n\\n\\n    err1 = 0\\n    for x in xrange(n):\\n        for y in xrange(x + 2, n):\\n            err1 += abs(H[y,x])\\n\\n    if verbose > 0:\\n        print(\\\"difference (H):\\\", err0, err1)\\n\\n    if verbose > 1:\\n        print(\\\"B:\\\\n\\\", B)\\n\\n    assert err0 < eps\\n    assert err1 == 0\\n\\n\\ndef run_schur(A, verbose = 0):\\n    if verbose > 1:\\n        print(\\\"original matrix (schur):\\\\n\\\", A)\\n\\n    n = A.rows\\n\\n    Q, R = mp.schur(A)\\n\\n    if verbose > 1:\\n        print(\\\"Q:\\\\n\\\", Q)\\n        print(\\\"R:\\\\n\\\", R)\\n\\n    B = Q * R * Q.transpose_conj()\\n    C = Q * Q.transpose_conj()\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    err0 = 0\\n    for x in xrange(n):\\n        for y in xrange(n):\\n            err0 += abs(A[y,x] - B[y,x])\\n    err0 /= n * n\\n\\n    err1 = 0\\n    for x in xrange(n):\\n        for y in xrange(n):\\n            if x == y:\\n                C[y,x] -= 1\\n            err1 += abs(C[y,x])\\n    err1 /= n * n\\n\\n    err2 = 0\\n    for x in xrange(n):\\n        for y in xrange(x + 1, n):\\n            err2 += abs(R[y,x])\\n\\n    if verbose > 0:\\n        print(\\\"difference (S):\\\", err0, err1, err2)\\n\\n    if verbose > 1:\\n        print(\\\"B:\\\\n\\\", B)\\n\\n    assert err0 < eps\\n    assert err1 < eps\\n    assert err2 == 0\\n\\ndef run_eig(A, verbose = 0):\\n    if verbose > 1:\\n        print(\\\"original matrix (eig):\\\\n\\\", A)\\n\\n    n = A.rows\\n\\n    E, EL, ER = mp.eig(A, left = True, right = True)\\n\\n    if verbose > 1:\\n        print(\\\"E:\\\\n\\\", E)\\n        print(\\\"EL:\\\\n\\\", EL)\\n        print(\\\"ER:\\\\n\\\", ER)\\n\\n    eps = mp.exp(0.8 * mp.log(mp.eps))\\n\\n    err0 = 0\\n    for i in xrange(n):\\n        B = A * ER[:,i] - E[i] * ER[:,i]\\n        err0 = max(err0, mp.mnorm(B))\\n\\n        B = EL[i,:] * A - EL[i,:] * E[i]\\n        err0 = max(err0, mp.mnorm(B))\\n\\n    err0 /= n * n\\n\\n    if verbose > 0:\\n        print(\\\"difference (E):\\\", err0)\\n\\n    assert err0 < eps\\n\\n#####################\\n\\ndef test_eig_dyn():\\n    v = 0\\n    for i in xrange(5):\\n        n = 1 + int(mp.rand() * 5)\\n        if mp.rand() > 0.5:\\n            # real\\n            A = 2 * mp.randmatrix(n, n) - 1\\n            if mp.rand() > 0.5:\\n                A *= 10\\n                for x in xrange(n):\\n                    for y in xrange(n):\\n                        A[x,y] = int(A[x,y])\\n        else:\\n            A = (2 * mp.randmatrix(n, n) - 1) + 1j * (2 * mp.randmatrix(n, n) - 1)\\n            if mp.rand() > 0.5:\\n                A *= 10\\n                for x in xrange(n):\\n                    for y in xrange(n):\\n                        A[x,y] = int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y]))\\n\\n        run_hessenberg(A, verbose = v)\\n        run_schur(A, verbose = v)\\n        run_eig(A, verbose = v)\\n\\ndef test_eig():\\n    v = 0\\n    AS = []\\n\\n    A = mp.matrix([[2, 1, 0],  # jordan block of size 3\\n                   [0, 2, 1],\\n                   [0, 0, 2]])\\n    AS.append(A)\\n    AS.append(A.transpose())\\n\\n    A = mp.matrix([[2, 0, 0],  # jordan block of size 2\\n                   [0, 2, 1],\\n                   [0, 0, 2]])\\n    AS.append(A)\\n    AS.append(A.transpose())\\n\\n    A = mp.matrix([[2, 0, 1],  # jordan block of size 2\\n                   [0, 2, 0],\\n                   [0, 0, 2]])\\n    AS.append(A)\\n    AS.append(A.transpose())\\n\\n    A=  mp.matrix([[0, 0, 1],  # cyclic\\n                   [1, 0, 0],\\n                   [0, 1, 0]])\\n    AS.append(A)\\n    AS.append(A.transpose())\\n\\n    for A in AS:\\n        run_hessenberg(A, verbose = v)\\n        run_schur(A, verbose = v)\\n        run_eig(A, verbose = v)\\n\\n\\nfrom mpmath import *\\n\\ndef test_diff():\\n    mp.dps = 15\\n    assert diff(log, 2.0, n=0).ae(log(2))\\n    assert diff(cos, 1.0).ae(-sin(1))\\n    assert diff(abs, 0.0) == 0\\n    assert diff(abs, 0.0, direction=1) == 1\\n    assert diff(abs, 0.0, direction=-1) == -1\\n    assert diff(exp, 1.0).ae(e)\\n    assert diff(exp, 1.0, n=5).ae(e)\\n    assert diff(exp, 2.0, n=5, direction=3*j).ae(e**2)\\n    assert diff(lambda x: x**2, 3.0, method='quad').ae(6)\\n    assert diff(lambda x: 3+x**5, 3.0, n=2, method='quad').ae(540)\\n    assert diff(lambda x: 3+x**5, 3.0, n=2, method='step').ae(540)\\n    assert diffun(sin)(2).ae(cos(2))\\n    assert diffun(sin, n=2)(2).ae(-sin(2))\\n\\ndef test_diffs():\\n    mp.dps = 15\\n    assert [chop(d) for d in diffs(sin, 0, 1)] == [0, 1]\\n    assert [chop(d) for d in diffs(sin, 0, 1, method='quad')] == [0, 1]\\n    assert [chop(d) for d in diffs(sin, 0, 2)] == [0, 1, 0]\\n    assert [chop(d) for d in diffs(sin, 0, 2, method='quad')] == [0, 1, 0]\\n\\ndef test_taylor():\\n    mp.dps = 15\\n    # Easy to test since the coefficients are exact in floating-point\\n    assert taylor(sqrt, 1, 4) == [1, 0.5, -0.125, 0.0625, -0.0390625]\\n\\ndef test_diff_partial():\\n    mp.dps = 15\\n    x,y,z = xyz = 2,3,7\\n    f = lambda x,y,z: 3*x**2 * (y+2)**3 * z**5\\n    assert diff(f, xyz, (0,0,0)).ae(25210500)\\n    assert diff(f, xyz, (0,0,1)).ae(18007500)\\n    assert diff(f, xyz, (0,0,2)).ae(10290000)\\n    assert diff(f, xyz, (0,1,0)).ae(15126300)\\n    assert diff(f, xyz, (0,1,1)).ae(10804500)\\n    assert diff(f, xyz, (0,1,2)).ae(6174000)\\n    assert diff(f, xyz, (0,2,0)).ae(6050520)\\n    assert diff(f, xyz, (0,2,1)).ae(4321800)\\n    assert diff(f, xyz, (0,2,2)).ae(2469600)\\n    assert diff(f, xyz, (1,0,0)).ae(25210500)\\n    assert diff(f, xyz, (1,0,1)).ae(18007500)\\n    assert diff(f, xyz, (1,0,2)).ae(10290000)\\n    assert diff(f, xyz, (1,1,0)).ae(15126300)\\n    assert diff(f, xyz, (1,1,1)).ae(10804500)\\n    assert diff(f, xyz, (1,1,2)).ae(6174000)\\n    assert diff(f, xyz, (1,2,0)).ae(6050520)\\n    assert diff(f, xyz, (1,2,1)).ae(4321800)\\n    assert diff(f, xyz, (1,2,2)).ae(2469600)\\n    assert diff(f, xyz, (2,0,0)).ae(12605250)\\n    assert diff(f, xyz, (2,0,1)).ae(9003750)\\n    assert diff(f, xyz, (2,0,2)).ae(5145000)\\n    assert diff(f, xyz, (2,1,0)).ae(7563150)\\n    assert diff(f, xyz, (2,1,1)).ae(5402250)\\n    assert diff(f, xyz, (2,1,2)).ae(3087000)\\n    assert diff(f, xyz, (2,2,0)).ae(3025260)\\n    assert diff(f, xyz, (2,2,1)).ae(2160900)\\n    assert diff(f, xyz, (2,2,2)).ae(1234800)\\n\\n\\n\\\"\\\"\\\"\\nCheck that the output from irrational functions is accurate for\\nhigh-precision input, from 5 to 200 digits. The reference values were\\nverified with Mathematica.\\n\\\"\\\"\\\"\\n\\nimport time\\nfrom mpmath import *\\n\\nprecs = [5, 15, 28, 35, 57, 80, 100, 150, 200]\\n\\n# sqrt(3) + pi/2\\na = \\\\\\n\\\"3.302847134363773912758768033145623809041389953497933538543279275605\\\"\\\\\\n\\\"841220051904536395163599428307109666700184672047856353516867399774243594\\\"\\\\\\n\\\"67433521615861420725323528325327484262075464241255915238845599752675\\\"\\n\\n# e + 1/euler**2\\nb = \\\\\\n\\\"5.719681166601007617111261398629939965860873957353320734275716220045750\\\"\\\\\\n\\\"31474116300529519620938123730851145473473708966080207482581266469342214\\\"\\\\\\n\\\"824842256999042984813905047895479210702109260221361437411947323431\\\"\\n\\n# sqrt(a)\\nsqrt_a = \\\\\\n\\\"1.817373691447021556327498239690365674922395036495564333152483422755\\\"\\\\\\n\\\"144321726165582817927383239308173567921345318453306994746434073691275094\\\"\\\\\\n\\\"484777905906961689902608644112196725896908619756404253109722911487\\\"\\n\\n# sqrt(a+b*i).real\\nsqrt_abi_real = \\\\\\n\\\"2.225720098415113027729407777066107959851146508557282707197601407276\\\"\\\\\\n\\\"89160998185797504198062911768240808839104987021515555650875977724230130\\\"\\\\\\n\\\"3584116233925658621288393930286871862273400475179312570274423840384\\\"\\n\\n# sqrt(a+b*i).imag\\nsqrt_abi_imag = \\\\\\n\\\"1.2849057639084690902371581529110949983261182430040898147672052833653668\\\"\\\\\\n\\\"0629534491275114877090834296831373498336559849050755848611854282001250\\\"\\\\\\n\\\"1924311019152914021365263161630765255610885489295778894976075186\\\"\\n\\n# log(a)\\nlog_a = \\\\\\n\\\"1.194784864491089550288313512105715261520511949410072046160598707069\\\"\\\\\\n\\\"4336653155025770546309137440687056366757650909754708302115204338077595203\\\"\\\\\\n\\\"83005773986664564927027147084436553262269459110211221152925732612\\\"\\n\\n# log(a+b*i).real\\nlog_abi_real = \\\\\\n\\\"1.8877985921697018111624077550443297276844736840853590212962006811663\\\"\\\\\\n\\\"04949387789489704203167470111267581371396245317618589339274243008242708\\\"\\\\\\n\\\"014251531496104028712866224020066439049377679709216784954509456421\\\"\\n\\n# log(a+b*i).imag\\nlog_abi_imag = \\\\\\n\\\"1.0471204952840802663567714297078763189256357109769672185219334169734948\\\"\\\\\\n\\\"4265809854092437285294686651806426649541504240470168212723133326542181\\\"\\\\\\n\\\"8300136462287639956713914482701017346851009323172531601894918640\\\"\\n\\n# exp(a)\\nexp_a = \\\\\\n\\\"27.18994224087168661137253262213293847994194869430518354305430976149\\\"\\\\\\n\\\"382792035050358791398632888885200049857986258414049540376323785711941636\\\"\\\\\\n\\\"100358982497583832083513086941635049329804685212200507288797531143\\\"\\n\\n# exp(a+b*i).real\\nexp_abi_real = \\\\\\n\\\"22.98606617170543596386921087657586890620262522816912505151109385026\\\"\\\\\\n\\\"40160179326569526152851983847133513990281518417211964710397233157168852\\\"\\\\\\n\\\"4963130831190142571659948419307628119985383887599493378056639916701\\\"\\n\\n# exp(a+b*i).imag\\nexp_abi_imag = \\\\\\n\\\"-14.523557450291489727214750571590272774669907424478129280902375851196283\\\"\\\\\\n\\\"3377162379031724734050088565710975758824441845278120105728824497308303\\\"\\\\\\n\\\"6065619788140201636218705414429933685889542661364184694108251449\\\"\\n\\n# a**b\\npow_a_b = \\\\\\n\\\"928.7025342285568142947391505837660251004990092821305668257284426997\\\"\\\\\\n\\\"361966028275685583421197860603126498884545336686124793155581311527995550\\\"\\\\\\n\\\"580229264427202446131740932666832138634013168125809402143796691154\\\"\\n\\n# (a**(a+b*i)).real\\npow_a_abi_real = \\\\\\n\\\"44.09156071394489511956058111704382592976814280267142206420038656267\\\"\\\\\\n\\\"67707916510652790502399193109819563864568986234654864462095231138500505\\\"\\\\\\n\\\"8197456514795059492120303477512711977915544927440682508821426093455\\\"\\n\\n# (a**(a+b*i)).imag\\npow_a_abi_imag = \\\\\\n\\\"27.069371511573224750478105146737852141664955461266218367212527612279886\\\"\\\\\\n\\\"9322304536553254659049205414427707675802193810711302947536332040474573\\\"\\\\\\n\\\"8166261217563960235014674118610092944307893857862518964990092301\\\"\\n\\n# ((a+b*i)**(a+b*i)).real\\npow_abi_abi_real = \\\\\\n\\\"-0.15171310677859590091001057734676423076527145052787388589334350524\\\"\\\\\\n\\\"8084195882019497779202452975350579073716811284169068082670778986235179\\\"\\\\\\n\\\"0813026562962084477640470612184016755250592698408112493759742219150452\\\"\\\\\\n\\n# ((a+b*i)**(a+b*i)).imag\\npow_abi_abi_imag = \\\\\\n\\\"1.2697592504953448936553147870155987153192995316950583150964099070426\\\"\\\\\\n\\\"4736837932577176947632535475040521749162383347758827307504526525647759\\\"\\\\\\n\\\"97547638617201824468382194146854367480471892602963428122896045019902\\\"\\n\\n# sin(a)\\nsin_a = \\\\\\n\\\"-0.16055653857469062740274792907968048154164433772938156243509084009\\\"\\\\\\n\\\"38437090841460493108570147191289893388608611542655654723437248152535114\\\"\\\\\\n\\\"528368009465836614227575701220612124204622383149391870684288862269631\\\"\\n\\n# sin(1000*a)\\nsin_1000a = \\\\\\n\\\"-0.85897040577443833776358106803777589664322997794126153477060795801\\\"\\\\\\n\\\"09151695416961724733492511852267067419573754315098042850381158563024337\\\"\\\\\\n\\\"216458577140500488715469780315833217177634490142748614625281171216863\\\"\\n\\n# sin(a+b*i)\\nsin_abi_real = \\\\\\n\\\"-24.4696999681556977743346798696005278716053366404081910969773939630\\\"\\\\\\n\\\"7149215135459794473448465734589287491880563183624997435193637389884206\\\"\\\\\\n\\\"02151395451271809790360963144464736839412254746645151672423256977064\\\"\\n\\nsin_abi_imag = \\\\\\n\\\"-150.42505378241784671801405965872972765595073690984080160750785565810981\\\"\\\\\\n\\\"8314482499135443827055399655645954830931316357243750839088113122816583\\\"\\\\\\n\\\"7169201254329464271121058839499197583056427233866320456505060735\\\"\\n\\n# cos\\ncos_a = \\\\\\n\\\"-0.98702664499035378399332439243967038895709261414476495730788864004\\\"\\\\\\n\\\"05406821549361039745258003422386169330787395654908532996287293003581554\\\"\\\\\\n\\\"257037193284199198069707141161341820684198547572456183525659969145501\\\"\\n\\ncos_1000a = \\\\\\n\\\"-0.51202523570982001856195696460663971099692261342827540426136215533\\\"\\\\\\n\\\"52686662667660613179619804463250686852463876088694806607652218586060613\\\"\\\\\\n\\\"951310588158830695735537073667299449753951774916401887657320950496820\\\"\\n\\n# tan\\ntan_a = \\\\\\n\\\"0.162666873675188117341401059858835168007137819495998960250142156848\\\"\\\\\\n\\\"639654718809412181543343168174807985559916643549174530459883826451064966\\\"\\\\\\n\\\"7996119428949951351938178809444268785629011625179962457123195557310\\\"\\n\\ntan_abi_real = \\\\\\n\\\"6.822696615947538488826586186310162599974827139564433912601918442911\\\"\\\\\\n\\\"1026830824380070400102213741875804368044342309515353631134074491271890\\\"\\\\\\n\\\"467615882710035471686578162073677173148647065131872116479947620E-6\\\"\\n\\ntan_abi_imag = \\\\\\n\\\"0.9999795833048243692245661011298447587046967777739649018690797625964167\\\"\\\\\\n\\\"1446419978852235960862841608081413169601038230073129482874832053357571\\\"\\\\\\n\\\"62702259309150715669026865777947502665936317953101462202542168429\\\"\\n\\n\\ndef test_hp():\\n    for dps in precs:\\n        mp.dps = dps + 8\\n        aa = mpf(a)\\n        bb = mpf(b)\\n        a1000 = 1000*mpf(a)\\n        abi = mpc(aa, bb)\\n        mp.dps = dps\\n        assert (sqrt(3) + pi/2).ae(aa)\\n        assert (e + 1/euler**2).ae(bb)\\n\\n        assert sqrt(aa).ae(mpf(sqrt_a))\\n        assert sqrt(abi).ae(mpc(sqrt_abi_real, sqrt_abi_imag))\\n\\n        assert log(aa).ae(mpf(log_a))\\n        assert log(abi).ae(mpc(log_abi_real, log_abi_imag))\\n\\n        assert exp(aa).ae(mpf(exp_a))\\n        assert exp(abi).ae(mpc(exp_abi_real, exp_abi_imag))\\n\\n        assert (aa**bb).ae(mpf(pow_a_b))\\n        assert (aa**abi).ae(mpc(pow_a_abi_real, pow_a_abi_imag))\\n        assert (abi**abi).ae(mpc(pow_abi_abi_real, pow_abi_abi_imag))\\n\\n        assert sin(a).ae(mpf(sin_a))\\n        assert sin(a1000).ae(mpf(sin_1000a))\\n        assert sin(abi).ae(mpc(sin_abi_real, sin_abi_imag))\\n\\n        assert cos(a).ae(mpf(cos_a))\\n        assert cos(a1000).ae(mpf(cos_1000a))\\n\\n        assert tan(a).ae(mpf(tan_a))\\n        assert tan(abi).ae(mpc(tan_abi_real, tan_abi_imag))\\n\\n        # check that complex cancellation is avoided so that both\\n        # real and imaginary parts have high relative accuracy.\\n        # abs_eps should be 0, but has to be set to 1e-205 to pass the\\n        # 200-digit case, probably due to slight inaccuracy in the\\n        # precomputed input\\n        assert (tan(abi).real).ae(mpf(tan_abi_real), abs_eps=1e-205)\\n        assert (tan(abi).imag).ae(mpf(tan_abi_imag), abs_eps=1e-205)\\n    mp.dps = 460\\n    assert str(log(3))[-20:] == '02166121184001409826'\\n    mp.dps = 15\\n\\n# Since str(a) can differ in the last digit from rounded a, and I want\\n# to compare the last digits of big numbers with the results in Mathematica,\\n# I made this hack to get the last 20 digits of rounded a\\n\\ndef last_digits(a):\\n    r = repr(a)\\n    s = str(a)\\n    #dps = mp.dps\\n    #mp.dps += 3\\n    m = 10\\n    r = r.replace(s[:-m],'')\\n    r = r.replace(\\\"mpf('\\\",'').replace(\\\"')\\\",'')\\n    num0 = 0\\n    for c in r:\\n        if c == '0':\\n            num0 += 1\\n        else:\\n            break\\n    b = float(int(r))/10**(len(r) - m)\\n    if b >= 10**m - 0.5:  # pragma: no cover\\n        raise NotImplementedError\\n    n = int(round(b))\\n    sn = str(n)\\n    s = s[:-m] + '0'*num0 + sn\\n    return s[-20:]\\n\\n# values checked with Mathematica\\ndef test_log_hp():\\n    mp.dps = 2000\\n    a = mpf(10)**15000/3\\n    r = log(a)\\n    res = last_digits(r)\\n    # Mathematica N[Log[10^15000/3], 2000]\\n    # ...7443804441768333470331\\n    assert res == '43804441768333470331'\\n\\n    # see issue 145\\n    r = log(mpf(3)/2)\\n    # Mathematica N[Log[3/2], 2000]\\n    # ...69653749808140753263288\\n    res = last_digits(r)\\n    assert res == '53749808140753263288'\\n\\n    mp.dps = 10000\\n    r = log(2)\\n    res = last_digits(r)\\n    # Mathematica  N[Log[2], 10000]\\n    # ...695615913401856601359655561\\n    assert res == '13401856601359655561'\\n    r = log(mpf(10)**10/3)\\n    res = last_digits(r)\\n    # Mathematica N[Log[10^10/3], 10000]\\n    # ...587087654020631943060007154\\n    assert res == '54020631943060007154', res\\n    r = log(mpf(10)**100/3)\\n    res = last_digits(r)\\n    # Mathematica N[Log[10^100/3], 10000]\\n    # ,,,59246336539088351652334666\\n    assert res == '36539088351652334666', res\\n    mp.dps += 10\\n    a = 1 - mpf(1)/10**10\\n    mp.dps -= 10\\n    r = log(a)\\n    res = last_digits(r)\\n    # ...3310334360482956137216724048322957404\\n    # 372167240483229574038733026370\\n    # Mathematica N[Log[1 - 10^-10]*10^10, 10000]\\n    # ...60482956137216724048322957404\\n    assert res == '37216724048322957404', res\\n    mp.dps = 10000\\n    mp.dps += 100\\n    a = 1 + mpf(1)/10**100\\n    mp.dps -= 100\\n\\n    r = log(a)\\n    res = last_digits(+r)\\n    # Mathematica N[Log[1 + 10^-100]*10^10, 10030]\\n    # ...3994733877377412241546890854692521568292338268273 10^-91\\n    assert res == '39947338773774122415', res\\n\\n    mp.dps = 15\\n\\ndef test_exp_hp():\\n    mp.dps = 4000\\n    r = exp(mpf(1)/10)\\n    # IntegerPart[N[Exp[1/10] * 10^4000, 4000]]\\n    # ...92167105162069688129\\n    assert int(r * 10**mp.dps) % 10**20 == 92167105162069688129\\n\\n\\nfrom mpmath import *\\nfrom mpmath.libmp import round_up, from_float, mpf_zeta_int\\n\\ndef test_zeta_int_bug():\\n    assert mpf_zeta_int(0, 10) == from_float(-0.5)\\n\\ndef test_bernoulli():\\n    assert bernfrac(0) == (1,1)\\n    assert bernfrac(1) == (-1,2)\\n    assert bernfrac(2) == (1,6)\\n    assert bernfrac(3) == (0,1)\\n    assert bernfrac(4) == (-1,30)\\n    assert bernfrac(5) == (0,1)\\n    assert bernfrac(6) == (1,42)\\n    assert bernfrac(8) == (-1,30)\\n    assert bernfrac(10) == (5,66)\\n    assert bernfrac(12) == (-691,2730)\\n    assert bernfrac(18) == (43867,798)\\n    p, q = bernfrac(228)\\n    assert p % 10**10 == 164918161\\n    assert q == 625170\\n    p, q = bernfrac(1000)\\n    assert p % 10**10 == 7950421099\\n    assert q == 342999030\\n    mp.dps = 15\\n    assert bernoulli(0) == 1\\n    assert bernoulli(1) == -0.5\\n    assert bernoulli(2).ae(1./6)\\n    assert bernoulli(3) == 0\\n    assert bernoulli(4).ae(-1./30)\\n    assert bernoulli(5) == 0\\n    assert bernoulli(6).ae(1./42)\\n    assert str(bernoulli(10)) == '0.0757575757575758'\\n    assert str(bernoulli(234)) == '7.62772793964344e+267'\\n    assert str(bernoulli(10**5)) == '-5.82229431461335e+376755'\\n    assert str(bernoulli(10**8+2)) == '1.19570355039953e+676752584'\\n\\n    mp.dps = 50\\n    assert str(bernoulli(10)) == '0.075757575757575757575757575757575757575757575757576'\\n    assert str(bernoulli(234)) == '7.6277279396434392486994969020496121553385863373331e+267'\\n    assert str(bernoulli(10**5)) == '-5.8222943146133508236497045360612887555320691004308e+376755'\\n    assert str(bernoulli(10**8+2)) == '1.1957035503995297272263047884604346914602088317782e+676752584'\\n\\n    mp.dps = 1000\\n    assert bernoulli(10).ae(mpf(5)/66)\\n\\n    mp.dps = 50000\\n    assert bernoulli(10).ae(mpf(5)/66)\\n\\n    mp.dps = 15\\n\\ndef test_bernpoly_eulerpoly():\\n    mp.dps = 15\\n    assert bernpoly(0,-1).ae(1)\\n    assert bernpoly(0,0).ae(1)\\n    assert bernpoly(0,'1/2').ae(1)\\n    assert bernpoly(0,'3/4').ae(1)\\n    assert bernpoly(0,1).ae(1)\\n    assert bernpoly(0,2).ae(1)\\n    assert bernpoly(1,-1).ae('-3/2')\\n    assert bernpoly(1,0).ae('-1/2')\\n    assert bernpoly(1,'1/2').ae(0)\\n    assert bernpoly(1,'3/4').ae('1/4')\\n    assert bernpoly(1,1).ae('1/2')\\n    assert bernpoly(1,2).ae('3/2')\\n    assert bernpoly(2,-1).ae('13/6')\\n    assert bernpoly(2,0).ae('1/6')\\n    assert bernpoly(2,'1/2').ae('-1/12')\\n    assert bernpoly(2,'3/4').ae('-1/48')\\n    assert bernpoly(2,1).ae('1/6')\\n    assert bernpoly(2,2).ae('13/6')\\n    assert bernpoly(3,-1).ae(-3)\\n    assert bernpoly(3,0).ae(0)\\n    assert bernpoly(3,'1/2').ae(0)\\n    assert bernpoly(3,'3/4').ae('-3/64')\\n    assert bernpoly(3,1).ae(0)\\n    assert bernpoly(3,2).ae(3)\\n    assert bernpoly(4,-1).ae('119/30')\\n    assert bernpoly(4,0).ae('-1/30')\\n    assert bernpoly(4,'1/2').ae('7/240')\\n    assert bernpoly(4,'3/4').ae('7/3840')\\n    assert bernpoly(4,1).ae('-1/30')\\n    assert bernpoly(4,2).ae('119/30')\\n    assert bernpoly(5,-1).ae(-5)\\n    assert bernpoly(5,0).ae(0)\\n    assert bernpoly(5,'1/2').ae(0)\\n    assert bernpoly(5,'3/4').ae('25/1024')\\n    assert bernpoly(5,1).ae(0)\\n    assert bernpoly(5,2).ae(5)\\n    assert bernpoly(10,-1).ae('665/66')\\n    assert bernpoly(10,0).ae('5/66')\\n    assert bernpoly(10,'1/2').ae('-2555/33792')\\n    assert bernpoly(10,'3/4').ae('-2555/34603008')\\n    assert bernpoly(10,1).ae('5/66')\\n    assert bernpoly(10,2).ae('665/66')\\n    assert bernpoly(11,-1).ae(-11)\\n    assert bernpoly(11,0).ae(0)\\n    assert bernpoly(11,'1/2').ae(0)\\n    assert bernpoly(11,'3/4').ae('-555731/4194304')\\n    assert bernpoly(11,1).ae(0)\\n    assert bernpoly(11,2).ae(11)\\n    assert eulerpoly(0,-1).ae(1)\\n    assert eulerpoly(0,0).ae(1)\\n    assert eulerpoly(0,'1/2').ae(1)\\n    assert eulerpoly(0,'3/4').ae(1)\\n    assert eulerpoly(0,1).ae(1)\\n    assert eulerpoly(0,2).ae(1)\\n    assert eulerpoly(1,-1).ae('-3/2')\\n    assert eulerpoly(1,0).ae('-1/2')\\n    assert eulerpoly(1,'1/2').ae(0)\\n    assert eulerpoly(1,'3/4').ae('1/4')\\n    assert eulerpoly(1,1).ae('1/2')\\n    assert eulerpoly(1,2).ae('3/2')\\n    assert eulerpoly(2,-1).ae(2)\\n    assert eulerpoly(2,0).ae(0)\\n    assert eulerpoly(2,'1/2').ae('-1/4')\\n    assert eulerpoly(2,'3/4').ae('-3/16')\\n    assert eulerpoly(2,1).ae(0)\\n    assert eulerpoly(2,2).ae(2)\\n    assert eulerpoly(3,-1).ae('-9/4')\\n    assert eulerpoly(3,0).ae('1/4')\\n    assert eulerpoly(3,'1/2').ae(0)\\n    assert eulerpoly(3,'3/4').ae('-11/64')\\n    assert eulerpoly(3,1).ae('-1/4')\\n    assert eulerpoly(3,2).ae('9/4')\\n    assert eulerpoly(4,-1).ae(2)\\n    assert eulerpoly(4,0).ae(0)\\n    assert eulerpoly(4,'1/2').ae('5/16')\\n    assert eulerpoly(4,'3/4').ae('57/256')\\n    assert eulerpoly(4,1).ae(0)\\n    assert eulerpoly(4,2).ae(2)\\n    assert eulerpoly(5,-1).ae('-3/2')\\n    assert eulerpoly(5,0).ae('-1/2')\\n    assert eulerpoly(5,'1/2').ae(0)\\n    assert eulerpoly(5,'3/4').ae('361/1024')\\n    assert eulerpoly(5,1).ae('1/2')\\n    assert eulerpoly(5,2).ae('3/2')\\n    assert eulerpoly(10,-1).ae(2)\\n    assert eulerpoly(10,0).ae(0)\\n    assert eulerpoly(10,'1/2').ae('-50521/1024')\\n    assert eulerpoly(10,'3/4').ae('-36581523/1048576')\\n    assert eulerpoly(10,1).ae(0)\\n    assert eulerpoly(10,2).ae(2)\\n    assert eulerpoly(11,-1).ae('-699/4')\\n    assert eulerpoly(11,0).ae('691/4')\\n    assert eulerpoly(11,'1/2').ae(0)\\n    assert eulerpoly(11,'3/4').ae('-512343611/4194304')\\n    assert eulerpoly(11,1).ae('-691/4')\\n    assert eulerpoly(11,2).ae('699/4')\\n    # Potential accuracy issues\\n    assert bernpoly(10000,10000).ae('5.8196915936323387117e+39999')\\n    assert bernpoly(200,17.5).ae(3.8048418524583064909e244)\\n    assert eulerpoly(200,17.5).ae(-3.7309911582655785929e275)\\n\\ndef test_gamma():\\n    mp.dps = 15\\n    assert gamma(0.25).ae(3.6256099082219083119)\\n    assert gamma(0.0001).ae(9999.4228832316241908)\\n    assert gamma(300).ae('1.0201917073881354535e612')\\n    assert gamma(-0.5).ae(-3.5449077018110320546)\\n    assert gamma(-7.43).ae(0.00026524416464197007186)\\n    #assert gamma(Rational(1,2)) == gamma(0.5)\\n    #assert gamma(Rational(-7,3)).ae(gamma(mpf(-7)/3))\\n    assert gamma(1+1j).ae(0.49801566811835604271 - 0.15494982830181068512j)\\n    assert gamma(-1+0.01j).ae(-0.422733904013474115 + 99.985883082635367436j)\\n    assert gamma(20+30j).ae(-1453876687.5534810 + 1163777777.8031573j)\\n    # Should always give exact factorials when they can\\n    # be represented as mpfs under the current working precision\\n    fact = 1\\n    for i in range(1, 18):\\n        assert gamma(i) == fact\\n        fact *= i\\n    for dps in [170, 600]:\\n        fact = 1\\n        mp.dps = dps\\n        for i in range(1, 105):\\n            assert gamma(i) == fact\\n            fact *= i\\n    mp.dps = 100\\n    assert gamma(0.5).ae(sqrt(pi))\\n    mp.dps = 15\\n    assert factorial(0) == fac(0) == 1\\n    assert factorial(3) == 6\\n    assert isnan(gamma(nan))\\n    assert gamma(1100).ae('4.8579168073569433667e2866')\\n    assert rgamma(0) == 0\\n    assert rgamma(-1) == 0\\n    assert rgamma(2) == 1.0\\n    assert rgamma(3) == 0.5\\n    assert loggamma(2+8j).ae(-8.5205176753667636926 + 10.8569497125597429366j)\\n    assert loggamma('1e10000').ae('2.302485092994045684017991e10004')\\n    assert loggamma('1e10000j').ae(mpc('-1.570796326794896619231322e10000','2.302485092994045684017991e10004'))\\n\\ndef test_fac2():\\n    mp.dps = 15\\n    assert [fac2(n) for n in range(10)] == [1,1,2,3,8,15,48,105,384,945]\\n    assert fac2(-5).ae(1./3)\\n    assert fac2(-11).ae(-1./945)\\n    assert fac2(50).ae(5.20469842636666623e32)\\n    assert fac2(0.5+0.75j).ae(0.81546769394688069176-0.34901016085573266889j)\\n    assert fac2(inf) == inf\\n    assert isnan(fac2(-inf))\\n\\ndef test_gamma_quotients():\\n    mp.dps = 15\\n    h = 1e-8\\n    ep = 1e-4\\n    G = gamma\\n    assert gammaprod([-1],[-3,-4]) == 0\\n    assert gammaprod([-1,0],[-5]) == inf\\n    assert abs(gammaprod([-1],[-2]) - G(-1+h)/G(-2+h)) < 1e-4\\n    assert abs(gammaprod([-4,-3],[-2,0]) - G(-4+h)*G(-3+h)/G(-2+h)/G(0+h)) < 1e-4\\n    assert rf(3,0) == 1\\n    assert rf(2.5,1) == 2.5\\n    assert rf(-5,2) == 20\\n    assert rf(j,j).ae(gamma(2*j)/gamma(j))\\n    assert rf('-255.5815971722918','-0.5119253100282322').ae('-0.1952720278805729485')  # issue 421\\n    assert ff(-2,0) == 1\\n    assert ff(-2,1) == -2\\n    assert ff(4,3) == 24\\n    assert ff(3,4) == 0\\n    assert binomial(0,0) == 1\\n    assert binomial(1,0) == 1\\n    assert binomial(0,-1) == 0\\n    assert binomial(3,2) == 3\\n    assert binomial(5,2) == 10\\n    assert binomial(5,3) == 10\\n    assert binomial(5,5) == 1\\n    assert binomial(-1,0) == 1\\n    assert binomial(-2,-4) == 3\\n    assert binomial(4.5, 1.5) == 6.5625\\n    assert binomial(1100,1) == 1100\\n    assert binomial(1100,2) == 604450\\n    assert beta(1,1) == 1\\n    assert beta(0,0) == inf\\n    assert beta(3,0) == inf\\n    assert beta(-1,-1) == inf\\n    assert beta(1.5,1).ae(2/3.)\\n    assert beta(1.5,2.5).ae(pi/16)\\n    assert (10**15*beta(10,100)).ae(2.3455339739604649879)\\n    assert beta(inf,inf) == 0\\n    assert isnan(beta(-inf,inf))\\n    assert isnan(beta(-3,inf))\\n    assert isnan(beta(0,inf))\\n    assert beta(inf,0.5) == beta(0.5,inf) == 0\\n    assert beta(inf,-1.5) == inf\\n    assert beta(inf,-0.5) == -inf\\n    assert beta(1+2j,-1-j/2).ae(1.16396542451069943086+0.08511695947832914640j)\\n    assert beta(-0.5,0.5) == 0\\n    assert beta(-3,3).ae(-1/3.)\\n    assert beta('-255.5815971722918','-0.5119253100282322').ae('18.157330562703710339')  # issue 421\\n\\ndef test_zeta():\\n    mp.dps = 15\\n    assert zeta(2).ae(pi**2 / 6)\\n    assert zeta(2.0).ae(pi**2 / 6)\\n    assert zeta(mpc(2)).ae(pi**2 / 6)\\n    assert zeta(100).ae(1)\\n    assert zeta(0).ae(-0.5)\\n    assert zeta(0.5).ae(-1.46035450880958681)\\n    assert zeta(-1).ae(-mpf(1)/12)\\n    assert zeta(-2) == 0\\n    assert zeta(-3).ae(mpf(1)/120)\\n    assert zeta(-4) == 0\\n    assert zeta(-100) == 0\\n    assert isnan(zeta(nan))\\n    assert zeta(1e-30).ae(-0.5)\\n    assert zeta(-1e-30).ae(-0.5)\\n    # Zeros in the critical strip\\n    assert zeta(mpc(0.5, 14.1347251417346937904)).ae(0)\\n    assert zeta(mpc(0.5, 21.0220396387715549926)).ae(0)\\n    assert zeta(mpc(0.5, 25.0108575801456887632)).ae(0)\\n    assert zeta(mpc(1e-30,1e-40)).ae(-0.5)\\n    assert zeta(mpc(-1e-30,1e-40)).ae(-0.5)\\n    mp.dps = 50\\n    im = '236.5242296658162058024755079556629786895294952121891237'\\n    assert zeta(mpc(0.5, im)).ae(0, 1e-46)\\n    mp.dps = 15\\n    # Complex reflection formula\\n    assert (zeta(-60+3j) / 10**34).ae(8.6270183987866146+15.337398548226238j)\\n    # issue #358\\n    assert zeta(0,0.5) == 0\\n    assert zeta(0,0) == 0.5\\n    assert zeta(0,0.5,1).ae(-0.34657359027997265)\\n    # see issue #390\\n    assert zeta(-1.5,0.5j).ae(-0.13671400162512768475 + 0.11411333638426559139j)\\n\\ndef test_altzeta():\\n    mp.dps = 15\\n    assert altzeta(-2) == 0\\n    assert altzeta(-4) == 0\\n    assert altzeta(-100) == 0\\n    assert altzeta(0) == 0.5\\n    assert altzeta(-1) == 0.25\\n    assert altzeta(-3) == -0.125\\n    assert altzeta(-5) == 0.25\\n    assert altzeta(-21) == 1180529130.25\\n    assert altzeta(1).ae(log(2))\\n    assert altzeta(2).ae(pi**2/12)\\n    assert altzeta(10).ae(73*pi**10/6842880)\\n    assert altzeta(50) < 1\\n    assert altzeta(60, rounding='d') < 1\\n    assert altzeta(60, rounding='u') == 1\\n    assert altzeta(10000, rounding='d') < 1\\n    assert altzeta(10000, rounding='u') == 1\\n    assert altzeta(3+0j) == altzeta(3)\\n    s = 3+4j\\n    assert altzeta(s).ae((1-2**(1-s))*zeta(s))\\n    s = -3+4j\\n    assert altzeta(s).ae((1-2**(1-s))*zeta(s))\\n    assert altzeta(-100.5).ae(4.58595480083585913e+108)\\n    assert altzeta(1.3).ae(0.73821404216623045)\\n    assert altzeta(1e-30).ae(0.5)\\n    assert altzeta(-1e-30).ae(0.5)\\n    assert altzeta(mpc(1e-30,1e-40)).ae(0.5)\\n    assert altzeta(mpc(-1e-30,1e-40)).ae(0.5)\\n\\ndef test_zeta_huge():\\n    mp.dps = 15\\n    assert zeta(inf) == 1\\n    mp.dps = 50\\n    assert zeta(100).ae('1.0000000000000000000000000000007888609052210118073522')\\n    assert zeta(40*pi).ae('1.0000000000000000000000000000000000000148407238666182')\\n    mp.dps = 10000\\n    v = zeta(33000)\\n    mp.dps = 15\\n    assert str(v-1) == '1.02363019598118e-9934'\\n    assert zeta(pi*1000, rounding=round_up) > 1\\n    assert zeta(3000, rounding=round_up) > 1\\n    assert zeta(pi*1000) == 1\\n    assert zeta(3000) == 1\\n\\ndef test_zeta_negative():\\n    mp.dps = 150\\n    a = -pi*10**40\\n    mp.dps = 15\\n    assert str(zeta(a)) == '2.55880492708712e+1233536161668617575553892558646631323374078'\\n    mp.dps = 50\\n    assert str(zeta(a)) == '2.5588049270871154960875033337384432038436330847333e+1233536161668617575553892558646631323374078'\\n    mp.dps = 15\\n\\ndef test_polygamma():\\n    mp.dps = 15\\n    psi0 = lambda z: psi(0,z)\\n    psi1 = lambda z: psi(1,z)\\n    assert psi0(3) == psi(0,3) == digamma(3)\\n    #assert psi2(3) == psi(2,3) == tetragamma(3)\\n    #assert psi3(3) == psi(3,3) == pentagamma(3)\\n    assert psi0(pi).ae(0.97721330794200673)\\n    assert psi0(-pi).ae(7.8859523853854902)\\n    assert psi0(-pi+1).ae(7.5676424992016996)\\n    assert psi0(pi+j).ae(1.04224048313859376 + 0.35853686544063749j)\\n    assert psi0(-pi-j).ae(1.3404026194821986 - 2.8824392476809402j)\\n    assert findroot(psi0, 1).ae(1.4616321449683622)\\n    assert psi0(1e-10).ae(-10000000000.57722)\\n    assert psi0(1e-40).ae(-1.000000000000000e+40)\\n    assert psi0(1e-10+1e-10j).ae(-5000000000.577215 + 5000000000.000000j)\\n    assert psi0(1e-40+1e-40j).ae(-5.000000000000000e+39 + 5.000000000000000e+39j)\\n    assert psi0(inf) == inf\\n    assert psi1(inf) == 0\\n    assert psi(2,inf) == 0\\n    assert psi1(pi).ae(0.37424376965420049)\\n    assert psi1(-pi).ae(53.030438740085385)\\n    assert psi1(pi+j).ae(0.32935710377142464 - 0.12222163911221135j)\\n    assert psi1(-pi-j).ae(-0.30065008356019703 + 0.01149892486928227j)\\n    assert (10**6*psi(4,1+10*pi*j)).ae(-6.1491803479004446 - 0.3921316371664063j)\\n    assert psi0(1+10*pi*j).ae(3.4473994217222650 + 1.5548808324857071j)\\n    assert isnan(psi0(nan))\\n    assert isnan(psi0(-inf))\\n    assert psi0(-100.5).ae(4.615124601338064)\\n    assert psi0(3+0j).ae(psi0(3))\\n    assert psi0(-100+3j).ae(4.6106071768714086321+3.1117510556817394626j)\\n    assert isnan(psi(2,mpc(0,inf)))\\n    assert isnan(psi(2,mpc(0,nan)))\\n    assert isnan(psi(2,mpc(0,-inf)))\\n    assert isnan(psi(2,mpc(1,inf)))\\n    assert isnan(psi(2,mpc(1,nan)))\\n    assert isnan(psi(2,mpc(1,-inf)))\\n    assert isnan(psi(2,mpc(inf,inf)))\\n    assert isnan(psi(2,mpc(nan,nan)))\\n    assert isnan(psi(2,mpc(-inf,-inf)))\\n    mp.dps = 30\\n    # issue #534\\n    assert digamma(-0.75+1j).ae(mpc('0.46317279488182026118963809283042317', '2.4821070143037957102007677817351115'))\\n    mp.dps = 15\\n\\ndef test_polygamma_high_prec():\\n    mp.dps = 100\\n    assert str(psi(0,pi)) == \\\"0.9772133079420067332920694864061823436408346099943256380095232865318105924777141317302075654362928734\\\"\\n    assert str(psi(10,pi)) == \\\"-12.98876181434889529310283769414222588307175962213707170773803550518307617769657562747174101900659238\\\"\\n\\ndef test_polygamma_identities():\\n    mp.dps = 15\\n    psi0 = lambda z: psi(0,z)\\n    psi1 = lambda z: psi(1,z)\\n    psi2 = lambda z: psi(2,z)\\n    assert psi0(0.5).ae(-euler-2*log(2))\\n    assert psi0(1).ae(-euler)\\n    assert psi1(0.5).ae(0.5*pi**2)\\n    assert psi1(1).ae(pi**2/6)\\n    assert psi1(0.25).ae(pi**2 + 8*catalan)\\n    assert psi2(1).ae(-2*apery)\\n    mp.dps = 20\\n    u = -182*apery+4*sqrt(3)*pi**3\\n    mp.dps = 15\\n    assert psi(2,5/6.).ae(u)\\n    assert psi(3,0.5).ae(pi**4)\\n\\ndef test_foxtrot_identity():\\n    # A test of the complex digamma function.\\n    # See http://mathworld.wolfram.com/FoxTrotSeries.html and\\n    # http://mathworld.wolfram.com/DigammaFunction.html\\n    psi0 = lambda z: psi(0,z)\\n    mp.dps = 50\\n    a = (-1)**fraction(1,3)\\n    b = (-1)**fraction(2,3)\\n    x = -psi0(0.5*a) - psi0(-0.5*b) + psi0(0.5*(1+a)) + psi0(0.5*(1-b))\\n    y = 2*pi*sech(0.5*sqrt(3)*pi)\\n    assert x.ae(y)\\n    mp.dps = 15\\n\\ndef test_polygamma_high_order():\\n    mp.dps = 100\\n    assert str(psi(50, pi)) == \\\"-1344100348958402765749252447726432491812.641985273160531055707095989227897753035823152397679626136483\\\"\\n    assert str(psi(50, pi + 14*e)) == \\\"-0.00000000000000000189793739550804321623512073101895801993019919886375952881053090844591920308111549337295143780341396\\\"\\n    assert str(psi(50, pi + 14*e*j)) == (\\\"(-0.0000000000000000522516941152169248975225472155683565752375889510631513244785\\\"\\n        \\\"9377385233700094871256507814151956624433 - 0.00000000000000001813157041407010184\\\"\\n        \\\"702414110218205348527862196327980417757665282244728963891298080199341480881811613j)\\\")\\n    mp.dps = 15\\n    assert str(psi(50, pi)) == \\\"-1.34410034895841e+39\\\"\\n    assert str(psi(50, pi + 14*e)) == \\\"-1.89793739550804e-18\\\"\\n    assert str(psi(50, pi + 14*e*j)) == \\\"(-5.2251694115217e-17 - 1.81315704140701e-17j)\\\"\\n\\ndef test_harmonic():\\n    mp.dps = 15\\n    assert harmonic(0) == 0\\n    assert harmonic(1) == 1\\n    assert harmonic(2) == 1.5\\n    assert harmonic(3).ae(1. + 1./2 + 1./3)\\n    assert harmonic(10**10).ae(23.603066594891989701)\\n    assert harmonic(10**1000).ae(2303.162308658947)\\n    assert harmonic(0.5).ae(2-2*log(2))\\n    assert harmonic(inf) == inf\\n    assert harmonic(2+0j) == 1.5+0j\\n    assert harmonic(1+2j).ae(1.4918071802755104+0.92080728264223022j)\\n\\ndef test_gamma_huge_1():\\n    mp.dps = 500\\n    x = mpf(10**10) / 7\\n    mp.dps = 15\\n    assert str(gamma(x)) == \\\"6.26075321389519e+12458010678\\\"\\n    mp.dps = 50\\n    assert str(gamma(x)) == \\\"6.2607532138951929201303779291707455874010420783933e+12458010678\\\"\\n    mp.dps = 15\\n\\ndef test_gamma_huge_2():\\n    mp.dps = 500\\n    x = mpf(10**100) / 19\\n    mp.dps = 15\\n    assert str(gamma(x)) == (\\\\\\n        \\\"1.82341134776679e+5172997469323364168990133558175077136829182824042201886051511\\\"\\n        \\\"9656908623426021308685461258226190190661\\\")\\n    mp.dps = 50\\n    assert str(gamma(x)) == (\\\\\\n        \\\"1.82341134776678875374414910350027596939980412984e+5172997469323364168990133558\\\"\\n        \\\"1750771368291828240422018860515119656908623426021308685461258226190190661\\\")\\n\\ndef test_gamma_huge_3():\\n    mp.dps = 500\\n    x = 10**80 // 3 + 10**70*j / 7\\n    mp.dps = 15\\n    y = gamma(x)\\n    assert str(y.real) == (\\\\\\n        \\\"-6.82925203918106e+2636286142112569524501781477865238132302397236429627932441916\\\"\\n        \\\"056964386399485392600\\\")\\n    assert str(y.imag) == (\\\\\\n        \\\"8.54647143678418e+26362861421125695245017814778652381323023972364296279324419160\\\"\\n        \\\"56964386399485392600\\\")\\n    mp.dps = 50\\n    y = gamma(x)\\n    assert str(y.real) == (\\\\\\n        \\\"-6.8292520391810548460682736226799637356016538421817e+26362861421125695245017814\\\"\\n        \\\"77865238132302397236429627932441916056964386399485392600\\\")\\n    assert str(y.imag) == (\\\\\\n        \\\"8.5464714367841748507479306948130687511711420234015e+263628614211256952450178147\\\"\\n        \\\"7865238132302397236429627932441916056964386399485392600\\\")\\n\\ndef test_gamma_huge_4():\\n    x = 3200+11500j\\n    mp.dps = 15\\n    assert str(gamma(x)) == \\\\\\n        \\\"(8.95783268539713e+5164 - 1.94678798329735e+5164j)\\\"\\n    mp.dps = 50\\n    assert str(gamma(x)) == (\\\\\\n        \\\"(8.9578326853971339570292952697675570822206567327092e+5164\\\"\\n        \\\" - 1.9467879832973509568895402139429643650329524144794e+51\\\"\\n        \\\"64j)\\\")\\n    mp.dps = 15\\n\\ndef test_gamma_huge_5():\\n    mp.dps = 500\\n    x = 10**60 * j / 3\\n    mp.dps = 15\\n    y = gamma(x)\\n    assert str(y.real) == \\\"-3.27753899634941e-227396058973640224580963937571892628368354580620654233316839\\\"\\n    assert str(y.imag) == \\\"-7.1519888950416e-227396058973640224580963937571892628368354580620654233316841\\\"\\n    mp.dps = 50\\n    y = gamma(x)\\n    assert str(y.real) == (\\\\\\n        \\\"-3.2775389963494132168950056995974690946983219123935e-22739605897364022458096393\\\"\\n        \\\"7571892628368354580620654233316839\\\")\\n    assert str(y.imag) == (\\\\\\n        \\\"-7.1519888950415979749736749222530209713136588885897e-22739605897364022458096393\\\"\\n        \\\"7571892628368354580620654233316841\\\")\\n    mp.dps = 15\\n\\ndef test_gamma_huge_7():\\n    mp.dps = 100\\n    a = 3 + j/mpf(10)**1000\\n    mp.dps = 15\\n    y = gamma(a)\\n    assert str(y.real) == \\\"2.0\\\"\\n    # wrong\\n    #assert str(y.imag) == \\\"2.16735365342606e-1000\\\"\\n    assert str(y.imag) == \\\"1.84556867019693e-1000\\\"\\n    mp.dps = 50\\n    y = gamma(a)\\n    assert str(y.real) == \\\"2.0\\\"\\n    #assert str(y.imag) == \\\"2.1673536534260596065418805612488708028522563689298e-1000\\\"\\n    assert str(y.imag) ==  \\\"1.8455686701969342787869758198351951379156813281202e-1000\\\"\\n\\ndef test_stieltjes():\\n    mp.dps = 15\\n    assert stieltjes(0).ae(+euler)\\n    mp.dps = 25\\n    assert stieltjes(1).ae('-0.07281584548367672486058637587')\\n    assert stieltjes(2).ae('-0.009690363192872318484530386035')\\n    assert stieltjes(3).ae('0.002053834420303345866160046543')\\n    assert stieltjes(4).ae('0.002325370065467300057468170178')\\n    mp.dps = 15\\n    assert stieltjes(1).ae(-0.07281584548367672486058637587)\\n    assert stieltjes(2).ae(-0.009690363192872318484530386035)\\n    assert stieltjes(3).ae(0.002053834420303345866160046543)\\n    assert stieltjes(4).ae(0.0023253700654673000574681701775)\\n\\ndef test_barnesg():\\n    mp.dps = 15\\n    assert barnesg(0) == barnesg(-1) == 0\\n    assert [superfac(i) for i in range(8)] == [1, 1, 2, 12, 288, 34560, 24883200, 125411328000]\\n    assert str(superfac(1000)) == '3.24570818422368e+1177245'\\n    assert isnan(barnesg(nan))\\n    assert isnan(superfac(nan))\\n    assert isnan(hyperfac(nan))\\n    assert barnesg(inf) == inf\\n    assert superfac(inf) == inf\\n    assert hyperfac(inf) == inf\\n    assert isnan(superfac(-inf))\\n    assert barnesg(0.7).ae(0.8068722730141471)\\n    assert barnesg(2+3j).ae(-0.17810213864082169+0.04504542715447838j)\\n    assert [hyperfac(n) for n in range(7)] == [1, 1, 4, 108, 27648, 86400000, 4031078400000]\\n    assert [hyperfac(n) for n in range(0,-7,-1)] == [1,1,-1,-4,108,27648,-86400000]\\n    a = barnesg(-3+0j)\\n    assert a == 0 and isinstance(a, mpc)\\n    a = hyperfac(-3+0j)\\n    assert a == -4 and isinstance(a, mpc)\\n\\ndef test_polylog():\\n    mp.dps = 15\\n    zs = [mpmathify(z) for z in [0, 0.5, 0.99, 4, -0.5, -4, 1j, 3+4j]]\\n    for z in zs: assert polylog(1, z).ae(-log(1-z))\\n    for z in zs: assert polylog(0, z).ae(z/(1-z))\\n    for z in zs: assert polylog(-1, z).ae(z/(1-z)**2)\\n    for z in zs: assert polylog(-2, z).ae(z*(1+z)/(1-z)**3)\\n    for z in zs: assert polylog(-3, z).ae(z*(1+4*z+z**2)/(1-z)**4)\\n    assert polylog(3, 7).ae(5.3192579921456754382-5.9479244480803301023j)\\n    assert polylog(3, -7).ae(-4.5693548977219423182)\\n    assert polylog(2, 0.9).ae(1.2997147230049587252)\\n    assert polylog(2, -0.9).ae(-0.75216317921726162037)\\n    assert polylog(2, 0.9j).ae(-0.17177943786580149299+0.83598828572550503226j)\\n    assert polylog(2, 1.1).ae(1.9619991013055685931-0.2994257606855892575j)\\n    assert polylog(2, -1.1).ae(-0.89083809026228260587)\\n    assert polylog(2, 1.1*sqrt(j)).ae(0.58841571107611387722+1.09962542118827026011j)\\n    assert polylog(-2, 0.9).ae(1710)\\n    assert polylog(-2, -0.9).ae(-90/6859.)\\n    assert polylog(3, 0.9).ae(1.0496589501864398696)\\n    assert polylog(-3, 0.9).ae(48690)\\n    assert polylog(-3, -4).ae(-0.0064)\\n    assert polylog(0.5+j/3, 0.5+j/2).ae(0.31739144796565650535 + 0.99255390416556261437j)\\n    assert polylog(3+4j,1).ae(zeta(3+4j))\\n    assert polylog(3+4j,-1).ae(-altzeta(3+4j))\\n    # issue 390\\n    assert polylog(1.5, -48.910886523731889).ae(-6.272992229311817)\\n    assert polylog(1.5, 200).ae(-8.349608319033686529 - 8.159694826434266042j)\\n    assert polylog(-2+0j, -2).ae(mpf(1)/13.5)\\n    assert polylog(-2+0j, 1.25).ae(-180)\\n\\ndef test_bell_polyexp():\\n    mp.dps = 15\\n    # TODO: more tests for polyexp\\n    assert (polyexp(0,1e-10)*10**10).ae(1.00000000005)\\n    assert (polyexp(1,1e-10)*10**10).ae(1.0000000001)\\n    assert polyexp(5,3j).ae(-607.7044517476176454+519.962786482001476087j)\\n    assert polyexp(-1,3.5).ae(12.09537536175543444)\\n    # bell(0,x) = 1\\n    assert bell(0,0) == 1\\n    assert bell(0,1) == 1\\n    assert bell(0,2) == 1\\n    assert bell(0,inf) == 1\\n    assert bell(0,-inf) == 1\\n    assert isnan(bell(0,nan))\\n    # bell(1,x) = x\\n    assert bell(1,4) == 4\\n    assert bell(1,0) == 0\\n    assert bell(1,inf) == inf\\n    assert bell(1,-inf) == -inf\\n    assert isnan(bell(1,nan))\\n    # bell(2,x) = x*(1+x)\\n    assert bell(2,-1) == 0\\n    assert bell(2,0) == 0\\n    # large orders / arguments\\n    assert bell(10) == 115975\\n    assert bell(10,1) == 115975\\n    assert bell(10, -8) == 11054008\\n    assert bell(5,-50) == -253087550\\n    assert bell(50,-50).ae('3.4746902914629720259e74')\\n    mp.dps = 80\\n    assert bell(50,-50) == 347469029146297202586097646631767227177164818163463279814268368579055777450\\n    assert bell(40,50) == 5575520134721105844739265207408344706846955281965031698187656176321717550\\n    assert bell(74) == 5006908024247925379707076470957722220463116781409659160159536981161298714301202\\n    mp.dps = 15\\n    assert bell(10,20j) == 7504528595600+15649605360020j\\n    # continuity of the generalization\\n    assert bell(0.5,0).ae(sinc(pi*0.5))\\n\\ndef test_primezeta():\\n    mp.dps = 15\\n    assert primezeta(0.9).ae(1.8388316154446882243 + 3.1415926535897932385j)\\n    assert primezeta(4).ae(0.076993139764246844943)\\n    assert primezeta(1) == inf\\n    assert primezeta(inf) == 0\\n    assert isnan(primezeta(nan))\\n\\ndef test_rs_zeta():\\n    mp.dps = 15\\n    assert zeta(0.5+100000j).ae(1.0730320148577531321 + 5.7808485443635039843j)\\n    assert zeta(0.75+100000j).ae(1.837852337251873704 + 1.9988492668661145358j)\\n    assert zeta(0.5+1000000j, derivative=3).ae(1647.7744105852674733 - 1423.1270943036622097j)\\n    assert zeta(1+1000000j, derivative=3).ae(3.4085866124523582894 - 18.179184721525947301j)\\n    assert zeta(1+1000000j, derivative=1).ae(-0.10423479366985452134 - 0.74728992803359056244j)\\n    assert zeta(0.5-1000000j, derivative=1).ae(11.636804066002521459 + 17.127254072212996004j)\\n    # Additional sanity tests using fp arithmetic.\\n    # Some more high-precision tests are found in the docstrings\\n    def ae(x, y, tol=1e-6):\\n        return abs(x-y) < tol*abs(y)\\n    assert ae(fp.zeta(0.5-100000j), 1.0730320148577531321 - 5.7808485443635039843j)\\n    assert ae(fp.zeta(0.75-100000j), 1.837852337251873704 - 1.9988492668661145358j)\\n    assert ae(fp.zeta(0.5+1e6j), 0.076089069738227100006 + 2.8051021010192989554j)\\n    assert ae(fp.zeta(0.5+1e6j, derivative=1), 11.636804066002521459 - 17.127254072212996004j)\\n    assert ae(fp.zeta(1+1e6j), 0.94738726251047891048 + 0.59421999312091832833j)\\n    assert ae(fp.zeta(1+1e6j, derivative=1), -0.10423479366985452134 - 0.74728992803359056244j)\\n    assert ae(fp.zeta(0.5+100000j, derivative=1), 10.766962036817482375 - 30.92705282105996714j)\\n    assert ae(fp.zeta(0.5+100000j, derivative=2), -119.40515625740538429 + 217.14780631141830251j)\\n    assert ae(fp.zeta(0.5+100000j, derivative=3), 1129.7550282628460881 - 1685.4736895169690346j)\\n    assert ae(fp.zeta(0.5+100000j, derivative=4), -10407.160819314958615 + 13777.786698628045085j)\\n    assert ae(fp.zeta(0.75+100000j, derivative=1), -0.41742276699594321475 - 6.4453816275049955949j)\\n    assert ae(fp.zeta(0.75+100000j, derivative=2), -9.214314279161977266 + 35.07290795337967899j)\\n    assert ae(fp.zeta(0.75+100000j, derivative=3), 110.61331857820103469 - 236.87847130518129926j)\\n    assert ae(fp.zeta(0.75+100000j, derivative=4), -1054.334275898559401 + 1769.9177890161596383j)\\n\\ndef test_siegelz():\\n    mp.dps = 15\\n    assert siegelz(100000).ae(5.87959246868176504171)\\n    assert siegelz(100000, derivative=2).ae(-54.1172711010126452832)\\n    assert siegelz(100000, derivative=3).ae(-278.930831343966552538)\\n    assert siegelz(100000+j,derivative=1).ae(678.214511857070283307-379.742160779916375413j)\\n\\n\\n\\ndef test_zeta_near_1():\\n    # Test for a former bug in mpf_zeta and mpc_zeta\\n    mp.dps = 15\\n    s1 = fadd(1, '1e-10', exact=True)\\n    s2 = fadd(1, '-1e-10', exact=True)\\n    s3 = fadd(1, '1e-10j', exact=True)\\n    assert zeta(s1).ae(1.000000000057721566490881444e10)\\n    assert zeta(s2).ae(-9.99999999942278433510574872e9)\\n    z = zeta(s3)\\n    assert z.real.ae(0.57721566490153286060)\\n    assert z.imag.ae(-9.9999999999999999999927184e9)\\n    mp.dps = 30\\n    s1 = fadd(1, '1e-50', exact=True)\\n    s2 = fadd(1, '-1e-50', exact=True)\\n    s3 = fadd(1, '1e-50j', exact=True)\\n    assert zeta(s1).ae('1e50')\\n    assert zeta(s2).ae('-1e50')\\n    z = zeta(s3)\\n    assert z.real.ae('0.57721566490153286060651209008240243104215933593992')\\n    assert z.imag.ae('-1e50')\\n\\n\\n\\\"\\\"\\\"\\nTest bit-level integer and mpf operations\\n\\\"\\\"\\\"\\n\\nfrom mpmath import *\\nfrom mpmath.libmp import *\\n\\ndef test_bitcount():\\n    assert bitcount(0) == 0\\n    assert bitcount(1) == 1\\n    assert bitcount(7) == 3\\n    assert bitcount(8) == 4\\n    assert bitcount(2**100) == 101\\n    assert bitcount(2**100-1) == 100\\n\\ndef test_trailing():\\n    assert trailing(0) == 0\\n    assert trailing(1) == 0\\n    assert trailing(2) == 1\\n    assert trailing(7) == 0\\n    assert trailing(8) == 3\\n    assert trailing(2**100) == 100\\n    assert trailing(2**100-1) == 0\\n\\ndef test_round_down():\\n    assert from_man_exp(0, -4, 4, round_down)[:3] == (0, 0, 0)\\n    assert from_man_exp(0xf0, -4, 4, round_down)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf1, -4, 4, round_down)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xff, -4, 4, round_down)[:3] == (0, 15, 0)\\n    assert from_man_exp(-0xf0, -4, 4, round_down)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf1, -4, 4, round_down)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xff, -4, 4, round_down)[:3] == (1, 15, 0)\\n\\ndef test_round_up():\\n    assert from_man_exp(0, -4, 4, round_up)[:3] == (0, 0, 0)\\n    assert from_man_exp(0xf0, -4, 4, round_up)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf1, -4, 4, round_up)[:3] == (0, 1, 4)\\n    assert from_man_exp(0xff, -4, 4, round_up)[:3] == (0, 1, 4)\\n    assert from_man_exp(-0xf0, -4, 4, round_up)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf1, -4, 4, round_up)[:3] == (1, 1, 4)\\n    assert from_man_exp(-0xff, -4, 4, round_up)[:3] == (1, 1, 4)\\n\\ndef test_round_floor():\\n    assert from_man_exp(0, -4, 4, round_floor)[:3] == (0, 0, 0)\\n    assert from_man_exp(0xf0, -4, 4, round_floor)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf1, -4, 4, round_floor)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xff, -4, 4, round_floor)[:3] == (0, 15, 0)\\n    assert from_man_exp(-0xf0, -4, 4, round_floor)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf1, -4, 4, round_floor)[:3] == (1, 1, 4)\\n    assert from_man_exp(-0xff, -4, 4, round_floor)[:3] == (1, 1, 4)\\n\\ndef test_round_ceiling():\\n    assert from_man_exp(0, -4, 4, round_ceiling)[:3] == (0, 0, 0)\\n    assert from_man_exp(0xf0, -4, 4, round_ceiling)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf1, -4, 4, round_ceiling)[:3] == (0, 1, 4)\\n    assert from_man_exp(0xff, -4, 4, round_ceiling)[:3] == (0, 1, 4)\\n    assert from_man_exp(-0xf0, -4, 4, round_ceiling)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf1, -4, 4, round_ceiling)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xff, -4, 4, round_ceiling)[:3] == (1, 15, 0)\\n\\ndef test_round_nearest():\\n    assert from_man_exp(0, -4, 4, round_nearest)[:3] == (0, 0, 0)\\n    assert from_man_exp(0xf0, -4, 4, round_nearest)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf7, -4, 4, round_nearest)[:3] == (0, 15, 0)\\n    assert from_man_exp(0xf8, -4, 4, round_nearest)[:3] == (0, 1, 4)    # 1111.1000 -> 10000.0\\n    assert from_man_exp(0xf9, -4, 4, round_nearest)[:3] == (0, 1, 4)    # 1111.1001 -> 10000.0\\n    assert from_man_exp(0xe8, -4, 4, round_nearest)[:3] == (0, 7, 1)    # 1110.1000 -> 1110.0\\n    assert from_man_exp(0xe9, -4, 4, round_nearest)[:3] == (0, 15, 0)     # 1110.1001 -> 1111.0\\n    assert from_man_exp(-0xf0, -4, 4, round_nearest)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf7, -4, 4, round_nearest)[:3] == (1, 15, 0)\\n    assert from_man_exp(-0xf8, -4, 4, round_nearest)[:3] == (1, 1, 4)\\n    assert from_man_exp(-0xf9, -4, 4, round_nearest)[:3] == (1, 1, 4)\\n    assert from_man_exp(-0xe8, -4, 4, round_nearest)[:3] == (1, 7, 1)\\n    assert from_man_exp(-0xe9, -4, 4, round_nearest)[:3] == (1, 15, 0)\\n\\ndef test_rounding_bugs():\\n    # 1 less than power-of-two cases\\n    assert from_man_exp(72057594037927935, -56, 53, round_up) == (0, 1, 0, 1)\\n    assert from_man_exp(73786976294838205979, -65, 53, round_nearest) == (0, 1, 1, 1)\\n    assert from_man_exp(31, 0, 4, round_up) == (0, 1, 5, 1)\\n    assert from_man_exp(-31, 0, 4, round_floor) == (1, 1, 5, 1)\\n    assert from_man_exp(255, 0, 7, round_up) == (0, 1, 8, 1)\\n    assert from_man_exp(-255, 0, 7, round_floor) == (1, 1, 8, 1)\\n\\ndef test_rounding_issue_200():\\n    a = from_man_exp(9867,-100)\\n    b = from_man_exp(9867,-200)\\n    c = from_man_exp(-1,0)\\n    z = (1, 1023, -10, 10)\\n    assert mpf_add(a, c, 10, 'd') == z\\n    assert mpf_add(b, c, 10, 'd') == z\\n    assert mpf_add(c, a, 10, 'd') == z\\n    assert mpf_add(c, b, 10, 'd') == z\\n\\ndef test_perturb():\\n    a = fone\\n    b = from_float(0.99999999999999989)\\n    c = from_float(1.0000000000000002)\\n    assert mpf_perturb(a, 0, 53, round_nearest) == a\\n    assert mpf_perturb(a, 1, 53, round_nearest) == a\\n    assert mpf_perturb(a, 0, 53, round_up) == c\\n    assert mpf_perturb(a, 0, 53, round_ceiling) == c\\n    assert mpf_perturb(a, 0, 53, round_down) == a\\n    assert mpf_perturb(a, 0, 53, round_floor) == a\\n    assert mpf_perturb(a, 1, 53, round_up) == a\\n    assert mpf_perturb(a, 1, 53, round_ceiling) == a\\n    assert mpf_perturb(a, 1, 53, round_down) == b\\n    assert mpf_perturb(a, 1, 53, round_floor) == b\\n    a = mpf_neg(a)\\n    b = mpf_neg(b)\\n    c = mpf_neg(c)\\n    assert mpf_perturb(a, 0, 53, round_nearest) == a\\n    assert mpf_perturb(a, 1, 53, round_nearest) == a\\n    assert mpf_perturb(a, 0, 53, round_up) == a\\n    assert mpf_perturb(a, 0, 53, round_floor) == a\\n    assert mpf_perturb(a, 0, 53, round_down) == b\\n    assert mpf_perturb(a, 0, 53, round_ceiling) == b\\n    assert mpf_perturb(a, 1, 53, round_up) == c\\n    assert mpf_perturb(a, 1, 53, round_floor) == c\\n    assert mpf_perturb(a, 1, 53, round_down) == a\\n    assert mpf_perturb(a, 1, 53, round_ceiling) == a\\n\\ndef test_add_exact():\\n    ff = from_float\\n    assert mpf_add(ff(3.0), ff(2.5)) == ff(5.5)\\n    assert mpf_add(ff(3.0), ff(-2.5)) == ff(0.5)\\n    assert mpf_add(ff(-3.0), ff(2.5)) == ff(-0.5)\\n    assert mpf_add(ff(-3.0), ff(-2.5)) == ff(-5.5)\\n    assert mpf_sub(mpf_add(fone, ff(1e-100)), fone) == ff(1e-100)\\n    assert mpf_sub(mpf_add(ff(1e-100), fone), fone) == ff(1e-100)\\n    assert mpf_sub(mpf_add(fone, ff(-1e-100)), fone) == ff(-1e-100)\\n    assert mpf_sub(mpf_add(ff(-1e-100), fone), fone) == ff(-1e-100)\\n    assert mpf_add(fone, fzero) == fone\\n    assert mpf_add(fzero, fone) == fone\\n    assert mpf_add(fzero, fzero) == fzero\\n\\ndef test_long_exponent_shifts():\\n    mp.dps = 15\\n    # Check for possible bugs due to exponent arithmetic overflow\\n    # in a C implementation\\n    x = mpf(1)\\n    for p in [32, 64]:\\n        a = ldexp(1,2**(p-1))\\n        b = ldexp(1,2**p)\\n        c = ldexp(1,2**(p+1))\\n        d = ldexp(1,-2**(p-1))\\n        e = ldexp(1,-2**p)\\n        f = ldexp(1,-2**(p+1))\\n        assert (x+a) == a\\n        assert (x+b) == b\\n        assert (x+c) == c\\n        assert (x+d) == x\\n        assert (x+e) == x\\n        assert (x+f) == x\\n        assert (a+x) == a\\n        assert (b+x) == b\\n        assert (c+x) == c\\n        assert (d+x) == x\\n        assert (e+x) == x\\n        assert (f+x) == x\\n        assert (x-a) == -a\\n        assert (x-b) == -b\\n        assert (x-c) == -c\\n        assert (x-d) == x\\n        assert (x-e) == x\\n        assert (x-f) == x\\n        assert (a-x) == a\\n        assert (b-x) == b\\n        assert (c-x) == c\\n        assert (d-x) == -x\\n        assert (e-x) == -x\\n        assert (f-x) == -x\\n\\ndef test_float_rounding():\\n    mp.prec = 64\\n    for x in [mpf(1), mpf(1)+eps, mpf(1)-eps, -mpf(1)+eps, -mpf(1)-eps]:\\n        fa = float(x)\\n        fb = float(fadd(x,0,prec=53,rounding='n'))\\n        assert fa == fb\\n        z = mpc(x,x)\\n        ca = complex(z)\\n        cb = complex(fadd(z,0,prec=53,rounding='n'))\\n        assert ca == cb\\n        for rnd in ['n', 'd', 'u', 'f', 'c']:\\n            fa = to_float(x._mpf_, rnd=rnd)\\n            fb = to_float(fadd(x,0,prec=53,rounding=rnd)._mpf_, rnd=rnd)\\n            assert fa == fb\\n    mp.prec = 53\\n\\n\\nimport mpmath\\nfrom mpmath import *\\nfrom mpmath.libmp import *\\nimport random\\nimport sys\\n\\ntry:\\n    long = long\\nexcept NameError:\\n    long = int\\n\\ndef test_type_compare():\\n    assert mpf(2) == mpc(2,0)\\n    assert mpf(0) == mpc(0)\\n    assert mpf(2) != mpc(2, 0.00001)\\n    assert mpf(2) == 2.0\\n    assert mpf(2) != 3.0\\n    assert mpf(2) == 2\\n    assert mpf(2) != '2.0'\\n    assert mpc(2) != '2.0'\\n\\ndef test_add():\\n    assert mpf(2.5) + mpf(3) == 5.5\\n    assert mpf(2.5) + 3 == 5.5\\n    assert mpf(2.5) + 3.0 == 5.5\\n    assert 3 + mpf(2.5) == 5.5\\n    assert 3.0 + mpf(2.5) == 5.5\\n    assert (3+0j) + mpf(2.5) == 5.5\\n    assert mpc(2.5) + mpf(3) == 5.5\\n    assert mpc(2.5) + 3 == 5.5\\n    assert mpc(2.5) + 3.0 == 5.5\\n    assert mpc(2.5) + (3+0j) == 5.5\\n    assert 3 + mpc(2.5) == 5.5\\n    assert 3.0 + mpc(2.5) == 5.5\\n    assert (3+0j) + mpc(2.5) == 5.5\\n\\ndef test_sub():\\n    assert mpf(2.5) - mpf(3) == -0.5\\n    assert mpf(2.5) - 3 == -0.5\\n    assert mpf(2.5) - 3.0 == -0.5\\n    assert 3 - mpf(2.5) == 0.5\\n    assert 3.0 - mpf(2.5) == 0.5\\n    assert (3+0j) - mpf(2.5) == 0.5\\n    assert mpc(2.5) - mpf(3) == -0.5\\n    assert mpc(2.5) - 3 == -0.5\\n    assert mpc(2.5) - 3.0 == -0.5\\n    assert mpc(2.5) - (3+0j) == -0.5\\n    assert 3 - mpc(2.5) == 0.5\\n    assert 3.0 - mpc(2.5) == 0.5\\n    assert (3+0j) - mpc(2.5) == 0.5\\n\\ndef test_mul():\\n    assert mpf(2.5) * mpf(3) == 7.5\\n    assert mpf(2.5) * 3 == 7.5\\n    assert mpf(2.5) * 3.0 == 7.5\\n    assert 3 * mpf(2.5) == 7.5\\n    assert 3.0 * mpf(2.5) == 7.5\\n    assert (3+0j) * mpf(2.5) == 7.5\\n    assert mpc(2.5) * mpf(3) == 7.5\\n    assert mpc(2.5) * 3 == 7.5\\n    assert mpc(2.5) * 3.0 == 7.5\\n    assert mpc(2.5) * (3+0j) == 7.5\\n    assert 3 * mpc(2.5) == 7.5\\n    assert 3.0 * mpc(2.5) == 7.5\\n    assert (3+0j) * mpc(2.5) == 7.5\\n\\ndef test_div():\\n    assert mpf(6) / mpf(3) == 2.0\\n    assert mpf(6) / 3 == 2.0\\n    assert mpf(6) / 3.0 == 2.0\\n    assert 6 / mpf(3) == 2.0\\n    assert 6.0 / mpf(3) == 2.0\\n    assert (6+0j) / mpf(3.0) == 2.0\\n    assert mpc(6) / mpf(3) == 2.0\\n    assert mpc(6) / 3 == 2.0\\n    assert mpc(6) / 3.0 == 2.0\\n    assert mpc(6) / (3+0j) == 2.0\\n    assert 6 / mpc(3) == 2.0\\n    assert 6.0 / mpc(3) == 2.0\\n    assert (6+0j) / mpc(3) == 2.0\\n\\ndef test_pow():\\n    assert mpf(6) ** mpf(3) == 216.0\\n    assert mpf(6) ** 3 == 216.0\\n    assert mpf(6) ** 3.0 == 216.0\\n    assert 6 ** mpf(3) == 216.0\\n    assert 6.0 ** mpf(3) == 216.0\\n    assert (6+0j) ** mpf(3.0) == 216.0\\n    assert mpc(6) ** mpf(3) == 216.0\\n    assert mpc(6) ** 3 == 216.0\\n    assert mpc(6) ** 3.0 == 216.0\\n    assert mpc(6) ** (3+0j) == 216.0\\n    assert 6 ** mpc(3) == 216.0\\n    assert 6.0 ** mpc(3) == 216.0\\n    assert (6+0j) ** mpc(3) == 216.0\\n\\ndef test_mixed_misc():\\n    assert 1 + mpf(3) == mpf(3) + 1 == 4\\n    assert 1 - mpf(3) == -(mpf(3) - 1) == -2\\n    assert 3 * mpf(2) == mpf(2) * 3 == 6\\n    assert 6 / mpf(2) == mpf(6) / 2 == 3\\n    assert 1.0 + mpf(3) == mpf(3) + 1.0 == 4\\n    assert 1.0 - mpf(3) == -(mpf(3) - 1.0) == -2\\n    assert 3.0 * mpf(2) == mpf(2) * 3.0 == 6\\n    assert 6.0 / mpf(2) == mpf(6) / 2.0 == 3\\n\\ndef test_add_misc():\\n    mp.dps = 15\\n    assert mpf(4) + mpf(-70) == -66\\n    assert mpf(1) + mpf(1.1)/80 == 1 + 1.1/80\\n    assert mpf((1, 10000000000)) + mpf(3) == mpf((1, 10000000000))\\n    assert mpf(3) + mpf((1, 10000000000)) == mpf((1, 10000000000))\\n    assert mpf((1, -10000000000)) + mpf(3) == mpf(3)\\n    assert mpf(3) + mpf((1, -10000000000)) == mpf(3)\\n    assert mpf(1) + 1e-15 != 1\\n    assert mpf(1) + 1e-20 == 1\\n    assert mpf(1.07e-22) + 0 == mpf(1.07e-22)\\n    assert mpf(0) + mpf(1.07e-22) == mpf(1.07e-22)\\n\\ndef test_complex_misc():\\n    # many more tests needed\\n    assert 1 + mpc(2) == 3\\n    assert not mpc(2).ae(2 + 1e-13)\\n    assert mpc(2+1e-15j).ae(2)\\n\\ndef test_complex_zeros():\\n    for a in [0,2]:\\n        for b in [0,3]:\\n            for c in [0,4]:\\n                for d in [0,5]:\\n                    assert mpc(a,b)*mpc(c,d) == complex(a,b)*complex(c,d)\\n\\ndef test_hash():\\n    for i in range(-256, 256):\\n        assert hash(mpf(i)) == hash(i)\\n    assert hash(mpf(0.5)) == hash(0.5)\\n    assert hash(mpc(2,3)) == hash(2+3j)\\n    # Check that this doesn't fail\\n    assert hash(inf)\\n    # Check that overflow doesn't assign equal hashes to large numbers\\n    assert hash(mpf('1e1000')) != hash('1e10000')\\n    assert hash(mpc(100,'1e1000')) != hash(mpc(200,'1e1000'))\\n    from mpmath.rational import mpq\\n    assert hash(mp.mpq(1,3))\\n    assert hash(mp.mpq(0,1)) == 0\\n    assert hash(mp.mpq(-1,1)) == hash(-1)\\n    assert hash(mp.mpq(1,1)) == hash(1)\\n    assert hash(mp.mpq(5,1)) == hash(5)\\n    assert hash(mp.mpq(1,2)) == hash(0.5)\\n    if sys.version_info >= (3, 2):\\n        assert hash(mpf(1)*2**2000) == hash(2**2000)\\n        assert hash(mpf(1)/2**2000) == hash(mpq(1,2**2000))\\n\\n# Advanced rounding test\\ndef test_add_rounding():\\n    mp.dps = 15\\n    a = from_float(1e-50)\\n    assert mpf_sub(mpf_add(fone, a, 53, round_up), fone, 53, round_up) == from_float(2.2204460492503131e-16)\\n    assert mpf_sub(fone, a, 53, round_up) == fone\\n    assert mpf_sub(fone, mpf_sub(fone, a, 53, round_down), 53, round_down) == from_float(1.1102230246251565e-16)\\n    assert mpf_add(fone, a, 53, round_down) == fone\\n\\ndef test_almost_equal():\\n    assert mpf(1.2).ae(mpf(1.20000001), 1e-7)\\n    assert not mpf(1.2).ae(mpf(1.20000001), 1e-9)\\n    assert not mpf(-0.7818314824680298).ae(mpf(-0.774695868667929))\\n\\ndef test_arithmetic_functions():\\n    import operator\\n    ops = [(operator.add, fadd), (operator.sub, fsub), (operator.mul, fmul),\\n        (operator.truediv, fdiv)]\\n    a = mpf(0.27)\\n    b = mpf(1.13)\\n    c = mpc(0.51+2.16j)\\n    d = mpc(1.08-0.99j)\\n    for x in [a,b,c,d]:\\n        for y in [a,b,c,d]:\\n            for op, fop in ops:\\n                if fop is not fdiv:\\n                    mp.prec = 200\\n                    z0 = op(x,y)\\n                mp.prec = 60\\n                z1 = op(x,y)\\n                mp.prec = 53\\n                z2 = op(x,y)\\n                assert fop(x, y, prec=60) == z1\\n                assert fop(x, y) == z2\\n                if fop is not fdiv:\\n                    assert fop(x, y, prec=inf) == z0\\n                    assert fop(x, y, dps=inf) == z0\\n                    assert fop(x, y, exact=True) == z0\\n                assert fneg(fneg(z1, exact=True), prec=inf) == z1\\n                assert fneg(z1) == -(+z1)\\n    mp.dps = 15\\n\\ndef test_exact_integer_arithmetic():\\n    # XXX: re-fix this so that all operations are tested with all rounding modes\\n    random.seed(0)\\n    for prec in [6, 10, 25, 40, 100, 250, 725]:\\n        for rounding in ['d', 'u', 'f', 'c', 'n']:\\n            mp.dps = prec\\n            M = 10**(prec-2)\\n            M2 = 10**(prec//2-2)\\n            for i in range(10):\\n                a = random.randint(-M, M)\\n                b = random.randint(-M, M)\\n                assert mpf(a, rounding=rounding) == a\\n                assert int(mpf(a, rounding=rounding)) == a\\n                assert int(mpf(str(a), rounding=rounding)) == a\\n                assert mpf(a) + mpf(b) == a + b\\n                assert mpf(a) - mpf(b) == a - b\\n                assert -mpf(a) == -a\\n                a = random.randint(-M2, M2)\\n                b = random.randint(-M2, M2)\\n                assert mpf(a) * mpf(b) == a*b\\n                assert mpf_mul(from_int(a), from_int(b), mp.prec, rounding) == from_int(a*b)\\n    mp.dps = 15\\n\\ndef test_odd_int_bug():\\n    assert to_int(from_int(3), round_nearest) == 3\\n\\ndef test_str_1000_digits():\\n    mp.dps = 1001\\n    # last digit may be wrong\\n    assert str(mpf(2)**0.5)[-10:-1] == '9518488472'[:9]\\n    assert str(pi)[-10:-1] == '2164201989'[:9]\\n    mp.dps = 15\\n\\ndef test_str_10000_digits():\\n    mp.dps = 10001\\n    # last digit may be wrong\\n    assert str(mpf(2)**0.5)[-10:-1] == '5873258351'[:9]\\n    assert str(pi)[-10:-1] == '5256375678'[:9]\\n    mp.dps = 15\\n\\ndef test_monitor():\\n    f = lambda x: x**2\\n    a = []\\n    b = []\\n    g = monitor(f, a.append, b.append)\\n    assert g(3) == 9\\n    assert g(4) == 16\\n    assert a[0] == ((3,), {})\\n    assert b[0] == 9\\n\\ndef test_nint_distance():\\n    assert nint_distance(mpf(-3)) == (-3, -inf)\\n    assert nint_distance(mpc(-3)) == (-3, -inf)\\n    assert nint_distance(mpf(-3.1)) == (-3, -3)\\n    assert nint_distance(mpf(-3.01)) == (-3, -6)\\n    assert nint_distance(mpf(-3.001)) == (-3, -9)\\n    assert nint_distance(mpf(-3.0001)) == (-3, -13)\\n    assert nint_distance(mpf(-2.9)) == (-3, -3)\\n    assert nint_distance(mpf(-2.99)) == (-3, -6)\\n    assert nint_distance(mpf(-2.999)) == (-3, -9)\\n    assert nint_distance(mpf(-2.9999)) == (-3, -13)\\n    assert nint_distance(mpc(-3+0.1j)) == (-3, -3)\\n    assert nint_distance(mpc(-3+0.01j)) == (-3, -6)\\n    assert nint_distance(mpc(-3.1+0.1j)) == (-3, -3)\\n    assert nint_distance(mpc(-3.01+0.01j)) == (-3, -6)\\n    assert nint_distance(mpc(-3.001+0.001j)) == (-3, -9)\\n    assert nint_distance(mpf(0)) == (0, -inf)\\n    assert nint_distance(mpf(0.01)) == (0, -6)\\n    assert nint_distance(mpf('1e-100')) == (0, -332)\\n\\ndef test_floor_ceil_nint_frac():\\n    mp.dps = 15\\n    for n in range(-10,10):\\n        assert floor(n) == n\\n        assert floor(n+0.5) == n\\n        assert ceil(n) == n\\n        assert ceil(n+0.5) == n+1\\n        assert nint(n) == n\\n        # nint rounds to even\\n        if n % 2 == 1:\\n            assert nint(n+0.5) == n+1\\n        else:\\n            assert nint(n+0.5) == n\\n    assert floor(inf) == inf\\n    assert floor(ninf) == ninf\\n    assert isnan(floor(nan))\\n    assert ceil(inf) == inf\\n    assert ceil(ninf) == ninf\\n    assert isnan(ceil(nan))\\n    assert nint(inf) == inf\\n    assert nint(ninf) == ninf\\n    assert isnan(nint(nan))\\n    assert floor(0.1) == 0\\n    assert floor(0.9) == 0\\n    assert floor(-0.1) == -1\\n    assert floor(-0.9) == -1\\n    assert floor(10000000000.1) == 10000000000\\n    assert floor(10000000000.9) == 10000000000\\n    assert floor(-10000000000.1) == -10000000000-1\\n    assert floor(-10000000000.9) == -10000000000-1\\n    assert floor(1e-100) == 0\\n    assert floor(-1e-100) == -1\\n    assert floor(1e100) == 1e100\\n    assert floor(-1e100) == -1e100\\n    assert ceil(0.1) == 1\\n    assert ceil(0.9) == 1\\n    assert ceil(-0.1) == 0\\n    assert ceil(-0.9) == 0\\n    assert ceil(10000000000.1) == 10000000000+1\\n    assert ceil(10000000000.9) == 10000000000+1\\n    assert ceil(-10000000000.1) == -10000000000\\n    assert ceil(-10000000000.9) == -10000000000\\n    assert ceil(1e-100) == 1\\n    assert ceil(-1e-100) == 0\\n    assert ceil(1e100) == 1e100\\n    assert ceil(-1e100) == -1e100\\n    assert nint(0.1) == 0\\n    assert nint(0.9) == 1\\n    assert nint(-0.1) == 0\\n    assert nint(-0.9) == -1\\n    assert nint(10000000000.1) == 10000000000\\n    assert nint(10000000000.9) == 10000000000+1\\n    assert nint(-10000000000.1) == -10000000000\\n    assert nint(-10000000000.9) == -10000000000-1\\n    assert nint(1e-100) == 0\\n    assert nint(-1e-100) == 0\\n    assert nint(1e100) == 1e100\\n    assert nint(-1e100) == -1e100\\n    assert floor(3.2+4.6j) == 3+4j\\n    assert ceil(3.2+4.6j) == 4+5j\\n    assert nint(3.2+4.6j) == 3+5j\\n    for n in range(-10,10):\\n        assert frac(n) == 0\\n    assert frac(0.25) == 0.25\\n    assert frac(1.25) == 0.25\\n    assert frac(2.25) == 0.25\\n    assert frac(-0.25) == 0.75\\n    assert frac(-1.25) == 0.75\\n    assert frac(-2.25) == 0.75\\n    assert frac('1e100000000000000') == 0\\n    u = mpf('1e-100000000000000')\\n    assert frac(u) == u\\n    assert frac(-u) == 1  # rounding!\\n    u = mpf('1e-400')\\n    assert frac(-u, prec=0) == fsub(1, u, exact=True)\\n    assert frac(3.25+4.75j) == 0.25+0.75j\\n\\ndef test_isnan_etc():\\n    from mpmath.rational import mpq\\n    assert isnan(nan) == True\\n    assert isnan(3) == False\\n    assert isnan(mpf(3)) == False\\n    assert isnan(inf) == False\\n    assert isnan(mpc(2,nan)) == True\\n    assert isnan(mpc(2,nan)) == True\\n    assert isnan(mpc(nan,nan)) == True\\n    assert isnan(mpc(2,2)) == False\\n    assert isnan(mpc(nan,inf)) == True\\n    assert isnan(mpc(inf,inf)) == False\\n    assert isnan(mpq((3,2))) == False\\n    assert isnan(mpq((0,1))) == False\\n    assert isinf(inf) == True\\n    assert isinf(-inf) == True\\n    assert isinf(3) == False\\n    assert isinf(nan) == False\\n    assert isinf(3+4j) == False\\n    assert isinf(mpc(inf)) == True\\n    assert isinf(mpc(3,inf)) == True\\n    assert isinf(mpc(inf,3)) == True\\n    assert isinf(mpc(inf,inf)) == True\\n    assert isinf(mpc(nan,inf)) == True\\n    assert isinf(mpc(inf,nan)) == True\\n    assert isinf(mpc(nan,nan)) == False\\n    assert isinf(mpq((3,2))) == False\\n    assert isinf(mpq((0,1))) == False\\n    assert isnormal(3) == True\\n    assert isnormal(3.5) == True\\n    assert isnormal(mpf(3.5)) == True\\n    assert isnormal(0) == False\\n    assert isnormal(mpf(0)) == False\\n    assert isnormal(0.0) == False\\n    assert isnormal(inf) == False\\n    assert isnormal(-inf) == False\\n    assert isnormal(nan) == False\\n    assert isnormal(float(inf)) == False\\n    assert isnormal(mpc(0,0)) == False\\n    assert isnormal(mpc(3,0)) == True\\n    assert isnormal(mpc(0,3)) == True\\n    assert isnormal(mpc(3,3)) == True\\n    assert isnormal(mpc(0,nan)) == False\\n    assert isnormal(mpc(0,inf)) == False\\n    assert isnormal(mpc(3,nan)) == False\\n    assert isnormal(mpc(3,inf)) == False\\n    assert isnormal(mpc(3,-inf)) == False\\n    assert isnormal(mpc(nan,0)) == False\\n    assert isnormal(mpc(inf,0)) == False\\n    assert isnormal(mpc(nan,3)) == False\\n    assert isnormal(mpc(inf,3)) == False\\n    assert isnormal(mpc(inf,nan)) == False\\n    assert isnormal(mpc(nan,inf)) == False\\n    assert isnormal(mpc(nan,nan)) == False\\n    assert isnormal(mpc(inf,inf)) == False\\n    assert isnormal(mpq((3,2))) == True\\n    assert isnormal(mpq((0,1))) == False\\n    assert isint(3) == True\\n    assert isint(0) == True\\n    assert isint(long(3)) == True\\n    assert isint(long(0)) == True\\n    assert isint(mpf(3)) == True\\n    assert isint(mpf(0)) == True\\n    assert isint(mpf(-3)) == True\\n    assert isint(mpf(3.2)) == False\\n    assert isint(3.2) == False\\n    assert isint(nan) == False\\n    assert isint(inf) == False\\n    assert isint(-inf) == False\\n    assert isint(mpc(0)) == True\\n    assert isint(mpc(3)) == True\\n    assert isint(mpc(3.2)) == False\\n    assert isint(mpc(3,inf)) == False\\n    assert isint(mpc(inf)) == False\\n    assert isint(mpc(3,2)) == False\\n    assert isint(mpc(0,2)) == False\\n    assert isint(mpc(3,2),gaussian=True) == True\\n    assert isint(mpc(3,0),gaussian=True) == True\\n    assert isint(mpc(0,3),gaussian=True) == True\\n    assert isint(3+4j) == False\\n    assert isint(3+4j, gaussian=True) == True\\n    assert isint(3+0j) == True\\n    assert isint(mpq((3,2))) == False\\n    assert isint(mpq((3,9))) == False\\n    assert isint(mpq((9,3))) == True\\n    assert isint(mpq((0,4))) == True\\n    assert isint(mpq((1,1))) == True\\n    assert isint(mpq((-1,1))) == True\\n    assert mp.isnpint(0) == True\\n    assert mp.isnpint(1) == False\\n    assert mp.isnpint(-1) == True\\n    assert mp.isnpint(-1.1) == False\\n    assert mp.isnpint(-1.0) == True\\n    assert mp.isnpint(mp.mpq(1,2)) == False\\n    assert mp.isnpint(mp.mpq(-1,2)) == False\\n    assert mp.isnpint(mp.mpq(-3,1)) == True\\n    assert mp.isnpint(mp.mpq(0,1)) == True\\n    assert mp.isnpint(mp.mpq(1,1)) == False\\n    assert mp.isnpint(0+0j) == True\\n    assert mp.isnpint(-1+0j) == True\\n    assert mp.isnpint(-1.1+0j) == False\\n    assert mp.isnpint(-1+0.1j) == False\\n    assert mp.isnpint(0+0.1j) == False\\n\\n\\ndef test_issue_438():\\n    assert mpf(finf) == mpf('inf')\\n    assert mpf(fninf) == mpf('-inf')\\n    assert mpf(fnan)._mpf_ == mpf('nan')._mpf_\\n\\n\\nfrom mpmath.libmp import *\\nfrom mpmath import *\\n\\ndef test_newstyle_classes():\\n    for cls in [mp, fp, iv, mpf, mpc]:\\n        for s in cls.__class__.__mro__:\\n            assert isinstance(s, type)\\n\\n\\nfrom mpmath import *\\nfrom mpmath.libmp import ifac\\n\\nimport sys\\nif \\\"-dps\\\" in sys.argv:\\n    maxdps = int(sys.argv[sys.argv.index(\\\"-dps\\\")+1])\\nelse:\\n    maxdps = 1000\\n\\nraise_ = \\\"-raise\\\" in sys.argv\\n\\nerrcount = 0\\n\\ndef check(name, func, z, y):\\n    global errcount\\n    try:\\n        x = func(z)\\n    except:\\n        errcount += 1\\n        if raise_:\\n            raise\\n        print()\\n        print(name)\\n        print(\\\"EXCEPTION\\\")\\n        import traceback\\n        traceback.print_tb(sys.exc_info()[2])\\n        print()\\n        return\\n    xre = x.real\\n    xim = x.imag\\n    yre = y.real\\n    yim = y.imag\\n    tol = eps*8\\n    err = 0\\n    if abs(xre-yre) > abs(yre)*tol:\\n        err = 1\\n        print()\\n        print(\\\"Error! %s (re = %s, wanted %s, err=%s)\\\" % (name, nstr(xre,10), nstr(yre,10), nstr(abs(xre-yre))))\\n        errcount += 1\\n        if raise_:\\n            raise SystemExit\\n    if abs(xim-yim) > abs(yim)*tol:\\n        err = 1\\n        print()\\n        print(\\\"Error! %s (im = %s, wanted %s, err=%s)\\\" % (name, nstr(xim,10), nstr(yim,10), nstr(abs(xim-yim))))\\n        errcount += 1\\n        if raise_:\\n            raise SystemExit\\n    if not err:\\n        sys.stdout.write(\\\"%s ok; \\\" % name)\\n\\ndef testcase(case):\\n    z, result = case\\n    print(\\\"Testing z =\\\", z)\\n    mp.dps = 1010\\n    z = eval(z)\\n    mp.dps = maxdps + 50\\n    if result is None:\\n        gamma_val = gamma(z)\\n        loggamma_val = loggamma(z)\\n        factorial_val = factorial(z)\\n        rgamma_val = rgamma(z)\\n    else:\\n        loggamma_val = eval(result)\\n        gamma_val = exp(loggamma_val)\\n        factorial_val = z * gamma_val\\n        rgamma_val = 1/gamma_val\\n    for dps in [5, 10, 15, 25, 40, 60, 90, 120, 250, 600, 1000, 1800, 3600]:\\n        if dps > maxdps:\\n            break\\n        mp.dps = dps\\n        print(\\\"dps = %s\\\" % dps)\\n        check(\\\"gamma\\\", gamma, z, gamma_val)\\n        check(\\\"rgamma\\\", rgamma, z, rgamma_val)\\n        check(\\\"loggamma\\\", loggamma, z, loggamma_val)\\n        check(\\\"factorial\\\", factorial, z, factorial_val)\\n        print()\\n        mp.dps = 15\\n\\ntestcases = []\\n\\n# Basic values\\nfor n in list(range(1,200)) + list(range(201,2000,17)):\\n    testcases.append([\\\"%s\\\" % n, None])\\nfor n in range(-200,200):\\n    testcases.append([\\\"%s+0.5\\\" % n, None])\\n    testcases.append([\\\"%s+0.37\\\" % n, None])\\n\\ntestcases += [\\\\\\n[\\\"(0.1+1j)\\\", None],\\n[\\\"(-0.1+1j)\\\", None],\\n[\\\"(0.1-1j)\\\", None],\\n[\\\"(-0.1-1j)\\\", None],\\n[\\\"10j\\\", None],\\n[\\\"-10j\\\", None],\\n[\\\"100j\\\", None],\\n[\\\"10000j\\\", None],\\n[\\\"-10000000j\\\", None],\\n[\\\"(10**100)*j\\\", None],\\n[\\\"125+(10**100)*j\\\", None],\\n[\\\"-125+(10**100)*j\\\", None],\\n[\\\"(10**10)*(1+j)\\\", None],\\n[\\\"(10**10)*(-1+j)\\\", None],\\n[\\\"(10**100)*(1+j)\\\", None],\\n[\\\"(10**100)*(-1+j)\\\", None],\\n[\\\"(1.5-1j)\\\", None],\\n[\\\"(6+4j)\\\", None],\\n[\\\"(4+1j)\\\", None],\\n[\\\"(3.5+2j)\\\", None],\\n[\\\"(1.5-1j)\\\", None],\\n[\\\"(-6-4j)\\\", None],\\n[\\\"(-2-3j)\\\", None],\\n[\\\"(-2.5-2j)\\\", None],\\n[\\\"(4+1j)\\\", None],\\n[\\\"(3+3j)\\\", None],\\n[\\\"(2-2j)\\\", None],\\n[\\\"1\\\", \\\"0\\\"],\\n[\\\"2\\\", \\\"0\\\"],\\n[\\\"3\\\", \\\"log(2)\\\"],\\n[\\\"4\\\", \\\"log(6)\\\"],\\n[\\\"5\\\", \\\"log(24)\\\"],\\n[\\\"0.5\\\", \\\"log(pi)/2\\\"],\\n[\\\"1.5\\\", \\\"log(sqrt(pi)/2)\\\"],\\n[\\\"2.5\\\", \\\"log(3*sqrt(pi)/4)\\\"],\\n[\\\"mpf('0.37')\\\", None],\\n[\\\"0.25\\\", \\\"log(sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2))))\\\"],\\n[\\\"-0.4\\\", None],\\n[\\\"mpf('-1.9')\\\", None],\\n[\\\"mpf('12.8')\\\", None],\\n[\\\"mpf('33.7')\\\", None],\\n[\\\"mpf('95.2')\\\", None],\\n[\\\"mpf('160.3')\\\", None],\\n[\\\"mpf('2057.8')\\\", None],\\n[\\\"25\\\", \\\"log(ifac(24))\\\"],\\n[\\\"80\\\", \\\"log(ifac(79))\\\"],\\n[\\\"500\\\", \\\"log(ifac(500-1))\\\"],\\n[\\\"8000\\\", \\\"log(ifac(8000-1))\\\"],\\n[\\\"8000.5\\\", None],\\n[\\\"mpf('8000.1')\\\", None],\\n[\\\"mpf('1.37e10')\\\", None],\\n[\\\"mpf('1.37e10')*(1+j)\\\", None],\\n[\\\"mpf('1.37e10')*(-1+j)\\\", None],\\n[\\\"mpf('1.37e10')*(-1-j)\\\", None],\\n[\\\"mpf('1.37e10')*(-1+j)\\\", None],\\n[\\\"mpf('1.37e100')\\\", None],\\n[\\\"mpf('1.37e100')*(1+j)\\\", None],\\n[\\\"mpf('1.37e100')*(-1+j)\\\", None],\\n[\\\"mpf('1.37e100')*(-1-j)\\\", None],\\n[\\\"mpf('1.37e100')*(-1+j)\\\", None],\\n[\\\"3+4j\\\",\\n\\\"mpc('\\\"\\n\\\"-1.7566267846037841105306041816232757851567066070613445016197619371316057169\\\"\\n\\\"4723618263960834804618463052988607348289672535780644470689771115236512106002\\\"\\n\\\"5970873471563240537307638968509556191696167970488390423963867031934333890838\\\"\\n\\\"8009531786948197210025029725361069435208930363494971027388382086721660805397\\\"\\n\\\"9163230643216054580167976201709951509519218635460317367338612500626714783631\\\"\\n\\\"7498317478048447525674016344322545858832610325861086336204591943822302971823\\\"\\n\\\"5161814175530618223688296232894588415495615809337292518431903058265147109853\\\"\\n\\\"1710568942184987827643886816200452860853873815413367529829631430146227470517\\\"\\n\\\"6579967222200868632179482214312673161276976117132204633283806161971389519137\\\"\\n\\\"1243359764435612951384238091232760634271570950240717650166551484551654327989\\\"\\n\\\"9360285030081716934130446150245110557038117075172576825490035434069388648124\\\"\\n\\\"6678152254554001586736120762641422590778766100376515737713938521275749049949\\\"\\n\\\"1284143906816424244705094759339932733567910991920631339597278805393743140853\\\"\\n\\\"391550313363278558195609260225928','\\\"\\n\\\"4.74266443803465792819488940755002274088830335171164611359052405215840070271\\\"\\n\\\"5906813009373171139767051863542508136875688550817670379002790304870822775498\\\"\\n\\\"2809996675877564504192565392367259119610438951593128982646945990372179860613\\\"\\n\\\"4294436498090428077839141927485901735557543641049637962003652638924845391650\\\"\\n\\\"9546290137755550107224907606529385248390667634297183361902055842228798984200\\\"\\n\\\"9591180450211798341715874477629099687609819466457990642030707080894518168924\\\"\\n\\\"6805549314043258530272479246115112769957368212585759640878745385160943755234\\\"\\n\\\"9398036774908108204370323896757543121853650025529763655312360354244898913463\\\"\\n\\\"7115955702828838923393113618205074162812089732064414530813087483533203244056\\\"\\n\\\"0546577484241423134079056537777170351934430586103623577814746004431994179990\\\"\\n\\\"5318522939077992613855205801498201930221975721246498720895122345420698451980\\\"\\n\\\"0051215797310305885845964334761831751370672996984756815410977750799748813563\\\"\\n\\\"8784405288158432214886648743541773208808731479748217023665577802702269468013\\\"\\n\\\"673719173759245720489020315779001')\\\"],\\n]\\n\\nfor z in [4, 14, 34, 64]:\\n    testcases.append([\\\"(2+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(-2+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(1+2*j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(2-j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(20+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(-20+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(1+20*j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(20-j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(200+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(-200+j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(1+200*j)*%s/3\\\" % z, None])\\n    testcases.append([\\\"(200-j)*%s/3\\\" % z, None])\\n\\n# Poles\\nfor n in [0,1,2,3,4,25,-1,-2,-3,-4,-20,-21,-50,-51,-200,-201,-20000,-20001]:\\n    for t in ['1e-5', '1e-20', '1e-100', '1e-10000']:\\n        testcases.append([\\\"fadd(%s,'%s',exact=True)\\\" % (n, t), None])\\n        testcases.append([\\\"fsub(%s,'%s',exact=True)\\\" % (n, t), None])\\n        testcases.append([\\\"fadd(%s,'%sj',exact=True)\\\" % (n, t), None])\\n        testcases.append([\\\"fsub(%s,'%sj',exact=True)\\\" % (n, t), None])\\n\\nif __name__ == \\\"__main__\\\":\\n    from timeit import default_timer as clock\\n    tot_time = 0.0\\n    for case in testcases:\\n        t1 = clock()\\n        testcase(case)\\n        t2 = clock()\\n        print(\\\"Test time:\\\", t2-t1)\\n        print()\\n        tot_time += (t2-t1)\\n    print(\\\"Total time:\\\", tot_time)\\n    print(\\\"Errors:\\\", errcount)\\n\\n\\n#from mpmath.calculus import ODE_step_euler, ODE_step_rk4, odeint, arange\\nfrom mpmath import odefun, cos, sin, mpf, sinc, mp\\n\\n'''\\nsolvers = [ODE_step_euler, ODE_step_rk4]\\n\\ndef test_ode1():\\n    \\\"\\\"\\\"\\n    Let's solve:\\n\\n    x'' + w**2 * x = 0\\n\\n    i.e. x1 = x, x2 = x1':\\n\\n    x1' =  x2\\n    x2' = -x1\\n    \\\"\\\"\\\"\\n    def derivs((x1, x2), t):\\n        return x2, -x1\\n\\n    for solver in solvers:\\n        t = arange(0, 3.1415926, 0.005)\\n        sol = odeint(derivs, (0., 1.), t, solver)\\n        x1 = [a[0] for a in sol]\\n        x2 = [a[1] for a in sol]\\n        # the result is x1 = sin(t), x2 = cos(t)\\n        # let's just check the end points for t = pi\\n        assert abs(x1[-1]) < 1e-2\\n        assert abs(x2[-1] - (-1)) < 1e-2\\n\\ndef test_ode2():\\n    \\\"\\\"\\\"\\n    Let's solve:\\n\\n    x' - x = 0\\n\\n    i.e. x = exp(x)\\n\\n    \\\"\\\"\\\"\\n    def derivs((x), t):\\n        return x\\n\\n    for solver in solvers:\\n        t = arange(0, 1, 1e-3)\\n        sol = odeint(derivs, (1.,), t, solver)\\n        x = [a[0] for a in sol]\\n        # the result is x = exp(t)\\n        # let's just check the end point for t = 1, i.e. x = e\\n        assert abs(x[-1] - 2.718281828) < 1e-2\\n'''\\n\\ndef test_odefun_rational():\\n    mp.dps = 15\\n    # A rational function\\n    f = lambda t: 1/(1+mpf(t)**2)\\n    g = odefun(lambda x, y: [-2*x*y[0]**2], 0, [f(0)])\\n    assert f(2).ae(g(2)[0])\\n\\ndef test_odefun_sinc_large():\\n    mp.dps = 15\\n    # Sinc function; test for large x\\n    f = sinc\\n    g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5)\\n    assert abs(f(100) - g(100)[0])/f(100) < 0.01\\n\\ndef test_odefun_harmonic():\\n    mp.dps = 15\\n    # Harmonic oscillator\\n    f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0])\\n    for x in [0, 1, 2.5, 8, 3.7]:    #  we go back to 3.7 to check caching\\n        c, s = f(x)\\n        assert c.ae(cos(x))\\n        assert s.ae(sin(x))\\n\\n\\nfrom mpmath import *\\nfrom random import seed, randint, random\\nimport math\\n\\n# Test compatibility with Python floats, which are\\n# IEEE doubles (53-bit)\\n\\nN = 5000\\nseed(1)\\n\\n# Choosing exponents between roughly -140, 140 ensures that\\n# the Python floats don't overflow or underflow\\nxs = [(random()-1) * 10**randint(-140, 140) for x in range(N)]\\nys = [(random()-1) * 10**randint(-140, 140) for x in range(N)]\\n\\n# include some equal values\\nys[int(N*0.8):] = xs[int(N*0.8):]\\n\\n# Detect whether Python is compiled to use 80-bit floating-point\\n# instructions, in which case the double compatibility test breaks\\nuses_x87 = -4.1974624032366689e+117 / -8.4657370748010221e-47 \\\\\\n    == 4.9581771393902231e+163\\n\\ndef test_double_compatibility():\\n    mp.prec = 53\\n    for x, y in zip(xs, ys):\\n        mpx = mpf(x)\\n        mpy = mpf(y)\\n        assert mpf(x) == x\\n        assert (mpx < mpy) == (x < y)\\n        assert (mpx > mpy) == (x > y)\\n        assert (mpx == mpy) == (x == y)\\n        assert (mpx != mpy) == (x != y)\\n        assert (mpx <= mpy) == (x <= y)\\n        assert (mpx >= mpy) == (x >= y)\\n        assert mpx == mpx\\n        if uses_x87:\\n            mp.prec = 64\\n            a = mpx + mpy\\n            b = mpx * mpy\\n            c = mpx / mpy\\n            d = mpx % mpy\\n            mp.prec = 53\\n            assert +a == x + y\\n            assert +b == x * y\\n            assert +c == x / y\\n            assert +d == x % y\\n        else:\\n            assert mpx + mpy == x + y\\n            assert mpx * mpy == x * y\\n            assert mpx / mpy == x / y\\n            assert mpx % mpy == x % y\\n        assert abs(mpx) == abs(x)\\n        assert mpf(repr(x)) == x\\n        assert ceil(mpx) == math.ceil(x)\\n        assert floor(mpx) == math.floor(x)\\n\\ndef test_sqrt():\\n    # this fails quite often. it appers to be float\\n    # that rounds the wrong way, not mpf\\n    fail = 0\\n    mp.prec = 53\\n    for x in xs:\\n        x = abs(x)\\n        mp.prec = 100\\n        mp_high = mpf(x)**0.5\\n        mp.prec = 53\\n        mp_low = mpf(x)**0.5\\n        fp = x**0.5\\n        assert abs(mp_low-mp_high) <= abs(fp-mp_high)\\n        fail += mp_low != fp\\n    assert fail < N/10\\n\\ndef test_bugs():\\n    # particular bugs\\n    assert mpf(4.4408920985006262E-16) < mpf(1.7763568394002505E-15)\\n    assert mpf(-4.4408920985006262E-16) > mpf(-1.7763568394002505E-15)\\n\\n\\nfrom mpmath import *\\n\\ndef test_interval_identity():\\n    iv.dps = 15\\n    assert mpi(2) == mpi(2, 2)\\n    assert mpi(2) != mpi(-2, 2)\\n    assert not (mpi(2) != mpi(2, 2))\\n    assert mpi(-1, 1) == mpi(-1, 1)\\n    assert str(mpi('0.1')) == \\\"[0.099999999999999991673, 0.10000000000000000555]\\\"\\n    assert repr(mpi('0.1')) == \\\"mpi('0.099999999999999992', '0.10000000000000001')\\\"\\n    u = mpi(-1, 3)\\n    assert -1 in u\\n    assert 2 in u\\n    assert 3 in u\\n    assert -1.1 not in u\\n    assert 3.1 not in u\\n    assert mpi(-1, 3) in u\\n    assert mpi(0, 1) in u\\n    assert mpi(-1.1, 2) not in u\\n    assert mpi(2.5, 3.1) not in u\\n    w = mpi(-inf, inf)\\n    assert mpi(-5, 5) in w\\n    assert mpi(2, inf) in w\\n    assert mpi(0, 2) in mpi(0, 10)\\n    assert not (3 in mpi(-inf, 0))\\n\\ndef test_interval_hash():\\n    assert hash(mpi(3)) == hash(3)\\n    assert hash(mpi(3.25)) == hash(3.25)\\n    assert hash(mpi(3,4)) == hash(mpi(3,4))\\n    assert hash(iv.mpc(3)) == hash(3)\\n    assert hash(iv.mpc(3,4)) == hash(3+4j)\\n    assert hash(iv.mpc((1,3),(2,4))) == hash(iv.mpc((1,3),(2,4)))\\n\\ndef test_interval_arithmetic():\\n    iv.dps = 15\\n    assert mpi(2) + mpi(3,4) == mpi(5,6)\\n    assert mpi(1, 2)**2 == mpi(1, 4)\\n    assert mpi(1) + mpi(0, 1e-50) == mpi(1, mpf('1.0000000000000002'))\\n    x = 1 / (1 / mpi(3))\\n    assert x.a < 3 < x.b\\n    x = mpi(2) ** mpi(0.5)\\n    iv.dps += 5\\n    sq = iv.sqrt(2)\\n    iv.dps -= 5\\n    assert x.a < sq < x.b\\n    assert mpi(1) / mpi(1, inf)\\n    assert mpi(2, 3) / inf == mpi(0, 0)\\n    assert mpi(0) / inf == 0\\n    assert mpi(0) / 0 == mpi(-inf, inf)\\n    assert mpi(inf) / 0 == mpi(-inf, inf)\\n    assert mpi(0) * inf == mpi(-inf, inf)\\n    assert 1 / mpi(2, inf) == mpi(0, 0.5)\\n    assert str((mpi(50, 50) * mpi(-10, -10)) / 3) == \\\\\\n        '[-166.66666666666668561, -166.66666666666665719]'\\n    assert mpi(0, 4) ** 3 == mpi(0, 64)\\n    assert mpi(2,4).mid == 3\\n    iv.dps = 30\\n    a = mpi(iv.pi)\\n    iv.dps = 15\\n    b = +a\\n    assert b.a < a.a\\n    assert b.b > a.b\\n    a = mpi(iv.pi)\\n    assert a == +a\\n    assert abs(mpi(-1,2)) == mpi(0,2)\\n    assert abs(mpi(0.5,2)) == mpi(0.5,2)\\n    assert abs(mpi(-3,2)) == mpi(0,3)\\n    assert abs(mpi(-3,-0.5)) == mpi(0.5,3)\\n    assert mpi(0) * mpi(2,3) == mpi(0)\\n    assert mpi(2,3) * mpi(0) == mpi(0)\\n    assert mpi(1,3).delta == 2\\n    assert mpi(1,2) - mpi(3,4) == mpi(-3,-1)\\n    assert mpi(-inf,0) - mpi(0,inf) == mpi(-inf,0)\\n    assert mpi(-inf,0) - mpi(-inf,inf) == mpi(-inf,inf)\\n    assert mpi(0,inf) - mpi(-inf,1) == mpi(-1,inf)\\n\\ndef test_interval_mul():\\n    assert mpi(-1, 0) * inf == mpi(-inf, 0)\\n    assert mpi(-1, 0) * -inf == mpi(0, inf)\\n    assert mpi(0, 1) * inf == mpi(0, inf)\\n    assert mpi(0, 1) * mpi(0, inf) == mpi(0, inf)\\n    assert mpi(-1, 1) * inf == mpi(-inf, inf)\\n    assert mpi(-1, 1) * mpi(0, inf) == mpi(-inf, inf)\\n    assert mpi(-1, 1) * mpi(-inf, inf) == mpi(-inf, inf)\\n    assert mpi(-inf, 0) * mpi(0, 1) == mpi(-inf, 0)\\n    assert mpi(-inf, 0) * mpi(0, 0) * mpi(-inf, 0)\\n    assert mpi(-inf, 0) * mpi(-inf, inf) == mpi(-inf, inf)\\n    assert mpi(-5,0)*mpi(-32,28) == mpi(-140,160)\\n    assert mpi(2,3) * mpi(-1,2) == mpi(-3,6)\\n    # Should be undefined?\\n    assert mpi(inf, inf) * 0 == mpi(-inf, inf)\\n    assert mpi(-inf, -inf) * 0 == mpi(-inf, inf)\\n    assert mpi(0) * mpi(-inf,2) == mpi(-inf,inf)\\n    assert mpi(0) * mpi(-2,inf) == mpi(-inf,inf)\\n    assert mpi(-2,inf) * mpi(0) == mpi(-inf,inf)\\n    assert mpi(-inf,2) * mpi(0) == mpi(-inf,inf)\\n\\ndef test_interval_pow():\\n    assert mpi(3)**2 == mpi(9, 9)\\n    assert mpi(-3)**2 == mpi(9, 9)\\n    assert mpi(-3, 1)**2 == mpi(0, 9)\\n    assert mpi(-3, -1)**2 == mpi(1, 9)\\n    assert mpi(-3, -1)**3 == mpi(-27, -1)\\n    assert mpi(-3, 1)**3 == mpi(-27, 1)\\n    assert mpi(-2, 3)**2 == mpi(0, 9)\\n    assert mpi(-3, 2)**2 == mpi(0, 9)\\n    assert mpi(4) ** -1 == mpi(0.25, 0.25)\\n    assert mpi(-4) ** -1 == mpi(-0.25, -0.25)\\n    assert mpi(4) ** -2 == mpi(0.0625, 0.0625)\\n    assert mpi(-4) ** -2 == mpi(0.0625, 0.0625)\\n    assert mpi(0, 1) ** inf == mpi(0, 1)\\n    assert mpi(0, 1) ** -inf == mpi(1, inf)\\n    assert mpi(0, inf) ** inf == mpi(0, inf)\\n    assert mpi(0, inf) ** -inf == mpi(0, inf)\\n    assert mpi(1, inf) ** inf == mpi(1, inf)\\n    assert mpi(1, inf) ** -inf == mpi(0, 1)\\n    assert mpi(2, 3) ** 1 == mpi(2, 3)\\n    assert mpi(2, 3) ** 0 == 1\\n    assert mpi(1,3) ** mpi(2) == mpi(1,9)\\n\\ndef test_interval_sqrt():\\n    assert mpi(4) ** 0.5 == mpi(2)\\n\\ndef test_interval_div():\\n    assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5)\\n    assert mpi(0, 1) / mpi(0, 1) == mpi(0, inf)\\n    assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf)\\n    assert mpi(inf, inf) / mpi(2, inf) == mpi(0, inf)\\n    assert mpi(inf, inf) / mpi(2, 2) == mpi(inf, inf)\\n    assert mpi(0, inf) / mpi(2, inf) == mpi(0, inf)\\n    assert mpi(0, inf) / mpi(2, 2) == mpi(0, inf)\\n    assert mpi(2, inf) / mpi(2, 2) == mpi(1, inf)\\n    assert mpi(2, inf) / mpi(2, inf) == mpi(0, inf)\\n    assert mpi(-4, 8) / mpi(1, inf) == mpi(-4, 8)\\n    assert mpi(-4, 8) / mpi(0.5, inf) == mpi(-8, 16)\\n    assert mpi(-inf, 8) / mpi(0.5, inf) == mpi(-inf, 16)\\n    assert mpi(-inf, inf) / mpi(0.5, inf) == mpi(-inf, inf)\\n    assert mpi(8, inf) / mpi(0.5, inf) == mpi(0, inf)\\n    assert mpi(-8, inf) / mpi(0.5, inf) == mpi(-16, inf)\\n    assert mpi(-4, 8) / mpi(inf, inf) == mpi(0, 0)\\n    assert mpi(0, 8) / mpi(inf, inf) == mpi(0, 0)\\n    assert mpi(0, 0) / mpi(inf, inf) == mpi(0, 0)\\n    assert mpi(-inf, 0) / mpi(inf, inf) == mpi(-inf, 0)\\n    assert mpi(-inf, 8) / mpi(inf, inf) == mpi(-inf, 0)\\n    assert mpi(-inf, inf) / mpi(inf, inf) == mpi(-inf, inf)\\n    assert mpi(-8, inf) / mpi(inf, inf) == mpi(0, inf)\\n    assert mpi(0, inf) / mpi(inf, inf) == mpi(0, inf)\\n    assert mpi(8, inf) / mpi(inf, inf) == mpi(0, inf)\\n    assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf)\\n    assert mpi(-1, 2) / mpi(0, 1) == mpi(-inf, +inf)\\n    assert mpi(0, 1) / mpi(0, 1) == mpi(0.0, +inf)\\n    assert mpi(-1, 0) / mpi(0, 1) == mpi(-inf, 0.0)\\n    assert mpi(-0.5, -0.25) / mpi(0, 1) == mpi(-inf, -0.25)\\n    assert mpi(0.5, 1) / mpi(0, 1) == mpi(0.5, +inf)\\n    assert mpi(0.5, 4) / mpi(0, 1) == mpi(0.5, +inf)\\n    assert mpi(-1, -0.5) / mpi(0, 1) == mpi(-inf, -0.5)\\n    assert mpi(-4, -0.5) / mpi(0, 1) == mpi(-inf, -0.5)\\n    assert mpi(-1, 2) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(0, 1) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(-1, 0) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(-0.5, -0.25) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(0.5, 1) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(0.5, 4) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(-1, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(-4, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf)\\n    assert mpi(-1, 2) / mpi(-1, 0) == mpi(-inf, +inf)\\n    assert mpi(0, 1) / mpi(-1, 0) == mpi(-inf, 0.0)\\n    assert mpi(-1, 0) / mpi(-1, 0) == mpi(0.0, +inf)\\n    assert mpi(-0.5, -0.25) / mpi(-1, 0) == mpi(0.25, +inf)\\n    assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5)\\n    assert mpi(0.5, 4) / mpi(-1, 0) == mpi(-inf, -0.5)\\n    assert mpi(-1, -0.5) / mpi(-1, 0) == mpi(0.5, +inf)\\n    assert mpi(-4, -0.5) / mpi(-1, 0) == mpi(0.5, +inf)\\n    assert mpi(-1, 2) / mpi(0.5, 1) == mpi(-2.0, 4.0)\\n    assert mpi(0, 1) / mpi(0.5, 1) == mpi(0.0, 2.0)\\n    assert mpi(-1, 0) / mpi(0.5, 1) == mpi(-2.0, 0.0)\\n    assert mpi(-0.5, -0.25) / mpi(0.5, 1) == mpi(-1.0, -0.25)\\n    assert mpi(0.5, 1) / mpi(0.5, 1) == mpi(0.5, 2.0)\\n    assert mpi(0.5, 4) / mpi(0.5, 1) == mpi(0.5, 8.0)\\n    assert mpi(-1, -0.5) / mpi(0.5, 1) == mpi(-2.0, -0.5)\\n    assert mpi(-4, -0.5) / mpi(0.5, 1) == mpi(-8.0, -0.5)\\n    assert mpi(-1, 2) / mpi(-2, -0.5) == mpi(-4.0, 2.0)\\n    assert mpi(0, 1) / mpi(-2, -0.5) == mpi(-2.0, 0.0)\\n    assert mpi(-1, 0) / mpi(-2, -0.5) == mpi(0.0, 2.0)\\n    assert mpi(-0.5, -0.25) / mpi(-2, -0.5) == mpi(0.125, 1.0)\\n    assert mpi(0.5, 1) / mpi(-2, -0.5) == mpi(-2.0, -0.25)\\n    assert mpi(0.5, 4) / mpi(-2, -0.5) == mpi(-8.0, -0.25)\\n    assert mpi(-1, -0.5) / mpi(-2, -0.5) == mpi(0.25, 2.0)\\n    assert mpi(-4, -0.5) / mpi(-2, -0.5) == mpi(0.25, 8.0)\\n    # Should be undefined?\\n    assert mpi(0, 0) / mpi(0, 0) == mpi(-inf, inf)\\n    assert mpi(0, 0) / mpi(0, 1) == mpi(-inf, inf)\\n\\ndef test_interval_cos_sin():\\n    iv.dps = 15\\n    cos = iv.cos\\n    sin = iv.sin\\n    tan = iv.tan\\n    pi = iv.pi\\n    # Around 0\\n    assert cos(mpi(0)) == 1\\n    assert sin(mpi(0)) == 0\\n    assert cos(mpi(0,1)) == mpi(0.54030230586813965399, 1.0)\\n    assert sin(mpi(0,1)) == mpi(0, 0.8414709848078966159)\\n    assert cos(mpi(1,2)) == mpi(-0.4161468365471424069, 0.54030230586813976501)\\n    assert sin(mpi(1,2)) == mpi(0.84147098480789650488, 1.0)\\n    assert sin(mpi(1,2.5)) == mpi(0.59847214410395643824, 1.0)\\n    assert cos(mpi(-1, 1)) == mpi(0.54030230586813965399, 1.0)\\n    assert cos(mpi(-1, 0.5)) == mpi(0.54030230586813965399, 1.0)\\n    assert cos(mpi(-1, 1.5)) == mpi(0.070737201667702906405, 1.0)\\n    assert sin(mpi(-1,1)) == mpi(-0.8414709848078966159, 0.8414709848078966159)\\n    assert sin(mpi(-1,0.5)) == mpi(-0.8414709848078966159, 0.47942553860420300538)\\n    assert mpi(-0.8414709848078966159, 1.00000000000000002e-100) in sin(mpi(-1,1e-100))\\n    assert mpi(-2.00000000000000004e-100, 1.00000000000000002e-100) in sin(mpi(-2e-100,1e-100))\\n    # Same interval\\n    assert cos(mpi(2, 2.5))\\n    assert cos(mpi(3.5, 4)) == mpi(-0.93645668729079634129, -0.65364362086361182946)\\n    assert cos(mpi(5, 5.5)) == mpi(0.28366218546322624627, 0.70866977429126010168)\\n    assert mpi(0.59847214410395654927, 0.90929742682568170942) in sin(mpi(2, 2.5))\\n    assert sin(mpi(3.5, 4)) == mpi(-0.75680249530792831347, -0.35078322768961983646)\\n    assert sin(mpi(5, 5.5)) == mpi(-0.95892427466313856499, -0.70554032557039181306)\\n    # Higher roots\\n    iv.dps = 55\\n    w = 4*10**50 + mpi(0.5)\\n    for p in [15, 40, 80]:\\n        iv.dps = p\\n        assert 0 in sin(4*mpi(pi))\\n        assert 0 in sin(4*10**50*mpi(pi))\\n        assert 0 in cos((4+0.5)*mpi(pi))\\n        assert 0 in cos(w*mpi(pi))\\n        assert 1 in cos(4*mpi(pi))\\n        assert 1 in cos(4*10**50*mpi(pi))\\n    iv.dps = 15\\n    assert cos(mpi(2,inf)) == mpi(-1,1)\\n    assert sin(mpi(2,inf)) == mpi(-1,1)\\n    assert cos(mpi(-inf,2)) == mpi(-1,1)\\n    assert sin(mpi(-inf,2)) == mpi(-1,1)\\n    u = tan(mpi(0.5,1))\\n    assert mpf(u.a).ae(mp.tan(0.5))\\n    assert mpf(u.b).ae(mp.tan(1))\\n    v = iv.cot(mpi(0.5,1))\\n    assert mpf(v.a).ae(mp.cot(1))\\n    assert mpf(v.b).ae(mp.cot(0.5))\\n    # Sanity check of evaluation at n*pi and (n+1/2)*pi\\n    for n in range(-5,7,2):\\n        x = iv.cos(n*iv.pi)\\n        assert -1 in x\\n        assert x >= -1\\n        assert x != -1\\n        x = iv.sin((n+0.5)*iv.pi)\\n        assert -1 in x\\n        assert x >= -1\\n        assert x != -1\\n    for n in range(-6,8,2):\\n        x = iv.cos(n*iv.pi)\\n        assert 1 in x\\n        assert x <= 1\\n        if n:\\n            assert x != 1\\n        x = iv.sin((n+0.5)*iv.pi)\\n        assert 1 in x\\n        assert x <= 1\\n        assert x != 1\\n    for n in range(-6,7):\\n        x = iv.cos((n+0.5)*iv.pi)\\n        assert x.a < 0 < x.b\\n        x = iv.sin(n*iv.pi)\\n        if n:\\n            assert x.a < 0 < x.b\\n\\ndef test_interval_complex():\\n    # TODO: many more tests\\n    iv.dps = 15\\n    mp.dps = 15\\n    assert iv.mpc(2,3) == 2+3j\\n    assert iv.mpc(2,3) != 2+4j\\n    assert iv.mpc(2,3) != 1+3j\\n    assert 1+3j in iv.mpc([1,2],[3,4])\\n    assert 2+5j not in iv.mpc([1,2],[3,4])\\n    assert iv.mpc(1,2) + 1j == 1+3j\\n    assert iv.mpc([1,2],[2,3]) + 2+3j == iv.mpc([3,4],[5,6])\\n    assert iv.mpc([2,4],[4,8]) / 2 == iv.mpc([1,2],[2,4])\\n    assert iv.mpc([1,2],[2,4]) * 2j == iv.mpc([-8,-4],[2,4])\\n    assert iv.mpc([2,4],[4,8]) / 2j == iv.mpc([2,4],[-2,-1])\\n    assert iv.exp(2+3j).ae(mp.exp(2+3j))\\n    assert iv.log(2+3j).ae(mp.log(2+3j))\\n    assert (iv.mpc(2,3) ** iv.mpc(0.5,2)).ae(mp.mpc(2,3) ** mp.mpc(0.5,2))\\n    assert 1j in (iv.mpf(-1) ** 0.5)\\n    assert 1j in (iv.mpc(-1) ** 0.5)\\n    assert abs(iv.mpc(0)) == 0\\n    assert abs(iv.mpc(inf)) == inf\\n    assert abs(iv.mpc(3,4)) == 5\\n    assert abs(iv.mpc(4)) == 4\\n    assert abs(iv.mpc(0,4)) == 4\\n    assert abs(iv.mpc(0,[2,3])) == iv.mpf([2,3])\\n    assert abs(iv.mpc(0,[-3,2])) == iv.mpf([0,3])\\n    assert abs(iv.mpc([3,5],[4,12])) == iv.mpf([5,13])\\n    assert abs(iv.mpc([3,5],[-4,12])) == iv.mpf([3,13])\\n    assert iv.mpc(2,3) ** 0 == 1\\n    assert iv.mpc(2,3) ** 1 == (2+3j)\\n    assert iv.mpc(2,3) ** 2 == (2+3j)**2\\n    assert iv.mpc(2,3) ** 3 == (2+3j)**3\\n    assert iv.mpc(2,3) ** 4 == (2+3j)**4\\n    assert iv.mpc(2,3) ** 5 == (2+3j)**5\\n    assert iv.mpc(2,2) ** (-1) == (2+2j) ** (-1)\\n    assert iv.mpc(2,2) ** (-2) == (2+2j) ** (-2)\\n    assert iv.cos(2).ae(mp.cos(2))\\n    assert iv.sin(2).ae(mp.sin(2))\\n    assert iv.cos(2+3j).ae(mp.cos(2+3j))\\n    assert iv.sin(2+3j).ae(mp.sin(2+3j))\\n\\ndef test_interval_complex_arg():\\n    mp.dps = 15\\n    iv.dps = 15\\n    assert iv.arg(3) == 0\\n    assert iv.arg(0) == 0\\n    assert iv.arg([0,3]) == 0\\n    assert iv.arg(-3).ae(pi)\\n    assert iv.arg(2+3j).ae(iv.arg(2+3j))\\n    z = iv.mpc([-2,-1],[3,4])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(-1+4j))\\n    assert t.b.ae(mp.arg(-2+3j))\\n    z = iv.mpc([-2,1],[3,4])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(1+3j))\\n    assert t.b.ae(mp.arg(-2+3j))\\n    z = iv.mpc([1,2],[3,4])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(2+3j))\\n    assert t.b.ae(mp.arg(1+4j))\\n    z = iv.mpc([1,2],[-2,3])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(1-2j))\\n    assert t.b.ae(mp.arg(1+3j))\\n    z = iv.mpc([1,2],[-4,-3])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(1-4j))\\n    assert t.b.ae(mp.arg(2-3j))\\n    z = iv.mpc([-1,2],[-4,-3])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(-1-3j))\\n    assert t.b.ae(mp.arg(2-3j))\\n    z = iv.mpc([-2,-1],[-4,-3])\\n    t = iv.arg(z)\\n    assert t.a.ae(mp.arg(-2-3j))\\n    assert t.b.ae(mp.arg(-1-4j))\\n    z = iv.mpc([-2,-1],[-3,3])\\n    t = iv.arg(z)\\n    assert t.a.ae(-mp.pi)\\n    assert t.b.ae(mp.pi)\\n    z = iv.mpc([-2,2],[-3,3])\\n    t = iv.arg(z)\\n    assert t.a.ae(-mp.pi)\\n    assert t.b.ae(mp.pi)\\n\\ndef test_interval_ae():\\n    iv.dps = 15\\n    x = iv.mpf([1,2])\\n    assert x.ae(1) is None\\n    assert x.ae(1.5) is None\\n    assert x.ae(2) is None\\n    assert x.ae(2.01) is False\\n    assert x.ae(0.99) is False\\n    x = iv.mpf(3.5)\\n    assert x.ae(3.5) is True\\n    assert x.ae(3.5+1e-15) is True\\n    assert x.ae(3.5-1e-15) is True\\n    assert x.ae(3.501) is False\\n    assert x.ae(3.499) is False\\n    assert x.ae(iv.mpf([3.5,3.501])) is None\\n    assert x.ae(iv.mpf([3.5,4.5+1e-15])) is None\\n\\ndef test_interval_nstr():\\n    iv.dps = n = 30\\n    x = mpi(1, 2)\\n    # FIXME: error_dps should not be necessary\\n    assert iv.nstr(x, n, mode='plusminus', error_dps=6) == '1.5 +- 0.5'\\n    assert iv.nstr(x, n, mode='plusminus', use_spaces=False, error_dps=6) == '1.5+-0.5'\\n    assert iv.nstr(x, n, mode='percent') == '1.5 (33.33%)'\\n    assert iv.nstr(x, n, mode='brackets', use_spaces=False) == '[1.0,2.0]'\\n    assert iv.nstr(x, n, mode='brackets' , brackets=('<', '>')) == '<1.0, 2.0>'\\n    x = mpi('5.2582327113062393041', '5.2582327113062749951')\\n    assert iv.nstr(x, n, mode='diff') == '5.2582327113062[393041, 749951]'\\n    assert iv.nstr(iv.cos(mpi(1)), n, mode='diff', use_spaces=False) == '0.54030230586813971740093660744[2955,3053]'\\n    assert iv.nstr(mpi('1e123', '1e129'), n, mode='diff') == '[1.0e+123, 1.0e+129]'\\n    exp = iv.exp\\n    assert iv.nstr(iv.exp(mpi('5000.1')), n, mode='diff') == '3.2797365856787867069110487[0926, 1191]e+2171'\\n    iv.dps = 15\\n\\ndef test_mpi_from_str():\\n    iv.dps = 15\\n    assert iv.convert('1.5 +- 0.5') == mpi(mpf('1.0'), mpf('2.0'))\\n    assert mpi(1, 2) in iv.convert('1.5 (33.33333333333333333333333333333%)')\\n    assert iv.convert('[1, 2]') == mpi(1, 2)\\n    assert iv.convert('1[2, 3]') == mpi(12, 13)\\n    assert iv.convert('1.[23,46]e-8') == mpi('1.23e-8', '1.46e-8')\\n    assert iv.convert('12[3.4,5.9]e4') == mpi('123.4e+4', '125.9e4')\\n\\ndef test_interval_gamma():\\n    mp.dps = 15\\n    iv.dps = 15\\n    # TODO: need many more tests\\n    assert iv.rgamma(0) == 0\\n    assert iv.fac(0) == 1\\n    assert iv.fac(1) == 1\\n    assert iv.fac(2) == 2\\n    assert iv.fac(3) == 6\\n    assert iv.gamma(0) == [-inf,inf]\\n    assert iv.gamma(1) == 1\\n    assert iv.gamma(2) == 1\\n    assert iv.gamma(3) == 2\\n    assert -3.5449077018110320546 in iv.gamma(-0.5)\\n    assert iv.loggamma(1) == 0\\n    assert iv.loggamma(2) == 0\\n    assert 0.69314718055994530942 in iv.loggamma(3)\\n    # Test tight log-gamma endpoints based on monotonicity\\n    xs = [iv.mpc([2,3],[1,4]),\\n          iv.mpc([2,3],[-4,-1]),\\n          iv.mpc([2,3],[-1,4]),\\n          iv.mpc([2,3],[-4,1]),\\n          iv.mpc([2,3],[-4,4]),\\n          iv.mpc([-3,-2],[2,4]),\\n          iv.mpc([-3,-2],[-4,-2])]\\n    for x in xs:\\n        ys = [mp.loggamma(mp.mpc(x.a,x.c)),\\n              mp.loggamma(mp.mpc(x.b,x.c)),\\n              mp.loggamma(mp.mpc(x.a,x.d)),\\n              mp.loggamma(mp.mpc(x.b,x.d))]\\n        if 0 in x.imag:\\n            ys += [mp.loggamma(x.a), mp.loggamma(x.b)]\\n        min_real = min([y.real for y in ys])\\n        max_real = max([y.real for y in ys])\\n        min_imag = min([y.imag for y in ys])\\n        max_imag = max([y.imag for y in ys])\\n        z = iv.loggamma(x)\\n        assert z.a.ae(min_real)\\n        assert z.b.ae(max_real)\\n        assert z.c.ae(min_imag)\\n        assert z.d.ae(max_imag)\\n\\ndef test_interval_conversions():\\n    mp.dps = 15\\n    iv.dps = 15\\n    for a, b in ((-0.0, 0), (0.0, 0.5), (1.0, 1), \\\\\\n                 ('-inf', 20.5), ('-inf', float(sqrt(2)))):\\n        r = mpi(a, b)\\n        assert int(r.b) == int(b)\\n        assert float(r.a) == float(a)\\n        assert float(r.b) == float(b)\\n        assert complex(r.a) == complex(a)\\n        assert complex(r.b) == complex(b)\\n\\n\\n\\\"\\\"\\\"\\nEasy-to-use test-generating code:\\n\\ncases = '''\\nexp 2.25\\nlog 2.25\\n'''\\n\\nfrom mpmath import *\\nmp.dps = 20\\nfor test in cases.splitlines():\\n    if not test:\\n        continue\\n    words = test.split()\\n    fname = words[0]\\n    args = words[1:]\\n    argstr = \\\", \\\".join(args)\\n    testline = \\\"%s(%s)\\\" % (fname, argstr)\\n    ans = str(eval(testline))\\n    print \\\"    assert ae(fp.%s, %s)\\\" % (testline, ans)\\n\\n\\\"\\\"\\\"\\n\\nfrom mpmath import fp\\n\\ndef ae(x, y, tol=1e-12):\\n    if x == y:\\n        return True\\n    return abs(x-y) <= tol*abs(y)\\n\\ndef test_conj():\\n    assert fp.conj(4) == 4\\n    assert fp.conj(3+4j) == 3-4j\\n    assert fp.fdot([1,2],[3,2+1j], conjugate=True) == 7-2j\\n\\ndef test_fp_number_parts():\\n    assert ae(fp.arg(3), 0.0)\\n    assert ae(fp.arg(-3), 3.1415926535897932385)\\n    assert ae(fp.arg(3j), 1.5707963267948966192)\\n    assert ae(fp.arg(-3j), -1.5707963267948966192)\\n    assert ae(fp.arg(2+3j), 0.98279372324732906799)\\n    assert ae(fp.arg(-1-1j), -2.3561944901923449288)\\n    assert ae(fp.re(2.5), 2.5)\\n    assert ae(fp.re(2.5+3j), 2.5)\\n    assert ae(fp.im(2.5), 0.0)\\n    assert ae(fp.im(2.5+3j), 3.0)\\n    assert ae(fp.floor(2.5), 2.0)\\n    assert ae(fp.floor(2), 2.0)\\n    assert ae(fp.floor(2.0+0j), (2.0 + 0.0j))\\n    assert ae(fp.floor(-1.5-0.5j), (-2.0 - 1.0j))\\n    assert ae(fp.ceil(2.5), 3.0)\\n    assert ae(fp.ceil(2), 2.0)\\n    assert ae(fp.ceil(2.0+0j), (2.0 + 0.0j))\\n    assert ae(fp.ceil(-1.5-0.5j), (-1.0 + 0.0j))\\n\\ndef test_fp_cospi_sinpi():\\n    assert ae(fp.sinpi(0), 0.0)\\n    assert ae(fp.sinpi(0.25), 0.7071067811865475244)\\n    assert ae(fp.sinpi(0.5), 1.0)\\n    assert ae(fp.sinpi(0.75), 0.7071067811865475244)\\n    assert ae(fp.sinpi(1), 0.0)\\n    assert ae(fp.sinpi(1.25), -0.7071067811865475244)\\n    assert ae(fp.sinpi(1.5), -1.0)\\n    assert ae(fp.sinpi(1.75), -0.7071067811865475244)\\n    assert ae(fp.sinpi(2), 0.0)\\n    assert ae(fp.sinpi(2.25), 0.7071067811865475244)\\n    assert ae(fp.sinpi(0+3j), (0.0 + 6195.8238636085899556j))\\n    assert ae(fp.sinpi(0.25+3j), (4381.1091260582448033 + 4381.1090689950686908j))\\n    assert ae(fp.sinpi(0.5+3j), (6195.8239443081075259 + 0.0j))\\n    assert ae(fp.sinpi(0.75+3j), (4381.1091260582448033 - 4381.1090689950686908j))\\n    assert ae(fp.sinpi(1+3j), (0.0 - 6195.8238636085899556j))\\n    assert ae(fp.sinpi(1.25+3j), (-4381.1091260582448033 - 4381.1090689950686908j))\\n    assert ae(fp.sinpi(1.5+3j), (-6195.8239443081075259 + 0.0j))\\n    assert ae(fp.sinpi(1.75+3j), (-4381.1091260582448033 + 4381.1090689950686908j))\\n    assert ae(fp.sinpi(2+3j), (0.0 + 6195.8238636085899556j))\\n    assert ae(fp.sinpi(2.25+3j), (4381.1091260582448033 + 4381.1090689950686908j))\\n    assert ae(fp.sinpi(-0.75), -0.7071067811865475244)\\n    assert ae(fp.sinpi(-1e-10), -3.1415926535897933529e-10)\\n    assert ae(fp.sinpi(1e-10), 3.1415926535897933529e-10)\\n    assert ae(fp.sinpi(1e-10+1e-10j), (3.141592653589793353e-10 + 3.1415926535897933528e-10j))\\n    assert ae(fp.sinpi(1e-10-1e-10j), (3.141592653589793353e-10 - 3.1415926535897933528e-10j))\\n    assert ae(fp.sinpi(-1e-10+1e-10j), (-3.141592653589793353e-10 + 3.1415926535897933528e-10j))\\n    assert ae(fp.sinpi(-1e-10-1e-10j), (-3.141592653589793353e-10 - 3.1415926535897933528e-10j))\\n    assert ae(fp.cospi(0), 1.0)\\n    assert ae(fp.cospi(0.25), 0.7071067811865475244)\\n    assert ae(fp.cospi(0.5), 0.0)\\n    assert ae(fp.cospi(0.75), -0.7071067811865475244)\\n    assert ae(fp.cospi(1), -1.0)\\n    assert ae(fp.cospi(1.25), -0.7071067811865475244)\\n    assert ae(fp.cospi(1.5), 0.0)\\n    assert ae(fp.cospi(1.75), 0.7071067811865475244)\\n    assert ae(fp.cospi(2), 1.0)\\n    assert ae(fp.cospi(2.25), 0.7071067811865475244)\\n    assert ae(fp.cospi(0+3j), (6195.8239443081075259 + 0.0j))\\n    assert ae(fp.cospi(0.25+3j), (4381.1091260582448033 - 4381.1090689950686908j))\\n    assert ae(fp.cospi(0.5+3j), (0.0 - 6195.8238636085899556j))\\n    assert ae(fp.cospi(0.75+3j), (-4381.1091260582448033 - 4381.1090689950686908j))\\n    assert ae(fp.cospi(1+3j), (-6195.8239443081075259 + 0.0j))\\n    assert ae(fp.cospi(1.25+3j), (-4381.1091260582448033 + 4381.1090689950686908j))\\n    assert ae(fp.cospi(1.5+3j), (0.0 + 6195.8238636085899556j))\\n    assert ae(fp.cospi(1.75+3j), (4381.1091260582448033 + 4381.1090689950686908j))\\n    assert ae(fp.cospi(2+3j), (6195.8239443081075259 + 0.0j))\\n    assert ae(fp.cospi(2.25+3j), (4381.1091260582448033 - 4381.1090689950686908j))\\n    assert ae(fp.cospi(-0.75), -0.7071067811865475244)\\n    assert ae(fp.sinpi(-0.7), -0.80901699437494750611)\\n    assert ae(fp.cospi(-0.7), -0.5877852522924730163)\\n    assert ae(fp.cospi(-3+2j), (-267.74676148374822225 + 0.0j))\\n    assert ae(fp.sinpi(-3+2j), (0.0 - 267.74489404101651426j))\\n    assert ae(fp.sinpi(-0.7+2j), (-216.6116802292079471 - 157.37650009392034693j))\\n    assert ae(fp.cospi(-0.7+2j), (-157.37759774921754565 + 216.61016943630197336j))\\n\\ndef test_fp_expj():\\n    assert ae(fp.expj(0), (1.0 + 0.0j))\\n    assert ae(fp.expj(1), (0.5403023058681397174 + 0.84147098480789650665j))\\n    assert ae(fp.expj(2), (-0.416146836547142387 + 0.9092974268256816954j))\\n    assert ae(fp.expj(0.75), (0.73168886887382088631 + 0.68163876002333416673j))\\n    assert ae(fp.expj(2+3j), (-0.020718731002242879378 + 0.045271253156092975488j))\\n    assert ae(fp.expjpi(0), (1.0 + 0.0j))\\n    assert ae(fp.expjpi(1), (-1.0 + 0.0j))\\n    assert ae(fp.expjpi(2), (1.0 + 0.0j))\\n    assert ae(fp.expjpi(0.75), (-0.7071067811865475244 + 0.7071067811865475244j))\\n    assert ae(fp.expjpi(2+3j), (0.000080699517570304599239 + 0.0j))\\n\\ndef test_fp_bernoulli():\\n    assert ae(fp.bernoulli(0), 1.0)\\n    assert ae(fp.bernoulli(1), -0.5)\\n    assert ae(fp.bernoulli(2), 0.16666666666666666667)\\n    assert ae(fp.bernoulli(10), 0.075757575757575757576)\\n    assert ae(fp.bernoulli(11), 0.0)\\n\\ndef test_fp_gamma():\\n    assert ae(fp.gamma(1), 1.0)\\n    assert ae(fp.gamma(1.5), 0.88622692545275801365)\\n    assert ae(fp.gamma(10), 362880.0)\\n    assert ae(fp.gamma(-0.5), -3.5449077018110320546)\\n    assert ae(fp.gamma(-7.1), 0.0016478244570263333622)\\n    assert ae(fp.gamma(12.3), 83385367.899970000963)\\n    assert ae(fp.gamma(2+0j), (1.0 + 0.0j))\\n    assert ae(fp.gamma(-2.5+0j), (-0.94530872048294188123 + 0.0j))\\n    assert ae(fp.gamma(3+4j), (0.0052255384713692141947 - 0.17254707929430018772j))\\n    assert ae(fp.gamma(-3-4j), (0.00001460997305874775607 - 0.000020760733311509070396j))\\n    assert ae(fp.fac(0), 1.0)\\n    assert ae(fp.fac(1), 1.0)\\n    assert ae(fp.fac(20), 2432902008176640000.0)\\n    assert ae(fp.fac(-3.5), -0.94530872048294188123)\\n    assert ae(fp.fac(2+3j), (-0.44011340763700171113 - 0.06363724312631702183j))\\n    assert ae(fp.loggamma(1.0), 0.0)\\n    assert ae(fp.loggamma(2.0), 0.0)\\n    assert ae(fp.loggamma(3.0), 0.69314718055994530942)\\n    assert ae(fp.loggamma(7.25), 7.0521854507385394449)\\n    assert ae(fp.loggamma(1000.0), 5905.2204232091812118)\\n    assert ae(fp.loggamma(1e50), 1.1412925464970229298e+52)\\n    assert ae(fp.loggamma(1e25+1e25j), (5.6125802751733671621e+26 + 5.7696599078528568383e+26j))\\n    assert ae(fp.loggamma(3+4j), (-1.7566267846037841105 + 4.7426644380346579282j))\\n    assert ae(fp.loggamma(-0.5), (1.2655121234846453965 - 3.1415926535897932385j))\\n    assert ae(fp.loggamma(-1.25), (1.3664317612369762346 - 6.2831853071795864769j))\\n    assert ae(fp.loggamma(-2.75), (0.0044878975359557733115 - 9.4247779607693797154j))\\n    assert ae(fp.loggamma(-3.5), (-1.3090066849930420464 - 12.566370614359172954j))\\n    assert ae(fp.loggamma(-4.5), (-2.8130840817693161197 - 15.707963267948966192j))\\n    assert ae(fp.loggamma(-2+3j), (-6.776523813485657093 - 4.568791367260286402j))\\n    assert ae(fp.loggamma(-1000.3), (-5912.8440347785205041 - 3144.7342462433830317j))\\n    assert ae(fp.loggamma(-100-100j), (-632.35117666833135562 - 158.37641469650352462j))\\n    assert ae(fp.loggamma(1e-10), 23.025850929882735237)\\n    assert ae(fp.loggamma(-1e-10), (23.02585092999817837 - 3.1415926535897932385j))\\n    assert ae(fp.loggamma(1e-10j), (23.025850929940456804 - 1.5707963268526181857j))\\n    assert ae(fp.loggamma(1e-10j-1e-10), (22.679277339718205716 - 2.3561944902500664954j))\\n\\ndef test_fp_psi():\\n    assert ae(fp.psi(0, 3.7), 1.1671535393615114409)\\n    assert ae(fp.psi(0, 0.5), -1.9635100260214234794)\\n    assert ae(fp.psi(0, 1), -0.57721566490153286061)\\n    assert ae(fp.psi(0, -2.5), 1.1031566406452431872)\\n    assert ae(fp.psi(0, 12.9), 2.5179671503279156347)\\n    assert ae(fp.psi(0, 100), 4.6001618527380874002)\\n    assert ae(fp.psi(0, 2500.3), 7.8239660143238547877)\\n    assert ae(fp.psi(0, 1e40), 92.103403719761827391)\\n    assert ae(fp.psi(0, 1e200), 460.51701859880913677)\\n    assert ae(fp.psi(0, 3.7+0j), (1.1671535393615114409 + 0.0j))\\n    assert ae(fp.psi(1, 3), 0.39493406684822643647)\\n    assert ae(fp.psi(3, 2+3j), (-0.05383196209159972116 + 0.0076890935247364805218j))\\n    assert ae(fp.psi(4, -0.5+1j), (1.2719531355492328195 - 18.211833410936276774j))\\n    assert ae(fp.harmonic(0), 0.0)\\n    assert ae(fp.harmonic(1), 1.0)\\n    assert ae(fp.harmonic(2), 1.5)\\n    assert ae(fp.harmonic(100), 5.1873775176396202608)\\n    assert ae(fp.harmonic(-2.5), 1.2803723055467760478)\\n    assert ae(fp.harmonic(2+3j), (1.9390425294578375875 + 0.87336044981834544043j))\\n    assert ae(fp.harmonic(-5-4j), (2.3725754822349437733 - 2.4160904444801621j))\\n\\ndef test_fp_zeta():\\n    assert ae(fp.zeta(1e100), 1.0)\\n    assert ae(fp.zeta(3), 1.2020569031595942854)\\n    assert ae(fp.zeta(2+0j), (1.6449340668482264365 + 0.0j))\\n    assert ae(fp.zeta(0.93), -13.713619351638164784)\\n    assert ae(fp.zeta(1.74), 1.9796863545771774095)\\n    assert ae(fp.zeta(0.0), -0.5)\\n    assert ae(fp.zeta(-1.0), -0.083333333333333333333)\\n    assert ae(fp.zeta(-2.0), 0.0)\\n    assert ae(fp.zeta(-3.0), 0.0083333333333333333333)\\n    assert ae(fp.zeta(-500.0), 0.0)\\n    assert ae(fp.zeta(-7.4), 0.0036537321227995882447)\\n    assert ae(fp.zeta(2.1), 1.5602165335033620158)\\n    assert ae(fp.zeta(26.9), 1.0000000079854809935)\\n    assert ae(fp.zeta(26), 1.0000000149015548284)\\n    assert ae(fp.zeta(27), 1.0000000074507117898)\\n    assert ae(fp.zeta(28), 1.0000000037253340248)\\n    assert ae(fp.zeta(27.1), 1.000000006951755045)\\n    assert ae(fp.zeta(32.7), 1.0000000001433243232)\\n    assert ae(fp.zeta(100), 1.0)\\n    assert ae(fp.altzeta(3.5), 0.92755357777394803511)\\n    assert ae(fp.altzeta(1), 0.69314718055994530942)\\n    assert ae(fp.altzeta(2), 0.82246703342411321824)\\n    assert ae(fp.altzeta(0), 0.5)\\n    assert ae(fp.zeta(-2+3j, 1), (0.13297115587929864827 + 0.12305330040458776494j))\\n    assert ae(fp.zeta(-2+3j, 5), (18.384866151867576927 - 11.377015110597711009j))\\n    assert ae(fp.zeta(1.0000000001), 9999999173.1735741337)\\n    assert ae(fp.zeta(0.9999999999), -9999999172.0191428039)\\n    assert ae(fp.zeta(1+0.000000001j), (0.57721566490153286061 - 999999999.99999993765j))\\n    assert ae(fp.primezeta(2.5+4j), (-0.16922458243438033385 - 0.010847965298387727811j))\\n    assert ae(fp.primezeta(4), 0.076993139764246844943)\\n    assert ae(fp.riemannr(3.7), 2.3034079839110855717)\\n    assert ae(fp.riemannr(8), 3.9011860449341499474)\\n    assert ae(fp.riemannr(3+4j), (2.2369653314259991796 + 1.6339943856990281694j))\\n\\ndef test_fp_hyp2f1():\\n    assert ae(fp.hyp2f1(1, (3,2), 3.25, 5.0), (-0.46600275923108143059 - 0.74393667908854842325j))\\n    assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 5.0), (-5.9208875603806515987 - 2.3813557707889590686j))\\n    assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 2+3j), (0.17174552030925080445 + 0.19589781970539389999j))\\n\\ndef test_fp_erf():\\n    assert fp.erf(2) == fp.erf(2.0) == fp.erf(2.0+0.0j)\\n    assert fp.erf(fp.inf) == 1.0\\n    assert fp.erf(fp.ninf) == -1.0\\n    assert ae(fp.erf(0), 0.0)\\n    assert ae(fp.erf(-0), -0.0)\\n    assert ae(fp.erf(0.3), 0.32862675945912741619)\\n    assert ae(fp.erf(-0.3), -0.32862675945912741619)\\n    assert ae(fp.erf(0.9), 0.79690821242283213966)\\n    assert ae(fp.erf(-0.9), -0.79690821242283213966)\\n    assert ae(fp.erf(1.0), 0.84270079294971486934)\\n    assert ae(fp.erf(-1.0), -0.84270079294971486934)\\n    assert ae(fp.erf(1.1), 0.88020506957408172966)\\n    assert ae(fp.erf(-1.1), -0.88020506957408172966)\\n    assert ae(fp.erf(8.5), 1.0)\\n    assert ae(fp.erf(-8.5), -1.0)\\n    assert ae(fp.erf(9.1), 1.0)\\n    assert ae(fp.erf(-9.1), -1.0)\\n    assert ae(fp.erf(20.0), 1.0)\\n    assert ae(fp.erf(-20.0), -1.0)\\n    assert ae(fp.erf(10000.0), 1.0)\\n    assert ae(fp.erf(-10000.0), -1.0)\\n    assert ae(fp.erf(1e+50), 1.0)\\n    assert ae(fp.erf(-1e+50), -1.0)\\n    assert ae(fp.erf(1j), 1.650425758797542876j)\\n    assert ae(fp.erf(-1j), -1.650425758797542876j)\\n    assert ae(fp.erf((2+3j)), (-20.829461427614568389 + 8.6873182714701631444j))\\n    assert ae(fp.erf(-(2+3j)), -(-20.829461427614568389 + 8.6873182714701631444j))\\n    assert ae(fp.erf((8+9j)), (-1072004.2525062051158 + 364149.91954310255423j))\\n    assert ae(fp.erf(-(8+9j)), -(-1072004.2525062051158 + 364149.91954310255423j))\\n    assert fp.erfc(fp.inf) == 0.0\\n    assert fp.erfc(fp.ninf) == 2.0\\n    assert fp.erfc(0) == 1\\n    assert fp.erfc(-0.0) == 1\\n    assert fp.erfc(0+0j) == 1\\n    assert ae(fp.erfc(0.3), 0.67137324054087258381)\\n    assert ae(fp.erfc(-0.3), 1.3286267594591274162)\\n    assert ae(fp.erfc(0.9), 0.20309178757716786034)\\n    assert ae(fp.erfc(-0.9), 1.7969082124228321397)\\n    assert ae(fp.erfc(1.0), 0.15729920705028513066)\\n    assert ae(fp.erfc(-1.0), 1.8427007929497148693)\\n    assert ae(fp.erfc(1.1), 0.11979493042591827034)\\n    assert ae(fp.erfc(-1.1), 1.8802050695740817297)\\n    assert ae(fp.erfc(8.5), 2.7623240713337714461e-33)\\n    assert ae(fp.erfc(-8.5), 2.0)\\n    assert ae(fp.erfc(9.1), 6.6969004279886077452e-38)\\n    assert ae(fp.erfc(-9.1), 2.0)\\n    assert ae(fp.erfc(20.0), 5.3958656116079009289e-176)\\n    assert ae(fp.erfc(-20.0), 2.0)\\n    assert ae(fp.erfc(10000.0), 0.0)\\n    assert ae(fp.erfc(-10000.0), 2.0)\\n    assert ae(fp.erfc(1e+50), 0.0)\\n    assert ae(fp.erfc(-1e+50), 2.0)\\n    assert ae(fp.erfc(1j), (1.0 - 1.650425758797542876j))\\n    assert ae(fp.erfc(-1j), (1.0 + 1.650425758797542876j))\\n    assert ae(fp.erfc((2+3j)), (21.829461427614568389 - 8.6873182714701631444j), 1e-13)\\n    assert ae(fp.erfc(-(2+3j)), (-19.829461427614568389 + 8.6873182714701631444j), 1e-13)\\n    assert ae(fp.erfc((8+9j)), (1072005.2525062051158 - 364149.91954310255423j))\\n    assert ae(fp.erfc(-(8+9j)), (-1072003.2525062051158 + 364149.91954310255423j))\\n    assert ae(fp.erfc(20+0j), (5.3958656116079009289e-176 + 0.0j))\\n\\ndef test_fp_lambertw():\\n    assert ae(fp.lambertw(0.0), 0.0)\\n    assert ae(fp.lambertw(1.0), 0.567143290409783873)\\n    assert ae(fp.lambertw(7.5), 1.5662309537823875394)\\n    assert ae(fp.lambertw(-0.25), -0.35740295618138890307)\\n    assert ae(fp.lambertw(-10.0), (1.3699809685212708156 + 2.140194527074713196j))\\n    assert ae(fp.lambertw(0+0j), (0.0 + 0.0j))\\n    assert ae(fp.lambertw(4+0j), (1.2021678731970429392 + 0.0j))\\n    assert ae(fp.lambertw(1000.5), 5.2500227450408980127)\\n    assert ae(fp.lambertw(1e100), 224.84310644511850156)\\n    assert ae(fp.lambertw(-1000.0), (5.1501630246362515223 + 2.6641981432905204596j))\\n    assert ae(fp.lambertw(1e-10), 9.9999999990000003645e-11)\\n    assert ae(fp.lambertw(1e-10j), (1.0000000000000000728e-20 + 1.0000000000000000364e-10j))\\n    assert ae(fp.lambertw(3+4j), (1.2815618061237758782 + 0.53309522202097107131j))\\n    assert ae(fp.lambertw(-3-4j), (1.0750730665692549276 - 1.3251023817343588823j))\\n    assert ae(fp.lambertw(10000+1000j), (7.2361526563371602186 + 0.087567810943839352034j))\\n    assert ae(fp.lambertw(0.0, -1), -fp.inf)\\n    assert ae(fp.lambertw(1.0, -1), (-1.5339133197935745079 - 4.3751851530618983855j))\\n    assert ae(fp.lambertw(7.5, -1), (0.44125668415098614999 - 4.8039842008452390179j))\\n    assert ae(fp.lambertw(-0.25, -1), -2.1532923641103496492)\\n    assert ae(fp.lambertw(-10.0, -1), (1.3699809685212708156 - 2.140194527074713196j))\\n    assert ae(fp.lambertw(0+0j, -1), -fp.inf)\\n    assert ae(fp.lambertw(4+0j, -1), (-0.15730793189620765317 - 4.6787800704666656212j))\\n    assert ae(fp.lambertw(1000.5, -1), (4.9153765415404024736 - 5.4465682700815159569j))\\n    assert ae(fp.lambertw(1e100, -1), (224.84272130101601052 - 6.2553713838167244141j))\\n    assert ae(fp.lambertw(-1000.0, -1), (5.1501630246362515223 - 2.6641981432905204596j))\\n    assert ae(fp.lambertw(1e-10, -1), (-26.303186778379041521 - 3.2650939117038283975j))\\n    assert ae(fp.lambertw(1e-10j, -1), (-26.297238779529035028 - 1.6328071613455765135j))\\n    assert ae(fp.lambertw(3+4j, -1), (0.25856740686699741676 - 3.8521166861614355895j))\\n    assert ae(fp.lambertw(-3-4j, -1), (-0.32028750204310768396 - 6.8801677192091972343j))\\n    assert ae(fp.lambertw(10000+1000j, -1), (7.0255308742285435567 - 5.5177506835734067601j))\\n    assert ae(fp.lambertw(0.0, 2), -fp.inf)\\n    assert ae(fp.lambertw(1.0, 2), (-2.4015851048680028842 + 10.776299516115070898j))\\n    assert ae(fp.lambertw(7.5, 2), (-0.38003357962843791529 + 10.960916473368746184j))\\n    assert ae(fp.lambertw(-0.25, 2), (-4.0558735269061511898 + 13.852334658567271386j))\\n    assert ae(fp.lambertw(-10.0, 2), (-0.34479123764318858696 + 14.112740596763592363j))\\n    assert ae(fp.lambertw(0+0j, 2), -fp.inf)\\n    assert ae(fp.lambertw(4+0j, 2), (-1.0070343323804262788 + 10.903476551861683082j))\\n    assert ae(fp.lambertw(1000.5, 2), (4.4076185165459395295 + 11.365524591091402177j))\\n    assert ae(fp.lambertw(1e100, 2), (224.84156762724875878 + 12.510785262632255672j))\\n    assert ae(fp.lambertw(-1000.0, 2), (4.1984245610246530756 + 14.420478573754313845j))\\n    assert ae(fp.lambertw(1e-10, 2), (-26.362258095445866488 + 9.7800247407031482519j))\\n    assert ae(fp.lambertw(1e-10j, 2), (-26.384250801683084252 + 11.403535950607739763j))\\n    assert ae(fp.lambertw(3+4j, 2), (-0.86554679943333993562 + 11.849956798331992027j))\\n    assert ae(fp.lambertw(-3-4j, 2), (-0.55792273874679112639 + 8.7173627024159324811j))\\n    assert ae(fp.lambertw(10000+1000j, 2), (6.6223802254585662734 + 11.61348646825020766j))\\n\\ndef test_fp_stress_ei_e1():\\n    # Can be tightened on recent Pythons with more accurate math/cmath\\n    ATOL = 1e-13\\n    PTOL = 1e-12\\n    v = fp.e1(1.1641532182693481445e-10)\\n    assert ae(v, 22.296641293693077672, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(0.25)\\n    assert ae(v, 1.0442826344437381945, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(1.0)\\n    assert ae(v, 0.21938393439552027368, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(2.0)\\n    assert ae(v, 0.048900510708061119567, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(5.0)\\n    assert ae(v, 0.0011482955912753257973, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(20.0)\\n    assert ae(v, 9.8355252906498816904e-11, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(30.0)\\n    assert ae(v, 3.0215520106888125448e-15, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(40.0)\\n    assert ae(v, 1.0367732614516569722e-19, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(50.0)\\n    assert ae(v, 3.7832640295504590187e-24, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1(80.0)\\n    assert ae(v, 2.2285432586884729112e-37, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.e1((1.1641532182693481445e-10 + 0.0j))\\n    assert ae(v, (22.296641293693077672 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 22.296641293693077672, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((0.25 + 0.0j))\\n    assert ae(v, (1.0442826344437381945 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 1.0442826344437381945, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((1.0 + 0.0j))\\n    assert ae(v, (0.21938393439552027368 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 0.21938393439552027368, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((2.0 + 0.0j))\\n    assert ae(v, (0.048900510708061119567 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 0.048900510708061119567, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((5.0 + 0.0j))\\n    assert ae(v, (0.0011482955912753257973 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 0.0011482955912753257973, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((20.0 + 0.0j))\\n    assert ae(v, (9.8355252906498816904e-11 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 9.8355252906498816904e-11, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((30.0 + 0.0j))\\n    assert ae(v, (3.0215520106888125448e-15 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 3.0215520106888125448e-15, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((40.0 + 0.0j))\\n    assert ae(v, (1.0367732614516569722e-19 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 1.0367732614516569722e-19, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((50.0 + 0.0j))\\n    assert ae(v, (3.7832640295504590187e-24 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 3.7832640295504590187e-24, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((80.0 + 0.0j))\\n    assert ae(v, (2.2285432586884729112e-37 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 2.2285432586884729112e-37, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.e1((4.6566128730773925781e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (20.880034622014215597 - 0.24497866301044883237j), tol=ATOL)\\n    assert ae(v.real, 20.880034622014215597, tol=PTOL)\\n    assert ae(v.imag, -0.24497866301044883237, tol=PTOL)\\n    v = fp.e1((1.0 + 0.25j))\\n    assert ae(v, (0.19731063945004229095 - 0.087366045774299963672j), tol=ATOL)\\n    assert ae(v.real, 0.19731063945004229095, tol=PTOL)\\n    assert ae(v.imag, -0.087366045774299963672, tol=PTOL)\\n    v = fp.e1((4.0 + 1.0j))\\n    assert ae(v, (0.0013106173980145506944 - 0.0034542480199350626699j), tol=ATOL)\\n    assert ae(v.real, 0.0013106173980145506944, tol=PTOL)\\n    assert ae(v.imag, -0.0034542480199350626699, tol=PTOL)\\n    v = fp.e1((8.0 + 2.0j))\\n    assert ae(v, (-0.000022278049065270225945 - 0.000029191940456521555288j), tol=ATOL)\\n    assert ae(v.real, -0.000022278049065270225945, tol=PTOL)\\n    assert ae(v.imag, -0.000029191940456521555288, tol=PTOL)\\n    v = fp.e1((20.0 + 5.0j))\\n    assert ae(v, (4.7711374515765346894e-11 + 8.2902652405126947359e-11j), tol=ATOL)\\n    assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL)\\n    assert ae(v.imag, 8.2902652405126947359e-11, tol=PTOL)\\n    v = fp.e1((80.0 + 20.0j))\\n    assert ae(v, (3.8353473865788235787e-38 - 2.129247592349605139e-37j), tol=ATOL)\\n    assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL)\\n    assert ae(v.imag, -2.129247592349605139e-37, tol=PTOL)\\n    v = fp.e1((120.0 + 30.0j))\\n    assert ae(v, (2.3836002337480334716e-55 + 5.6704043587126198306e-55j), tol=ATOL)\\n    assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL)\\n    assert ae(v.imag, 5.6704043587126198306e-55, tol=PTOL)\\n    v = fp.e1((160.0 + 40.0j))\\n    assert ae(v, (-1.6238022898654510661e-72 - 1.104172355572287367e-72j), tol=ATOL)\\n    assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL)\\n    assert ae(v.imag, -1.104172355572287367e-72, tol=PTOL)\\n    v = fp.e1((200.0 + 50.0j))\\n    assert ae(v, (6.6800061461666228487e-90 + 1.4473816083541016115e-91j), tol=ATOL)\\n    assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL)\\n    assert ae(v.imag, 1.4473816083541016115e-91, tol=PTOL)\\n    v = fp.e1((320.0 + 80.0j))\\n    assert ae(v, (4.2737871527778786157e-143 + 3.1789935525785660314e-142j), tol=ATOL)\\n    assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL)\\n    assert ae(v.imag, 3.1789935525785660314e-142, tol=PTOL)\\n    v = fp.e1((1.1641532182693481445e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (21.950067703413105017 - 0.7853981632810329878j), tol=ATOL)\\n    assert ae(v.real, 21.950067703413105017, tol=PTOL)\\n    assert ae(v.imag, -0.7853981632810329878, tol=PTOL)\\n    v = fp.e1((0.25 + 0.25j))\\n    assert ae(v, (0.71092525792923287894 - 0.56491812441304194711j), tol=ATOL)\\n    assert ae(v.real, 0.71092525792923287894, tol=PTOL)\\n    assert ae(v.imag, -0.56491812441304194711, tol=PTOL)\\n    v = fp.e1((1.0 + 1.0j))\\n    assert ae(v, (0.00028162445198141832551 - 0.17932453503935894015j), tol=ATOL)\\n    assert ae(v.real, 0.00028162445198141832551, tol=PTOL)\\n    assert ae(v.imag, -0.17932453503935894015, tol=PTOL)\\n    v = fp.e1((2.0 + 2.0j))\\n    assert ae(v, (-0.033767089606562004246 - 0.018599414169750541925j), tol=ATOL)\\n    assert ae(v.real, -0.033767089606562004246, tol=PTOL)\\n    assert ae(v.imag, -0.018599414169750541925, tol=PTOL)\\n    v = fp.e1((5.0 + 5.0j))\\n    assert ae(v, (0.0007266506660356393891 + 0.00047102780163522245054j), tol=ATOL)\\n    assert ae(v.real, 0.0007266506660356393891, tol=PTOL)\\n    assert ae(v.imag, 0.00047102780163522245054, tol=PTOL)\\n    v = fp.e1((20.0 + 20.0j))\\n    assert ae(v, (-2.3824537449367396579e-11 - 6.6969873156525615158e-11j), tol=ATOL)\\n    assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL)\\n    assert ae(v.imag, -6.6969873156525615158e-11, tol=PTOL)\\n    v = fp.e1((30.0 + 30.0j))\\n    assert ae(v, (1.7316045841744061617e-15 + 1.3065678019487308689e-15j), tol=ATOL)\\n    assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL)\\n    assert ae(v.imag, 1.3065678019487308689e-15, tol=PTOL)\\n    v = fp.e1((40.0 + 40.0j))\\n    assert ae(v, (-7.4001043002899232182e-20 - 4.991847855336816304e-21j), tol=ATOL)\\n    assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL)\\n    assert ae(v.imag, -4.991847855336816304e-21, tol=PTOL)\\n    v = fp.e1((50.0 + 50.0j))\\n    assert ae(v, (2.3566128324644641219e-24 - 1.3188326726201614778e-24j), tol=ATOL)\\n    assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL)\\n    assert ae(v.imag, -1.3188326726201614778e-24, tol=PTOL)\\n    v = fp.e1((80.0 + 80.0j))\\n    assert ae(v, (9.8279750572186526673e-38 + 1.243952841288868831e-37j), tol=ATOL)\\n    assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL)\\n    assert ae(v.imag, 1.243952841288868831e-37, tol=PTOL)\\n    v = fp.e1((1.1641532182693481445e-10 + 4.6566128730773925781e-10j))\\n    assert ae(v, (20.880034621664969632 - 1.3258176632023711778j), tol=ATOL)\\n    assert ae(v.real, 20.880034621664969632, tol=PTOL)\\n    assert ae(v.imag, -1.3258176632023711778, tol=PTOL)\\n    v = fp.e1((0.25 + 1.0j))\\n    assert ae(v, (-0.16868306393667788761 - 0.4858011885947426971j), tol=ATOL)\\n    assert ae(v.real, -0.16868306393667788761, tol=PTOL)\\n    assert ae(v.imag, -0.4858011885947426971, tol=PTOL)\\n    v = fp.e1((1.0 + 4.0j))\\n    assert ae(v, (0.03373591813926547318 + 0.073523452241083821877j), tol=ATOL)\\n    assert ae(v.real, 0.03373591813926547318, tol=PTOL)\\n    assert ae(v.imag, 0.073523452241083821877, tol=PTOL)\\n    v = fp.e1((2.0 + 8.0j))\\n    assert ae(v, (-0.015392833434733785143 - 0.0031747121557605415914j), tol=ATOL)\\n    assert ae(v.real, -0.015392833434733785143, tol=PTOL)\\n    assert ae(v.imag, -0.0031747121557605415914, tol=PTOL)\\n    v = fp.e1((5.0 + 20.0j))\\n    assert ae(v, (-0.00024419662286542966525 - 0.00021008322966152755674j), tol=ATOL)\\n    assert ae(v.real, -0.00024419662286542966525, tol=PTOL)\\n    assert ae(v.imag, -0.00021008322966152755674, tol=PTOL)\\n    v = fp.e1((20.0 + 80.0j))\\n    assert ae(v, (2.3255552781051330088e-11 + 8.9463918891349438007e-12j), tol=ATOL)\\n    assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL)\\n    assert ae(v.imag, 8.9463918891349438007e-12, tol=PTOL)\\n    v = fp.e1((30.0 + 120.0j))\\n    assert ae(v, (-2.7068919097124652332e-16 - 7.0477762411705130239e-16j), tol=ATOL)\\n    assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL)\\n    assert ae(v.imag, -7.0477762411705130239e-16, tol=PTOL)\\n    v = fp.e1((40.0 + 160.0j))\\n    assert ae(v, (-1.1695597827678024687e-20 + 2.2907401455645736661e-20j), tol=ATOL)\\n    assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL)\\n    assert ae(v.imag, 2.2907401455645736661e-20, tol=PTOL)\\n    v = fp.e1((50.0 + 200.0j))\\n    assert ae(v, (9.0323746914410162531e-25 - 2.3950601790033530935e-25j), tol=ATOL)\\n    assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL)\\n    assert ae(v.imag, -2.3950601790033530935e-25, tol=PTOL)\\n    v = fp.e1((80.0 + 320.0j))\\n    assert ae(v, (3.4819106748728063576e-38 - 4.215653005615772724e-38j), tol=ATOL)\\n    assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL)\\n    assert ae(v.imag, -4.215653005615772724e-38, tol=PTOL)\\n    v = fp.e1((0.0 + 1.1641532182693481445e-10j))\\n    assert ae(v, (22.29664129357666235 - 1.5707963266784812974j), tol=ATOL)\\n    assert ae(v.real, 22.29664129357666235, tol=PTOL)\\n    assert ae(v.imag, -1.5707963266784812974, tol=PTOL)\\n    v = fp.e1((0.0 + 0.25j))\\n    assert ae(v, (0.82466306258094565309 - 1.3216627564751394551j), tol=ATOL)\\n    assert ae(v.real, 0.82466306258094565309, tol=PTOL)\\n    assert ae(v.imag, -1.3216627564751394551, tol=PTOL)\\n    v = fp.e1((0.0 + 1.0j))\\n    assert ae(v, (-0.33740392290096813466 - 0.62471325642771360429j), tol=ATOL)\\n    assert ae(v.real, -0.33740392290096813466, tol=PTOL)\\n    assert ae(v.imag, -0.62471325642771360429, tol=PTOL)\\n    v = fp.e1((0.0 + 2.0j))\\n    assert ae(v, (-0.4229808287748649957 + 0.034616650007798229345j), tol=ATOL)\\n    assert ae(v.real, -0.4229808287748649957, tol=PTOL)\\n    assert ae(v.imag, 0.034616650007798229345, tol=PTOL)\\n    v = fp.e1((0.0 + 5.0j))\\n    assert ae(v, (0.19002974965664387862 - 0.020865081850222481957j), tol=ATOL)\\n    assert ae(v.real, 0.19002974965664387862, tol=PTOL)\\n    assert ae(v.imag, -0.020865081850222481957, tol=PTOL)\\n    v = fp.e1((0.0 + 20.0j))\\n    assert ae(v, (-0.04441982084535331654 - 0.022554625751456779068j), tol=ATOL)\\n    assert ae(v.real, -0.04441982084535331654, tol=PTOL)\\n    assert ae(v.imag, -0.022554625751456779068, tol=PTOL)\\n    v = fp.e1((0.0 + 30.0j))\\n    assert ae(v, (0.033032417282071143779 - 0.0040397867645455082476j), tol=ATOL)\\n    assert ae(v.real, 0.033032417282071143779, tol=PTOL)\\n    assert ae(v.imag, -0.0040397867645455082476, tol=PTOL)\\n    v = fp.e1((0.0 + 40.0j))\\n    assert ae(v, (-0.019020007896208766962 + 0.016188792559887887544j), tol=ATOL)\\n    assert ae(v.real, -0.019020007896208766962, tol=PTOL)\\n    assert ae(v.imag, 0.016188792559887887544, tol=PTOL)\\n    v = fp.e1((0.0 + 50.0j))\\n    assert ae(v, (0.0056283863241163054402 - 0.019179254308960724503j), tol=ATOL)\\n    assert ae(v.real, 0.0056283863241163054402, tol=PTOL)\\n    assert ae(v.imag, -0.019179254308960724503, tol=PTOL)\\n    v = fp.e1((0.0 + 80.0j))\\n    assert ae(v, (0.012402501155070958192 + 0.0015345601175906961199j), tol=ATOL)\\n    assert ae(v.real, 0.012402501155070958192, tol=PTOL)\\n    assert ae(v.imag, 0.0015345601175906961199, tol=PTOL)\\n    v = fp.e1((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j))\\n    assert ae(v, (20.880034621432138988 - 1.8157749894560994861j), tol=ATOL)\\n    assert ae(v.real, 20.880034621432138988, tol=PTOL)\\n    assert ae(v.imag, -1.8157749894560994861, tol=PTOL)\\n    v = fp.e1((-0.25 + 1.0j))\\n    assert ae(v, (-0.59066621214766308594 - 0.74474454765205036972j), tol=ATOL)\\n    assert ae(v.real, -0.59066621214766308594, tol=PTOL)\\n    assert ae(v.imag, -0.74474454765205036972, tol=PTOL)\\n    v = fp.e1((-1.0 + 4.0j))\\n    assert ae(v, (0.49739047283060471093 + 0.41543605404038863174j), tol=ATOL)\\n    assert ae(v.real, 0.49739047283060471093, tol=PTOL)\\n    assert ae(v.imag, 0.41543605404038863174, tol=PTOL)\\n    v = fp.e1((-2.0 + 8.0j))\\n    assert ae(v, (-0.8705211147733730969 + 0.24099328498605539667j), tol=ATOL)\\n    assert ae(v.real, -0.8705211147733730969, tol=PTOL)\\n    assert ae(v.imag, 0.24099328498605539667, tol=PTOL)\\n    v = fp.e1((-5.0 + 20.0j))\\n    assert ae(v, (-7.0789514293925893007 - 1.6102177171960790536j), tol=ATOL)\\n    assert ae(v.real, -7.0789514293925893007, tol=PTOL)\\n    assert ae(v.imag, -1.6102177171960790536, tol=PTOL)\\n    v = fp.e1((-20.0 + 80.0j))\\n    assert ae(v, (5855431.4907298084434 - 720920.93315409165707j), tol=ATOL)\\n    assert ae(v.real, 5855431.4907298084434, tol=PTOL)\\n    assert ae(v.imag, -720920.93315409165707, tol=PTOL)\\n    v = fp.e1((-30.0 + 120.0j))\\n    assert ae(v, (-65402491644.703470747 - 56697658399.657460294j), tol=ATOL)\\n    assert ae(v.real, -65402491644.703470747, tol=PTOL)\\n    assert ae(v.imag, -56697658399.657460294, tol=PTOL)\\n    v = fp.e1((-40.0 + 160.0j))\\n    assert ae(v, (25504929379604.776769 + 1429035198630573.2463j), tol=ATOL)\\n    assert ae(v.real, 25504929379604.776769, tol=PTOL)\\n    assert ae(v.imag, 1429035198630573.2463, tol=PTOL)\\n    v = fp.e1((-50.0 + 200.0j))\\n    assert ae(v, (18437746526988116954.0 - 17146362239046152345.0j), tol=ATOL)\\n    assert ae(v.real, 18437746526988116954.0, tol=PTOL)\\n    assert ae(v.imag, -17146362239046152345.0, tol=PTOL)\\n    v = fp.e1((-80.0 + 320.0j))\\n    assert ae(v, (3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL)\\n    assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL)\\n    assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL)\\n    v = fp.e1((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (20.880034621082893023 - 2.8966139903465137624j), tol=ATOL)\\n    assert ae(v.real, 20.880034621082893023, tol=PTOL)\\n    assert ae(v.imag, -2.8966139903465137624, tol=PTOL)\\n    v = fp.e1((-1.0 + 0.25j))\\n    assert ae(v, (-1.8942716983721074932 - 2.4689102827070540799j), tol=ATOL)\\n    assert ae(v.real, -1.8942716983721074932, tol=PTOL)\\n    assert ae(v.imag, -2.4689102827070540799, tol=PTOL)\\n    v = fp.e1((-4.0 + 1.0j))\\n    assert ae(v, (-14.806699492675420438 + 9.1384225230837893776j), tol=ATOL)\\n    assert ae(v.real, -14.806699492675420438, tol=PTOL)\\n    assert ae(v.imag, 9.1384225230837893776, tol=PTOL)\\n    v = fp.e1((-8.0 + 2.0j))\\n    assert ae(v, (54.633252667426386294 + 413.20318163814670688j), tol=ATOL)\\n    assert ae(v.real, 54.633252667426386294, tol=PTOL)\\n    assert ae(v.imag, 413.20318163814670688, tol=PTOL)\\n    v = fp.e1((-20.0 + 5.0j))\\n    assert ae(v, (-711836.97165402624643 - 24745250.939695900956j), tol=ATOL)\\n    assert ae(v.real, -711836.97165402624643, tol=PTOL)\\n    assert ae(v.imag, -24745250.939695900956, tol=PTOL)\\n    v = fp.e1((-80.0 + 20.0j))\\n    assert ae(v, (-4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL)\\n    assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL)\\n    assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL)\\n    v = fp.e1((-120.0 + 30.0j))\\n    assert ae(v, (9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL)\\n    assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL)\\n    assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL)\\n    v = fp.e1((-160.0 + 40.0j))\\n    assert ae(v, (8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL)\\n    assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL)\\n    assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL)\\n    v = fp.e1((-200.0 + 50.0j))\\n    assert ae(v, (-3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL)\\n    assert ae(v.real, -3.070744996327018106e+84, tol=PTOL)\\n    assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL)\\n    v = fp.e1((-320.0 + 80.0j))\\n    assert ae(v, (9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL)\\n    assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL)\\n    assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL)\\n    v = fp.e1(-1.1641532182693481445e-10)\\n    assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 22.296641293460247028, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-0.25)\\n    assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 0.54254326466191372953, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-1.0)\\n    assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -1.8951178163559367555, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-2.0)\\n    assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -4.9542343560018901634, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-5.0)\\n    assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -40.185275355803177455, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-20.0)\\n    assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -25615652.66405658882, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-30.0)\\n    assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -368973209407.27419706, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-40.0)\\n    assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -6039718263611241.5784, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-50.0)\\n    assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1(-80.0)\\n    assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-1.1641532182693481445e-10 + 0.0j))\\n    assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 22.296641293460247028, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-0.25 + 0.0j))\\n    assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 0.54254326466191372953, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-1.0 + 0.0j))\\n    assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -1.8951178163559367555, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-2.0 + 0.0j))\\n    assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -4.9542343560018901634, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-5.0 + 0.0j))\\n    assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -40.185275355803177455, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-20.0 + 0.0j))\\n    assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -25615652.66405658882, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-30.0 + 0.0j))\\n    assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -368973209407.27419706, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-40.0 + 0.0j))\\n    assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -6039718263611241.5784, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-50.0 + 0.0j))\\n    assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-80.0 + 0.0j))\\n    assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.e1((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (20.880034621082893023 + 2.8966139903465137624j), tol=ATOL)\\n    assert ae(v.real, 20.880034621082893023, tol=PTOL)\\n    assert ae(v.imag, 2.8966139903465137624, tol=PTOL)\\n    v = fp.e1((-1.0 - 0.25j))\\n    assert ae(v, (-1.8942716983721074932 + 2.4689102827070540799j), tol=ATOL)\\n    assert ae(v.real, -1.8942716983721074932, tol=PTOL)\\n    assert ae(v.imag, 2.4689102827070540799, tol=PTOL)\\n    v = fp.e1((-4.0 - 1.0j))\\n    assert ae(v, (-14.806699492675420438 - 9.1384225230837893776j), tol=ATOL)\\n    assert ae(v.real, -14.806699492675420438, tol=PTOL)\\n    assert ae(v.imag, -9.1384225230837893776, tol=PTOL)\\n    v = fp.e1((-8.0 - 2.0j))\\n    assert ae(v, (54.633252667426386294 - 413.20318163814670688j), tol=ATOL)\\n    assert ae(v.real, 54.633252667426386294, tol=PTOL)\\n    assert ae(v.imag, -413.20318163814670688, tol=PTOL)\\n    v = fp.e1((-20.0 - 5.0j))\\n    assert ae(v, (-711836.97165402624643 + 24745250.939695900956j), tol=ATOL)\\n    assert ae(v.real, -711836.97165402624643, tol=PTOL)\\n    assert ae(v.imag, 24745250.939695900956, tol=PTOL)\\n    v = fp.e1((-80.0 - 20.0j))\\n    assert ae(v, (-4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL)\\n    assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL)\\n    assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL)\\n    v = fp.e1((-120.0 - 30.0j))\\n    assert ae(v, (9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL)\\n    assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL)\\n    assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL)\\n    v = fp.e1((-160.0 - 40.0j))\\n    assert ae(v, (8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL)\\n    assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL)\\n    assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL)\\n    v = fp.e1((-200.0 - 50.0j))\\n    assert ae(v, (-3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL)\\n    assert ae(v.real, -3.070744996327018106e+84, tol=PTOL)\\n    assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL)\\n    v = fp.e1((-320.0 - 80.0j))\\n    assert ae(v, (9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL)\\n    assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL)\\n    assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL)\\n    v = fp.e1((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (21.950067703180274374 + 2.356194490075929607j), tol=ATOL)\\n    assert ae(v.real, 21.950067703180274374, tol=PTOL)\\n    assert ae(v.imag, 2.356194490075929607, tol=PTOL)\\n    v = fp.e1((-0.25 - 0.25j))\\n    assert ae(v, (0.21441047326710323254 + 2.0732153554307936389j), tol=ATOL)\\n    assert ae(v.real, 0.21441047326710323254, tol=PTOL)\\n    assert ae(v.imag, 2.0732153554307936389, tol=PTOL)\\n    v = fp.e1((-1.0 - 1.0j))\\n    assert ae(v, (-1.7646259855638540684 + 0.7538228020792708192j), tol=ATOL)\\n    assert ae(v.real, -1.7646259855638540684, tol=PTOL)\\n    assert ae(v.imag, 0.7538228020792708192, tol=PTOL)\\n    v = fp.e1((-2.0 - 2.0j))\\n    assert ae(v, (-1.8920781621855474089 - 2.1753697842428647236j), tol=ATOL)\\n    assert ae(v.real, -1.8920781621855474089, tol=PTOL)\\n    assert ae(v.imag, -2.1753697842428647236, tol=PTOL)\\n    v = fp.e1((-5.0 - 5.0j))\\n    assert ae(v, (13.470936071475245856 + 18.464085049321024206j), tol=ATOL)\\n    assert ae(v.real, 13.470936071475245856, tol=PTOL)\\n    assert ae(v.imag, 18.464085049321024206, tol=PTOL)\\n    v = fp.e1((-20.0 - 20.0j))\\n    assert ae(v, (-16589317.398788971896 - 5831702.3296441771206j), tol=ATOL)\\n    assert ae(v.real, -16589317.398788971896, tol=PTOL)\\n    assert ae(v.imag, -5831702.3296441771206, tol=PTOL)\\n    v = fp.e1((-30.0 - 30.0j))\\n    assert ae(v, (154596484273.69322527 + 204179357837.41389696j), tol=ATOL)\\n    assert ae(v.real, 154596484273.69322527, tol=PTOL)\\n    assert ae(v.imag, 204179357837.41389696, tol=PTOL)\\n    v = fp.e1((-40.0 - 40.0j))\\n    assert ae(v, (-287512180321448.45408 - 4203502407932314.974j), tol=ATOL)\\n    assert ae(v.real, -287512180321448.45408, tol=PTOL)\\n    assert ae(v.imag, -4203502407932314.974, tol=PTOL)\\n    v = fp.e1((-50.0 - 50.0j))\\n    assert ae(v, (-36128528616649268826.0 + 64648801861338741963.0j), tol=ATOL)\\n    assert ae(v.real, -36128528616649268826.0, tol=PTOL)\\n    assert ae(v.imag, 64648801861338741963.0, tol=PTOL)\\n    v = fp.e1((-80.0 - 80.0j))\\n    assert ae(v, (3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL)\\n    assert ae(v.real, 3.8674816337930010217e+32, tol=PTOL)\\n    assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL)\\n    v = fp.e1((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j))\\n    assert ae(v, (20.880034621432138988 + 1.8157749894560994861j), tol=ATOL)\\n    assert ae(v.real, 20.880034621432138988, tol=PTOL)\\n    assert ae(v.imag, 1.8157749894560994861, tol=PTOL)\\n    v = fp.e1((-0.25 - 1.0j))\\n    assert ae(v, (-0.59066621214766308594 + 0.74474454765205036972j), tol=ATOL)\\n    assert ae(v.real, -0.59066621214766308594, tol=PTOL)\\n    assert ae(v.imag, 0.74474454765205036972, tol=PTOL)\\n    v = fp.e1((-1.0 - 4.0j))\\n    assert ae(v, (0.49739047283060471093 - 0.41543605404038863174j), tol=ATOL)\\n    assert ae(v.real, 0.49739047283060471093, tol=PTOL)\\n    assert ae(v.imag, -0.41543605404038863174, tol=PTOL)\\n    v = fp.e1((-2.0 - 8.0j))\\n    assert ae(v, (-0.8705211147733730969 - 0.24099328498605539667j), tol=ATOL)\\n    assert ae(v.real, -0.8705211147733730969, tol=PTOL)\\n    assert ae(v.imag, -0.24099328498605539667, tol=PTOL)\\n    v = fp.e1((-5.0 - 20.0j))\\n    assert ae(v, (-7.0789514293925893007 + 1.6102177171960790536j), tol=ATOL)\\n    assert ae(v.real, -7.0789514293925893007, tol=PTOL)\\n    assert ae(v.imag, 1.6102177171960790536, tol=PTOL)\\n    v = fp.e1((-20.0 - 80.0j))\\n    assert ae(v, (5855431.4907298084434 + 720920.93315409165707j), tol=ATOL)\\n    assert ae(v.real, 5855431.4907298084434, tol=PTOL)\\n    assert ae(v.imag, 720920.93315409165707, tol=PTOL)\\n    v = fp.e1((-30.0 - 120.0j))\\n    assert ae(v, (-65402491644.703470747 + 56697658399.657460294j), tol=ATOL)\\n    assert ae(v.real, -65402491644.703470747, tol=PTOL)\\n    assert ae(v.imag, 56697658399.657460294, tol=PTOL)\\n    v = fp.e1((-40.0 - 160.0j))\\n    assert ae(v, (25504929379604.776769 - 1429035198630573.2463j), tol=ATOL)\\n    assert ae(v.real, 25504929379604.776769, tol=PTOL)\\n    assert ae(v.imag, -1429035198630573.2463, tol=PTOL)\\n    v = fp.e1((-50.0 - 200.0j))\\n    assert ae(v, (18437746526988116954.0 + 17146362239046152345.0j), tol=ATOL)\\n    assert ae(v.real, 18437746526988116954.0, tol=PTOL)\\n    assert ae(v.imag, 17146362239046152345.0, tol=PTOL)\\n    v = fp.e1((-80.0 - 320.0j))\\n    assert ae(v, (3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL)\\n    assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL)\\n    assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL)\\n    v = fp.e1((0.0 - 1.1641532182693481445e-10j))\\n    assert ae(v, (22.29664129357666235 + 1.5707963266784812974j), tol=ATOL)\\n    assert ae(v.real, 22.29664129357666235, tol=PTOL)\\n    assert ae(v.imag, 1.5707963266784812974, tol=PTOL)\\n    v = fp.e1((0.0 - 0.25j))\\n    assert ae(v, (0.82466306258094565309 + 1.3216627564751394551j), tol=ATOL)\\n    assert ae(v.real, 0.82466306258094565309, tol=PTOL)\\n    assert ae(v.imag, 1.3216627564751394551, tol=PTOL)\\n    v = fp.e1((0.0 - 1.0j))\\n    assert ae(v, (-0.33740392290096813466 + 0.62471325642771360429j), tol=ATOL)\\n    assert ae(v.real, -0.33740392290096813466, tol=PTOL)\\n    assert ae(v.imag, 0.62471325642771360429, tol=PTOL)\\n    v = fp.e1((0.0 - 2.0j))\\n    assert ae(v, (-0.4229808287748649957 - 0.034616650007798229345j), tol=ATOL)\\n    assert ae(v.real, -0.4229808287748649957, tol=PTOL)\\n    assert ae(v.imag, -0.034616650007798229345, tol=PTOL)\\n    v = fp.e1((0.0 - 5.0j))\\n    assert ae(v, (0.19002974965664387862 + 0.020865081850222481957j), tol=ATOL)\\n    assert ae(v.real, 0.19002974965664387862, tol=PTOL)\\n    assert ae(v.imag, 0.020865081850222481957, tol=PTOL)\\n    v = fp.e1((0.0 - 20.0j))\\n    assert ae(v, (-0.04441982084535331654 + 0.022554625751456779068j), tol=ATOL)\\n    assert ae(v.real, -0.04441982084535331654, tol=PTOL)\\n    assert ae(v.imag, 0.022554625751456779068, tol=PTOL)\\n    v = fp.e1((0.0 - 30.0j))\\n    assert ae(v, (0.033032417282071143779 + 0.0040397867645455082476j), tol=ATOL)\\n    assert ae(v.real, 0.033032417282071143779, tol=PTOL)\\n    assert ae(v.imag, 0.0040397867645455082476, tol=PTOL)\\n    v = fp.e1((0.0 - 40.0j))\\n    assert ae(v, (-0.019020007896208766962 - 0.016188792559887887544j), tol=ATOL)\\n    assert ae(v.real, -0.019020007896208766962, tol=PTOL)\\n    assert ae(v.imag, -0.016188792559887887544, tol=PTOL)\\n    v = fp.e1((0.0 - 50.0j))\\n    assert ae(v, (0.0056283863241163054402 + 0.019179254308960724503j), tol=ATOL)\\n    assert ae(v.real, 0.0056283863241163054402, tol=PTOL)\\n    assert ae(v.imag, 0.019179254308960724503, tol=PTOL)\\n    v = fp.e1((0.0 - 80.0j))\\n    assert ae(v, (0.012402501155070958192 - 0.0015345601175906961199j), tol=ATOL)\\n    assert ae(v.real, 0.012402501155070958192, tol=PTOL)\\n    assert ae(v.imag, -0.0015345601175906961199, tol=PTOL)\\n    v = fp.e1((1.1641532182693481445e-10 - 4.6566128730773925781e-10j))\\n    assert ae(v, (20.880034621664969632 + 1.3258176632023711778j), tol=ATOL)\\n    assert ae(v.real, 20.880034621664969632, tol=PTOL)\\n    assert ae(v.imag, 1.3258176632023711778, tol=PTOL)\\n    v = fp.e1((0.25 - 1.0j))\\n    assert ae(v, (-0.16868306393667788761 + 0.4858011885947426971j), tol=ATOL)\\n    assert ae(v.real, -0.16868306393667788761, tol=PTOL)\\n    assert ae(v.imag, 0.4858011885947426971, tol=PTOL)\\n    v = fp.e1((1.0 - 4.0j))\\n    assert ae(v, (0.03373591813926547318 - 0.073523452241083821877j), tol=ATOL)\\n    assert ae(v.real, 0.03373591813926547318, tol=PTOL)\\n    assert ae(v.imag, -0.073523452241083821877, tol=PTOL)\\n    v = fp.e1((2.0 - 8.0j))\\n    assert ae(v, (-0.015392833434733785143 + 0.0031747121557605415914j), tol=ATOL)\\n    assert ae(v.real, -0.015392833434733785143, tol=PTOL)\\n    assert ae(v.imag, 0.0031747121557605415914, tol=PTOL)\\n    v = fp.e1((5.0 - 20.0j))\\n    assert ae(v, (-0.00024419662286542966525 + 0.00021008322966152755674j), tol=ATOL)\\n    assert ae(v.real, -0.00024419662286542966525, tol=PTOL)\\n    assert ae(v.imag, 0.00021008322966152755674, tol=PTOL)\\n    v = fp.e1((20.0 - 80.0j))\\n    assert ae(v, (2.3255552781051330088e-11 - 8.9463918891349438007e-12j), tol=ATOL)\\n    assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL)\\n    assert ae(v.imag, -8.9463918891349438007e-12, tol=PTOL)\\n    v = fp.e1((30.0 - 120.0j))\\n    assert ae(v, (-2.7068919097124652332e-16 + 7.0477762411705130239e-16j), tol=ATOL)\\n    assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL)\\n    assert ae(v.imag, 7.0477762411705130239e-16, tol=PTOL)\\n    v = fp.e1((40.0 - 160.0j))\\n    assert ae(v, (-1.1695597827678024687e-20 - 2.2907401455645736661e-20j), tol=ATOL)\\n    assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL)\\n    assert ae(v.imag, -2.2907401455645736661e-20, tol=PTOL)\\n    v = fp.e1((50.0 - 200.0j))\\n    assert ae(v, (9.0323746914410162531e-25 + 2.3950601790033530935e-25j), tol=ATOL)\\n    assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL)\\n    assert ae(v.imag, 2.3950601790033530935e-25, tol=PTOL)\\n    v = fp.e1((80.0 - 320.0j))\\n    assert ae(v, (3.4819106748728063576e-38 + 4.215653005615772724e-38j), tol=ATOL)\\n    assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL)\\n    assert ae(v.imag, 4.215653005615772724e-38, tol=PTOL)\\n    v = fp.e1((1.1641532182693481445e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (21.950067703413105017 + 0.7853981632810329878j), tol=ATOL)\\n    assert ae(v.real, 21.950067703413105017, tol=PTOL)\\n    assert ae(v.imag, 0.7853981632810329878, tol=PTOL)\\n    v = fp.e1((0.25 - 0.25j))\\n    assert ae(v, (0.71092525792923287894 + 0.56491812441304194711j), tol=ATOL)\\n    assert ae(v.real, 0.71092525792923287894, tol=PTOL)\\n    assert ae(v.imag, 0.56491812441304194711, tol=PTOL)\\n    v = fp.e1((1.0 - 1.0j))\\n    assert ae(v, (0.00028162445198141832551 + 0.17932453503935894015j), tol=ATOL)\\n    assert ae(v.real, 0.00028162445198141832551, tol=PTOL)\\n    assert ae(v.imag, 0.17932453503935894015, tol=PTOL)\\n    v = fp.e1((2.0 - 2.0j))\\n    assert ae(v, (-0.033767089606562004246 + 0.018599414169750541925j), tol=ATOL)\\n    assert ae(v.real, -0.033767089606562004246, tol=PTOL)\\n    assert ae(v.imag, 0.018599414169750541925, tol=PTOL)\\n    v = fp.e1((5.0 - 5.0j))\\n    assert ae(v, (0.0007266506660356393891 - 0.00047102780163522245054j), tol=ATOL)\\n    assert ae(v.real, 0.0007266506660356393891, tol=PTOL)\\n    assert ae(v.imag, -0.00047102780163522245054, tol=PTOL)\\n    v = fp.e1((20.0 - 20.0j))\\n    assert ae(v, (-2.3824537449367396579e-11 + 6.6969873156525615158e-11j), tol=ATOL)\\n    assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL)\\n    assert ae(v.imag, 6.6969873156525615158e-11, tol=PTOL)\\n    v = fp.e1((30.0 - 30.0j))\\n    assert ae(v, (1.7316045841744061617e-15 - 1.3065678019487308689e-15j), tol=ATOL)\\n    assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL)\\n    assert ae(v.imag, -1.3065678019487308689e-15, tol=PTOL)\\n    v = fp.e1((40.0 - 40.0j))\\n    assert ae(v, (-7.4001043002899232182e-20 + 4.991847855336816304e-21j), tol=ATOL)\\n    assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL)\\n    assert ae(v.imag, 4.991847855336816304e-21, tol=PTOL)\\n    v = fp.e1((50.0 - 50.0j))\\n    assert ae(v, (2.3566128324644641219e-24 + 1.3188326726201614778e-24j), tol=ATOL)\\n    assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL)\\n    assert ae(v.imag, 1.3188326726201614778e-24, tol=PTOL)\\n    v = fp.e1((80.0 - 80.0j))\\n    assert ae(v, (9.8279750572186526673e-38 - 1.243952841288868831e-37j), tol=ATOL)\\n    assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL)\\n    assert ae(v.imag, -1.243952841288868831e-37, tol=PTOL)\\n    v = fp.e1((4.6566128730773925781e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (20.880034622014215597 + 0.24497866301044883237j), tol=ATOL)\\n    assert ae(v.real, 20.880034622014215597, tol=PTOL)\\n    assert ae(v.imag, 0.24497866301044883237, tol=PTOL)\\n    v = fp.e1((1.0 - 0.25j))\\n    assert ae(v, (0.19731063945004229095 + 0.087366045774299963672j), tol=ATOL)\\n    assert ae(v.real, 0.19731063945004229095, tol=PTOL)\\n    assert ae(v.imag, 0.087366045774299963672, tol=PTOL)\\n    v = fp.e1((4.0 - 1.0j))\\n    assert ae(v, (0.0013106173980145506944 + 0.0034542480199350626699j), tol=ATOL)\\n    assert ae(v.real, 0.0013106173980145506944, tol=PTOL)\\n    assert ae(v.imag, 0.0034542480199350626699, tol=PTOL)\\n    v = fp.e1((8.0 - 2.0j))\\n    assert ae(v, (-0.000022278049065270225945 + 0.000029191940456521555288j), tol=ATOL)\\n    assert ae(v.real, -0.000022278049065270225945, tol=PTOL)\\n    assert ae(v.imag, 0.000029191940456521555288, tol=PTOL)\\n    v = fp.e1((20.0 - 5.0j))\\n    assert ae(v, (4.7711374515765346894e-11 - 8.2902652405126947359e-11j), tol=ATOL)\\n    assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL)\\n    assert ae(v.imag, -8.2902652405126947359e-11, tol=PTOL)\\n    v = fp.e1((80.0 - 20.0j))\\n    assert ae(v, (3.8353473865788235787e-38 + 2.129247592349605139e-37j), tol=ATOL)\\n    assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL)\\n    assert ae(v.imag, 2.129247592349605139e-37, tol=PTOL)\\n    v = fp.e1((120.0 - 30.0j))\\n    assert ae(v, (2.3836002337480334716e-55 - 5.6704043587126198306e-55j), tol=ATOL)\\n    assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL)\\n    assert ae(v.imag, -5.6704043587126198306e-55, tol=PTOL)\\n    v = fp.e1((160.0 - 40.0j))\\n    assert ae(v, (-1.6238022898654510661e-72 + 1.104172355572287367e-72j), tol=ATOL)\\n    assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL)\\n    assert ae(v.imag, 1.104172355572287367e-72, tol=PTOL)\\n    v = fp.e1((200.0 - 50.0j))\\n    assert ae(v, (6.6800061461666228487e-90 - 1.4473816083541016115e-91j), tol=ATOL)\\n    assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL)\\n    assert ae(v.imag, -1.4473816083541016115e-91, tol=PTOL)\\n    v = fp.e1((320.0 - 80.0j))\\n    assert ae(v, (4.2737871527778786157e-143 - 3.1789935525785660314e-142j), tol=ATOL)\\n    assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL)\\n    assert ae(v.imag, -3.1789935525785660314e-142, tol=PTOL)\\n    v = fp.ei(1.1641532182693481445e-10)\\n    assert ae(v, -22.296641293460247028, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(0.25)\\n    assert ae(v, -0.54254326466191372953, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(1.0)\\n    assert ae(v, 1.8951178163559367555, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(2.0)\\n    assert ae(v, 4.9542343560018901634, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(5.0)\\n    assert ae(v, 40.185275355803177455, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(20.0)\\n    assert ae(v, 25615652.66405658882, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(30.0)\\n    assert ae(v, 368973209407.27419706, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(40.0)\\n    assert ae(v, 6039718263611241.5784, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(50.0)\\n    assert ae(v, 1.0585636897131690963e+20, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(80.0)\\n    assert ae(v, 7.0146000049047999696e+32, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei((1.1641532182693481445e-10 + 0.0j))\\n    assert ae(v, (-22.296641293460247028 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -22.296641293460247028, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((0.25 + 0.0j))\\n    assert ae(v, (-0.54254326466191372953 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -0.54254326466191372953, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((1.0 + 0.0j))\\n    assert ae(v, (1.8951178163559367555 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 1.8951178163559367555, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((2.0 + 0.0j))\\n    assert ae(v, (4.9542343560018901634 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 4.9542343560018901634, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((5.0 + 0.0j))\\n    assert ae(v, (40.185275355803177455 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 40.185275355803177455, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((20.0 + 0.0j))\\n    assert ae(v, (25615652.66405658882 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 25615652.66405658882, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((30.0 + 0.0j))\\n    assert ae(v, (368973209407.27419706 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 368973209407.27419706, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((40.0 + 0.0j))\\n    assert ae(v, (6039718263611241.5784 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 6039718263611241.5784, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((50.0 + 0.0j))\\n    assert ae(v, (1.0585636897131690963e+20 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 1.0585636897131690963e+20, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((80.0 + 0.0j))\\n    assert ae(v, (7.0146000049047999696e+32 + 0.0j), tol=ATOL)\\n    assert ae(v.real, 7.0146000049047999696e+32, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((4.6566128730773925781e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (-20.880034621082893023 + 0.24497866324327947603j), tol=ATOL)\\n    assert ae(v.real, -20.880034621082893023, tol=PTOL)\\n    assert ae(v.imag, 0.24497866324327947603, tol=PTOL)\\n    v = fp.ei((1.0 + 0.25j))\\n    assert ae(v, (1.8942716983721074932 + 0.67268237088273915854j), tol=ATOL)\\n    assert ae(v.real, 1.8942716983721074932, tol=PTOL)\\n    assert ae(v.imag, 0.67268237088273915854, tol=PTOL)\\n    v = fp.ei((4.0 + 1.0j))\\n    assert ae(v, (14.806699492675420438 + 12.280015176673582616j), tol=ATOL)\\n    assert ae(v.real, 14.806699492675420438, tol=PTOL)\\n    assert ae(v.imag, 12.280015176673582616, tol=PTOL)\\n    v = fp.ei((8.0 + 2.0j))\\n    assert ae(v, (-54.633252667426386294 + 416.34477429173650012j), tol=ATOL)\\n    assert ae(v.real, -54.633252667426386294, tol=PTOL)\\n    assert ae(v.imag, 416.34477429173650012, tol=PTOL)\\n    v = fp.ei((20.0 + 5.0j))\\n    assert ae(v, (711836.97165402624643 - 24745247.798103247366j), tol=ATOL)\\n    assert ae(v.real, 711836.97165402624643, tol=PTOL)\\n    assert ae(v.imag, -24745247.798103247366, tol=PTOL)\\n    v = fp.ei((80.0 + 20.0j))\\n    assert ae(v, (4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL)\\n    assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL)\\n    assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL)\\n    v = fp.ei((120.0 + 30.0j))\\n    assert ae(v, (-9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL)\\n    assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL)\\n    assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL)\\n    v = fp.ei((160.0 + 40.0j))\\n    assert ae(v, (-8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL)\\n    assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL)\\n    assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL)\\n    v = fp.ei((200.0 + 50.0j))\\n    assert ae(v, (3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL)\\n    assert ae(v.real, 3.070744996327018106e+84, tol=PTOL)\\n    assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL)\\n    v = fp.ei((320.0 + 80.0j))\\n    assert ae(v, (-9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL)\\n    assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL)\\n    assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL)\\n    v = fp.ei((1.1641532182693481445e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (-21.950067703180274374 + 0.78539816351386363145j), tol=ATOL)\\n    assert ae(v.real, -21.950067703180274374, tol=PTOL)\\n    assert ae(v.imag, 0.78539816351386363145, tol=PTOL)\\n    v = fp.ei((0.25 + 0.25j))\\n    assert ae(v, (-0.21441047326710323254 + 1.0683772981589995996j), tol=ATOL)\\n    assert ae(v.real, -0.21441047326710323254, tol=PTOL)\\n    assert ae(v.imag, 1.0683772981589995996, tol=PTOL)\\n    v = fp.ei((1.0 + 1.0j))\\n    assert ae(v, (1.7646259855638540684 + 2.3877698515105224193j), tol=ATOL)\\n    assert ae(v.real, 1.7646259855638540684, tol=PTOL)\\n    assert ae(v.imag, 2.3877698515105224193, tol=PTOL)\\n    v = fp.ei((2.0 + 2.0j))\\n    assert ae(v, (1.8920781621855474089 + 5.3169624378326579621j), tol=ATOL)\\n    assert ae(v.real, 1.8920781621855474089, tol=PTOL)\\n    assert ae(v.imag, 5.3169624378326579621, tol=PTOL)\\n    v = fp.ei((5.0 + 5.0j))\\n    assert ae(v, (-13.470936071475245856 - 15.322492395731230968j), tol=ATOL)\\n    assert ae(v.real, -13.470936071475245856, tol=PTOL)\\n    assert ae(v.imag, -15.322492395731230968, tol=PTOL)\\n    v = fp.ei((20.0 + 20.0j))\\n    assert ae(v, (16589317.398788971896 + 5831705.4712368307104j), tol=ATOL)\\n    assert ae(v.real, 16589317.398788971896, tol=PTOL)\\n    assert ae(v.imag, 5831705.4712368307104, tol=PTOL)\\n    v = fp.ei((30.0 + 30.0j))\\n    assert ae(v, (-154596484273.69322527 - 204179357834.2723043j), tol=ATOL)\\n    assert ae(v.real, -154596484273.69322527, tol=PTOL)\\n    assert ae(v.imag, -204179357834.2723043, tol=PTOL)\\n    v = fp.ei((40.0 + 40.0j))\\n    assert ae(v, (287512180321448.45408 + 4203502407932318.1156j), tol=ATOL)\\n    assert ae(v.real, 287512180321448.45408, tol=PTOL)\\n    assert ae(v.imag, 4203502407932318.1156, tol=PTOL)\\n    v = fp.ei((50.0 + 50.0j))\\n    assert ae(v, (36128528616649268826.0 - 64648801861338741960.0j), tol=ATOL)\\n    assert ae(v.real, 36128528616649268826.0, tol=PTOL)\\n    assert ae(v.imag, -64648801861338741960.0, tol=PTOL)\\n    v = fp.ei((80.0 + 80.0j))\\n    assert ae(v, (-3.8674816337930010217e+32 - 3.0540709639658071041e+32j), tol=ATOL)\\n    assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL)\\n    assert ae(v.imag, -3.0540709639658071041e+32, tol=PTOL)\\n    v = fp.ei((1.1641532182693481445e-10 + 4.6566128730773925781e-10j))\\n    assert ae(v, (-20.880034621432138988 + 1.3258176641336937524j), tol=ATOL)\\n    assert ae(v.real, -20.880034621432138988, tol=PTOL)\\n    assert ae(v.imag, 1.3258176641336937524, tol=PTOL)\\n    v = fp.ei((0.25 + 1.0j))\\n    assert ae(v, (0.59066621214766308594 + 2.3968481059377428687j), tol=ATOL)\\n    assert ae(v.real, 0.59066621214766308594, tol=PTOL)\\n    assert ae(v.imag, 2.3968481059377428687, tol=PTOL)\\n    v = fp.ei((1.0 + 4.0j))\\n    assert ae(v, (-0.49739047283060471093 + 3.5570287076301818702j), tol=ATOL)\\n    assert ae(v.real, -0.49739047283060471093, tol=PTOL)\\n    assert ae(v.imag, 3.5570287076301818702, tol=PTOL)\\n    v = fp.ei((2.0 + 8.0j))\\n    assert ae(v, (0.8705211147733730969 + 3.3825859385758486351j), tol=ATOL)\\n    assert ae(v.real, 0.8705211147733730969, tol=PTOL)\\n    assert ae(v.imag, 3.3825859385758486351, tol=PTOL)\\n    v = fp.ei((5.0 + 20.0j))\\n    assert ae(v, (7.0789514293925893007 + 1.5313749363937141849j), tol=ATOL)\\n    assert ae(v.real, 7.0789514293925893007, tol=PTOL)\\n    assert ae(v.imag, 1.5313749363937141849, tol=PTOL)\\n    v = fp.ei((20.0 + 80.0j))\\n    assert ae(v, (-5855431.4907298084434 - 720917.79156143806727j), tol=ATOL)\\n    assert ae(v.real, -5855431.4907298084434, tol=PTOL)\\n    assert ae(v.imag, -720917.79156143806727, tol=PTOL)\\n    v = fp.ei((30.0 + 120.0j))\\n    assert ae(v, (65402491644.703470747 - 56697658396.51586764j), tol=ATOL)\\n    assert ae(v.real, 65402491644.703470747, tol=PTOL)\\n    assert ae(v.imag, -56697658396.51586764, tol=PTOL)\\n    v = fp.ei((40.0 + 160.0j))\\n    assert ae(v, (-25504929379604.776769 + 1429035198630576.3879j), tol=ATOL)\\n    assert ae(v.real, -25504929379604.776769, tol=PTOL)\\n    assert ae(v.imag, 1429035198630576.3879, tol=PTOL)\\n    v = fp.ei((50.0 + 200.0j))\\n    assert ae(v, (-18437746526988116954.0 - 17146362239046152342.0j), tol=ATOL)\\n    assert ae(v.real, -18437746526988116954.0, tol=PTOL)\\n    assert ae(v.imag, -17146362239046152342.0, tol=PTOL)\\n    v = fp.ei((80.0 + 320.0j))\\n    assert ae(v, (-3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL)\\n    assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL)\\n    assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL)\\n    v = fp.ei((0.0 + 1.1641532182693481445e-10j))\\n    assert ae(v, (-22.29664129357666235 + 1.5707963269113119411j), tol=ATOL)\\n    assert ae(v.real, -22.29664129357666235, tol=PTOL)\\n    assert ae(v.imag, 1.5707963269113119411, tol=PTOL)\\n    v = fp.ei((0.0 + 0.25j))\\n    assert ae(v, (-0.82466306258094565309 + 1.8199298971146537833j), tol=ATOL)\\n    assert ae(v.real, -0.82466306258094565309, tol=PTOL)\\n    assert ae(v.imag, 1.8199298971146537833, tol=PTOL)\\n    v = fp.ei((0.0 + 1.0j))\\n    assert ae(v, (0.33740392290096813466 + 2.5168793971620796342j), tol=ATOL)\\n    assert ae(v.real, 0.33740392290096813466, tol=PTOL)\\n    assert ae(v.imag, 2.5168793971620796342, tol=PTOL)\\n    v = fp.ei((0.0 + 2.0j))\\n    assert ae(v, (0.4229808287748649957 + 3.1762093035975914678j), tol=ATOL)\\n    assert ae(v.real, 0.4229808287748649957, tol=PTOL)\\n    assert ae(v.imag, 3.1762093035975914678, tol=PTOL)\\n    v = fp.ei((0.0 + 5.0j))\\n    assert ae(v, (-0.19002974965664387862 + 3.1207275717395707565j), tol=ATOL)\\n    assert ae(v.real, -0.19002974965664387862, tol=PTOL)\\n    assert ae(v.imag, 3.1207275717395707565, tol=PTOL)\\n    v = fp.ei((0.0 + 20.0j))\\n    assert ae(v, (0.04441982084535331654 + 3.1190380278383364594j), tol=ATOL)\\n    assert ae(v.real, 0.04441982084535331654, tol=PTOL)\\n    assert ae(v.imag, 3.1190380278383364594, tol=PTOL)\\n    v = fp.ei((0.0 + 30.0j))\\n    assert ae(v, (-0.033032417282071143779 + 3.1375528668252477302j), tol=ATOL)\\n    assert ae(v.real, -0.033032417282071143779, tol=PTOL)\\n    assert ae(v.imag, 3.1375528668252477302, tol=PTOL)\\n    v = fp.ei((0.0 + 40.0j))\\n    assert ae(v, (0.019020007896208766962 + 3.157781446149681126j), tol=ATOL)\\n    assert ae(v.real, 0.019020007896208766962, tol=PTOL)\\n    assert ae(v.imag, 3.157781446149681126, tol=PTOL)\\n    v = fp.ei((0.0 + 50.0j))\\n    assert ae(v, (-0.0056283863241163054402 + 3.122413399280832514j), tol=ATOL)\\n    assert ae(v.real, -0.0056283863241163054402, tol=PTOL)\\n    assert ae(v.imag, 3.122413399280832514, tol=PTOL)\\n    v = fp.ei((0.0 + 80.0j))\\n    assert ae(v, (-0.012402501155070958192 + 3.1431272137073839346j), tol=ATOL)\\n    assert ae(v.real, -0.012402501155070958192, tol=PTOL)\\n    assert ae(v.imag, 3.1431272137073839346, tol=PTOL)\\n    v = fp.ei((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j))\\n    assert ae(v, (-20.880034621664969632 + 1.8157749903874220607j), tol=ATOL)\\n    assert ae(v.real, -20.880034621664969632, tol=PTOL)\\n    assert ae(v.imag, 1.8157749903874220607, tol=PTOL)\\n    v = fp.ei((-0.25 + 1.0j))\\n    assert ae(v, (0.16868306393667788761 + 2.6557914649950505414j), tol=ATOL)\\n    assert ae(v.real, 0.16868306393667788761, tol=PTOL)\\n    assert ae(v.imag, 2.6557914649950505414, tol=PTOL)\\n    v = fp.ei((-1.0 + 4.0j))\\n    assert ae(v, (-0.03373591813926547318 + 3.2151161058308770603j), tol=ATOL)\\n    assert ae(v.real, -0.03373591813926547318, tol=PTOL)\\n    assert ae(v.imag, 3.2151161058308770603, tol=PTOL)\\n    v = fp.ei((-2.0 + 8.0j))\\n    assert ae(v, (0.015392833434733785143 + 3.1384179414340326969j), tol=ATOL)\\n    assert ae(v.real, 0.015392833434733785143, tol=PTOL)\\n    assert ae(v.imag, 3.1384179414340326969, tol=PTOL)\\n    v = fp.ei((-5.0 + 20.0j))\\n    assert ae(v, (0.00024419662286542966525 + 3.1413825703601317109j), tol=ATOL)\\n    assert ae(v.real, 0.00024419662286542966525, tol=PTOL)\\n    assert ae(v.imag, 3.1413825703601317109, tol=PTOL)\\n    v = fp.ei((-20.0 + 80.0j))\\n    assert ae(v, (-2.3255552781051330088e-11 + 3.1415926535987396304j), tol=ATOL)\\n    assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535987396304, tol=PTOL)\\n    v = fp.ei((-30.0 + 120.0j))\\n    assert ae(v, (2.7068919097124652332e-16 + 3.1415926535897925337j), tol=ATOL)\\n    assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897925337, tol=PTOL)\\n    v = fp.ei((-40.0 + 160.0j))\\n    assert ae(v, (1.1695597827678024687e-20 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-50.0 + 200.0j))\\n    assert ae(v, (-9.0323746914410162531e-25 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-80.0 + 320.0j))\\n    assert ae(v, (-3.4819106748728063576e-38 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j))\\n    assert ae(v, (-20.880034622014215597 + 2.8966139905793444061j), tol=ATOL)\\n    assert ae(v.real, -20.880034622014215597, tol=PTOL)\\n    assert ae(v.imag, 2.8966139905793444061, tol=PTOL)\\n    v = fp.ei((-1.0 + 0.25j))\\n    assert ae(v, (-0.19731063945004229095 + 3.0542266078154932748j), tol=ATOL)\\n    assert ae(v.real, -0.19731063945004229095, tol=PTOL)\\n    assert ae(v.imag, 3.0542266078154932748, tol=PTOL)\\n    v = fp.ei((-4.0 + 1.0j))\\n    assert ae(v, (-0.0013106173980145506944 + 3.1381384055698581758j), tol=ATOL)\\n    assert ae(v.real, -0.0013106173980145506944, tol=PTOL)\\n    assert ae(v.imag, 3.1381384055698581758, tol=PTOL)\\n    v = fp.ei((-8.0 + 2.0j))\\n    assert ae(v, (0.000022278049065270225945 + 3.1415634616493367169j), tol=ATOL)\\n    assert ae(v.real, 0.000022278049065270225945, tol=PTOL)\\n    assert ae(v.imag, 3.1415634616493367169, tol=PTOL)\\n    v = fp.ei((-20.0 + 5.0j))\\n    assert ae(v, (-4.7711374515765346894e-11 + 3.1415926536726958909j), tol=ATOL)\\n    assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL)\\n    assert ae(v.imag, 3.1415926536726958909, tol=PTOL)\\n    v = fp.ei((-80.0 + 20.0j))\\n    assert ae(v, (-3.8353473865788235787e-38 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-120.0 + 30.0j))\\n    assert ae(v, (-2.3836002337480334716e-55 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-160.0 + 40.0j))\\n    assert ae(v, (1.6238022898654510661e-72 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-200.0 + 50.0j))\\n    assert ae(v, (-6.6800061461666228487e-90 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-320.0 + 80.0j))\\n    assert ae(v, (-4.2737871527778786157e-143 + 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL)\\n    assert ae(v.imag, 3.1415926535897932385, tol=PTOL)\\n    v = fp.ei(-1.1641532182693481445e-10)\\n    assert ae(v, -22.296641293693077672, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-0.25)\\n    assert ae(v, -1.0442826344437381945, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-1.0)\\n    assert ae(v, -0.21938393439552027368, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-2.0)\\n    assert ae(v, -0.048900510708061119567, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-5.0)\\n    assert ae(v, -0.0011482955912753257973, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-20.0)\\n    assert ae(v, -9.8355252906498816904e-11, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-30.0)\\n    assert ae(v, -3.0215520106888125448e-15, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-40.0)\\n    assert ae(v, -1.0367732614516569722e-19, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-50.0)\\n    assert ae(v, -3.7832640295504590187e-24, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei(-80.0)\\n    assert ae(v, -2.2285432586884729112e-37, tol=ATOL)\\n    assert type(v) is float\\n    v = fp.ei((-1.1641532182693481445e-10 + 0.0j))\\n    assert ae(v, (-22.296641293693077672 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -22.296641293693077672, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-0.25 + 0.0j))\\n    assert ae(v, (-1.0442826344437381945 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -1.0442826344437381945, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-1.0 + 0.0j))\\n    assert ae(v, (-0.21938393439552027368 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -0.21938393439552027368, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-2.0 + 0.0j))\\n    assert ae(v, (-0.048900510708061119567 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -0.048900510708061119567, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-5.0 + 0.0j))\\n    assert ae(v, (-0.0011482955912753257973 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -0.0011482955912753257973, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-20.0 + 0.0j))\\n    assert ae(v, (-9.8355252906498816904e-11 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -9.8355252906498816904e-11, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-30.0 + 0.0j))\\n    assert ae(v, (-3.0215520106888125448e-15 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -3.0215520106888125448e-15, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-40.0 + 0.0j))\\n    assert ae(v, (-1.0367732614516569722e-19 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -1.0367732614516569722e-19, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-50.0 + 0.0j))\\n    assert ae(v, (-3.7832640295504590187e-24 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -3.7832640295504590187e-24, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-80.0 + 0.0j))\\n    assert ae(v, (-2.2285432586884729112e-37 + 0.0j), tol=ATOL)\\n    assert ae(v.real, -2.2285432586884729112e-37, tol=PTOL)\\n    assert v.imag == 0\\n    v = fp.ei((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (-20.880034622014215597 - 2.8966139905793444061j), tol=ATOL)\\n    assert ae(v.real, -20.880034622014215597, tol=PTOL)\\n    assert ae(v.imag, -2.8966139905793444061, tol=PTOL)\\n    v = fp.ei((-1.0 - 0.25j))\\n    assert ae(v, (-0.19731063945004229095 - 3.0542266078154932748j), tol=ATOL)\\n    assert ae(v.real, -0.19731063945004229095, tol=PTOL)\\n    assert ae(v.imag, -3.0542266078154932748, tol=PTOL)\\n    v = fp.ei((-4.0 - 1.0j))\\n    assert ae(v, (-0.0013106173980145506944 - 3.1381384055698581758j), tol=ATOL)\\n    assert ae(v.real, -0.0013106173980145506944, tol=PTOL)\\n    assert ae(v.imag, -3.1381384055698581758, tol=PTOL)\\n    v = fp.ei((-8.0 - 2.0j))\\n    assert ae(v, (0.000022278049065270225945 - 3.1415634616493367169j), tol=ATOL)\\n    assert ae(v.real, 0.000022278049065270225945, tol=PTOL)\\n    assert ae(v.imag, -3.1415634616493367169, tol=PTOL)\\n    v = fp.ei((-20.0 - 5.0j))\\n    assert ae(v, (-4.7711374515765346894e-11 - 3.1415926536726958909j), tol=ATOL)\\n    assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL)\\n    assert ae(v.imag, -3.1415926536726958909, tol=PTOL)\\n    v = fp.ei((-80.0 - 20.0j))\\n    assert ae(v, (-3.8353473865788235787e-38 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-120.0 - 30.0j))\\n    assert ae(v, (-2.3836002337480334716e-55 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-160.0 - 40.0j))\\n    assert ae(v, (1.6238022898654510661e-72 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-200.0 - 50.0j))\\n    assert ae(v, (-6.6800061461666228487e-90 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-320.0 - 80.0j))\\n    assert ae(v, (-4.2737871527778786157e-143 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (-21.950067703413105017 - 2.3561944903087602507j), tol=ATOL)\\n    assert ae(v.real, -21.950067703413105017, tol=PTOL)\\n    assert ae(v.imag, -2.3561944903087602507, tol=PTOL)\\n    v = fp.ei((-0.25 - 0.25j))\\n    assert ae(v, (-0.71092525792923287894 - 2.5766745291767512913j), tol=ATOL)\\n    assert ae(v.real, -0.71092525792923287894, tol=PTOL)\\n    assert ae(v.imag, -2.5766745291767512913, tol=PTOL)\\n    v = fp.ei((-1.0 - 1.0j))\\n    assert ae(v, (-0.00028162445198141832551 - 2.9622681185504342983j), tol=ATOL)\\n    assert ae(v.real, -0.00028162445198141832551, tol=PTOL)\\n    assert ae(v.imag, -2.9622681185504342983, tol=PTOL)\\n    v = fp.ei((-2.0 - 2.0j))\\n    assert ae(v, (0.033767089606562004246 - 3.1229932394200426965j), tol=ATOL)\\n    assert ae(v.real, 0.033767089606562004246, tol=PTOL)\\n    assert ae(v.imag, -3.1229932394200426965, tol=PTOL)\\n    v = fp.ei((-5.0 - 5.0j))\\n    assert ae(v, (-0.0007266506660356393891 - 3.1420636813914284609j), tol=ATOL)\\n    assert ae(v.real, -0.0007266506660356393891, tol=PTOL)\\n    assert ae(v.imag, -3.1420636813914284609, tol=PTOL)\\n    v = fp.ei((-20.0 - 20.0j))\\n    assert ae(v, (2.3824537449367396579e-11 - 3.1415926535228233653j), tol=ATOL)\\n    assert ae(v.real, 2.3824537449367396579e-11, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535228233653, tol=PTOL)\\n    v = fp.ei((-30.0 - 30.0j))\\n    assert ae(v, (-1.7316045841744061617e-15 - 3.141592653589794545j), tol=ATOL)\\n    assert ae(v.real, -1.7316045841744061617e-15, tol=PTOL)\\n    assert ae(v.imag, -3.141592653589794545, tol=PTOL)\\n    v = fp.ei((-40.0 - 40.0j))\\n    assert ae(v, (7.4001043002899232182e-20 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 7.4001043002899232182e-20, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-50.0 - 50.0j))\\n    assert ae(v, (-2.3566128324644641219e-24 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -2.3566128324644641219e-24, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-80.0 - 80.0j))\\n    assert ae(v, (-9.8279750572186526673e-38 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -9.8279750572186526673e-38, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j))\\n    assert ae(v, (-20.880034621664969632 - 1.8157749903874220607j), tol=ATOL)\\n    assert ae(v.real, -20.880034621664969632, tol=PTOL)\\n    assert ae(v.imag, -1.8157749903874220607, tol=PTOL)\\n    v = fp.ei((-0.25 - 1.0j))\\n    assert ae(v, (0.16868306393667788761 - 2.6557914649950505414j), tol=ATOL)\\n    assert ae(v.real, 0.16868306393667788761, tol=PTOL)\\n    assert ae(v.imag, -2.6557914649950505414, tol=PTOL)\\n    v = fp.ei((-1.0 - 4.0j))\\n    assert ae(v, (-0.03373591813926547318 - 3.2151161058308770603j), tol=ATOL)\\n    assert ae(v.real, -0.03373591813926547318, tol=PTOL)\\n    assert ae(v.imag, -3.2151161058308770603, tol=PTOL)\\n    v = fp.ei((-2.0 - 8.0j))\\n    assert ae(v, (0.015392833434733785143 - 3.1384179414340326969j), tol=ATOL)\\n    assert ae(v.real, 0.015392833434733785143, tol=PTOL)\\n    assert ae(v.imag, -3.1384179414340326969, tol=PTOL)\\n    v = fp.ei((-5.0 - 20.0j))\\n    assert ae(v, (0.00024419662286542966525 - 3.1413825703601317109j), tol=ATOL)\\n    assert ae(v.real, 0.00024419662286542966525, tol=PTOL)\\n    assert ae(v.imag, -3.1413825703601317109, tol=PTOL)\\n    v = fp.ei((-20.0 - 80.0j))\\n    assert ae(v, (-2.3255552781051330088e-11 - 3.1415926535987396304j), tol=ATOL)\\n    assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535987396304, tol=PTOL)\\n    v = fp.ei((-30.0 - 120.0j))\\n    assert ae(v, (2.7068919097124652332e-16 - 3.1415926535897925337j), tol=ATOL)\\n    assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897925337, tol=PTOL)\\n    v = fp.ei((-40.0 - 160.0j))\\n    assert ae(v, (1.1695597827678024687e-20 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-50.0 - 200.0j))\\n    assert ae(v, (-9.0323746914410162531e-25 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((-80.0 - 320.0j))\\n    assert ae(v, (-3.4819106748728063576e-38 - 3.1415926535897932385j), tol=ATOL)\\n    assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL)\\n    assert ae(v.imag, -3.1415926535897932385, tol=PTOL)\\n    v = fp.ei((0.0 - 1.1641532182693481445e-10j))\\n    assert ae(v, (-22.29664129357666235 - 1.5707963269113119411j), tol=ATOL)\\n    assert ae(v.real, -22.29664129357666235, tol=PTOL)\\n    assert ae(v.imag, -1.5707963269113119411, tol=PTOL)\\n    v = fp.ei((0.0 - 0.25j))\\n    assert ae(v, (-0.82466306258094565309 - 1.8199298971146537833j), tol=ATOL)\\n    assert ae(v.real, -0.82466306258094565309, tol=PTOL)\\n    assert ae(v.imag, -1.8199298971146537833, tol=PTOL)\\n    v = fp.ei((0.0 - 1.0j))\\n    assert ae(v, (0.33740392290096813466 - 2.5168793971620796342j), tol=ATOL)\\n    assert ae(v.real, 0.33740392290096813466, tol=PTOL)\\n    assert ae(v.imag, -2.5168793971620796342, tol=PTOL)\\n    v = fp.ei((0.0 - 2.0j))\\n    assert ae(v, (0.4229808287748649957 - 3.1762093035975914678j), tol=ATOL)\\n    assert ae(v.real, 0.4229808287748649957, tol=PTOL)\\n    assert ae(v.imag, -3.1762093035975914678, tol=PTOL)\\n    v = fp.ei((0.0 - 5.0j))\\n    assert ae(v, (-0.19002974965664387862 - 3.1207275717395707565j), tol=ATOL)\\n    assert ae(v.real, -0.19002974965664387862, tol=PTOL)\\n    assert ae(v.imag, -3.1207275717395707565, tol=PTOL)\\n    v = fp.ei((0.0 - 20.0j))\\n    assert ae(v, (0.04441982084535331654 - 3.1190380278383364594j), tol=ATOL)\\n    assert ae(v.real, 0.04441982084535331654, tol=PTOL)\\n    assert ae(v.imag, -3.1190380278383364594, tol=PTOL)\\n    v = fp.ei((0.0 - 30.0j))\\n    assert ae(v, (-0.033032417282071143779 - 3.1375528668252477302j), tol=ATOL)\\n    assert ae(v.real, -0.033032417282071143779, tol=PTOL)\\n    assert ae(v.imag, -3.1375528668252477302, tol=PTOL)\\n    v = fp.ei((0.0 - 40.0j))\\n    assert ae(v, (0.019020007896208766962 - 3.157781446149681126j), tol=ATOL)\\n    assert ae(v.real, 0.019020007896208766962, tol=PTOL)\\n    assert ae(v.imag, -3.157781446149681126, tol=PTOL)\\n    v = fp.ei((0.0 - 50.0j))\\n    assert ae(v, (-0.0056283863241163054402 - 3.122413399280832514j), tol=ATOL)\\n    assert ae(v.real, -0.0056283863241163054402, tol=PTOL)\\n    assert ae(v.imag, -3.122413399280832514, tol=PTOL)\\n    v = fp.ei((0.0 - 80.0j))\\n    assert ae(v, (-0.012402501155070958192 - 3.1431272137073839346j), tol=ATOL)\\n    assert ae(v.real, -0.012402501155070958192, tol=PTOL)\\n    assert ae(v.imag, -3.1431272137073839346, tol=PTOL)\\n    v = fp.ei((1.1641532182693481445e-10 - 4.6566128730773925781e-10j))\\n    assert ae(v, (-20.880034621432138988 - 1.3258176641336937524j), tol=ATOL)\\n    assert ae(v.real, -20.880034621432138988, tol=PTOL)\\n    assert ae(v.imag, -1.3258176641336937524, tol=PTOL)\\n    v = fp.ei((0.25 - 1.0j))\\n    assert ae(v, (0.59066621214766308594 - 2.3968481059377428687j), tol=ATOL)\\n    assert ae(v.real, 0.59066621214766308594, tol=PTOL)\\n    assert ae(v.imag, -2.3968481059377428687, tol=PTOL)\\n    v = fp.ei((1.0 - 4.0j))\\n    assert ae(v, (-0.49739047283060471093 - 3.5570287076301818702j), tol=ATOL)\\n    assert ae(v.real, -0.49739047283060471093, tol=PTOL)\\n    assert ae(v.imag, -3.5570287076301818702, tol=PTOL)\\n    v = fp.ei((2.0 - 8.0j))\\n    assert ae(v, (0.8705211147733730969 - 3.3825859385758486351j), tol=ATOL)\\n    assert ae(v.real, 0.8705211147733730969, tol=PTOL)\\n    assert ae(v.imag, -3.3825859385758486351, tol=PTOL)\\n    v = fp.ei((5.0 - 20.0j))\\n    assert ae(v, (7.0789514293925893007 - 1.5313749363937141849j), tol=ATOL)\\n    assert ae(v.real, 7.0789514293925893007, tol=PTOL)\\n    assert ae(v.imag, -1.5313749363937141849, tol=PTOL)\\n    v = fp.ei((20.0 - 80.0j))\\n    assert ae(v, (-5855431.4907298084434 + 720917.79156143806727j), tol=ATOL)\\n    assert ae(v.real, -5855431.4907298084434, tol=PTOL)\\n    assert ae(v.imag, 720917.79156143806727, tol=PTOL)\\n    v = fp.ei((30.0 - 120.0j))\\n    assert ae(v, (65402491644.703470747 + 56697658396.51586764j), tol=ATOL)\\n    assert ae(v.real, 65402491644.703470747, tol=PTOL)\\n    assert ae(v.imag, 56697658396.51586764, tol=PTOL)\\n    v = fp.ei((40.0 - 160.0j))\\n    assert ae(v, (-25504929379604.776769 - 1429035198630576.3879j), tol=ATOL)\\n    assert ae(v.real, -25504929379604.776769, tol=PTOL)\\n    assert ae(v.imag, -1429035198630576.3879, tol=PTOL)\\n    v = fp.ei((50.0 - 200.0j))\\n    assert ae(v, (-18437746526988116954.0 + 17146362239046152342.0j), tol=ATOL)\\n    assert ae(v.real, -18437746526988116954.0, tol=PTOL)\\n    assert ae(v.imag, 17146362239046152342.0, tol=PTOL)\\n    v = fp.ei((80.0 - 320.0j))\\n    assert ae(v, (-3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL)\\n    assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL)\\n    assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL)\\n    v = fp.ei((1.1641532182693481445e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (-21.950067703180274374 - 0.78539816351386363145j), tol=ATOL)\\n    assert ae(v.real, -21.950067703180274374, tol=PTOL)\\n    assert ae(v.imag, -0.78539816351386363145, tol=PTOL)\\n    v = fp.ei((0.25 - 0.25j))\\n    assert ae(v, (-0.21441047326710323254 - 1.0683772981589995996j), tol=ATOL)\\n    assert ae(v.real, -0.21441047326710323254, tol=PTOL)\\n    assert ae(v.imag, -1.0683772981589995996, tol=PTOL)\\n    v = fp.ei((1.0 - 1.0j))\\n    assert ae(v, (1.7646259855638540684 - 2.3877698515105224193j), tol=ATOL)\\n    assert ae(v.real, 1.7646259855638540684, tol=PTOL)\\n    assert ae(v.imag, -2.3877698515105224193, tol=PTOL)\\n    v = fp.ei((2.0 - 2.0j))\\n    assert ae(v, (1.8920781621855474089 - 5.3169624378326579621j), tol=ATOL)\\n    assert ae(v.real, 1.8920781621855474089, tol=PTOL)\\n    assert ae(v.imag, -5.3169624378326579621, tol=PTOL)\\n    v = fp.ei((5.0 - 5.0j))\\n    assert ae(v, (-13.470936071475245856 + 15.322492395731230968j), tol=ATOL)\\n    assert ae(v.real, -13.470936071475245856, tol=PTOL)\\n    assert ae(v.imag, 15.322492395731230968, tol=PTOL)\\n    v = fp.ei((20.0 - 20.0j))\\n    assert ae(v, (16589317.398788971896 - 5831705.4712368307104j), tol=ATOL)\\n    assert ae(v.real, 16589317.398788971896, tol=PTOL)\\n    assert ae(v.imag, -5831705.4712368307104, tol=PTOL)\\n    v = fp.ei((30.0 - 30.0j))\\n    assert ae(v, (-154596484273.69322527 + 204179357834.2723043j), tol=ATOL)\\n    assert ae(v.real, -154596484273.69322527, tol=PTOL)\\n    assert ae(v.imag, 204179357834.2723043, tol=PTOL)\\n    v = fp.ei((40.0 - 40.0j))\\n    assert ae(v, (287512180321448.45408 - 4203502407932318.1156j), tol=ATOL)\\n    assert ae(v.real, 287512180321448.45408, tol=PTOL)\\n    assert ae(v.imag, -4203502407932318.1156, tol=PTOL)\\n    v = fp.ei((50.0 - 50.0j))\\n    assert ae(v, (36128528616649268826.0 + 64648801861338741960.0j), tol=ATOL)\\n    assert ae(v.real, 36128528616649268826.0, tol=PTOL)\\n    assert ae(v.imag, 64648801861338741960.0, tol=PTOL)\\n    v = fp.ei((80.0 - 80.0j))\\n    assert ae(v, (-3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL)\\n    assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL)\\n    assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL)\\n    v = fp.ei((4.6566128730773925781e-10 - 1.1641532182693481445e-10j))\\n    assert ae(v, (-20.880034621082893023 - 0.24497866324327947603j), tol=ATOL)\\n    assert ae(v.real, -20.880034621082893023, tol=PTOL)\\n    assert ae(v.imag, -0.24497866324327947603, tol=PTOL)\\n    v = fp.ei((1.0 - 0.25j))\\n    assert ae(v, (1.8942716983721074932 - 0.67268237088273915854j), tol=ATOL)\\n    assert ae(v.real, 1.8942716983721074932, tol=PTOL)\\n    assert ae(v.imag, -0.67268237088273915854, tol=PTOL)\\n    v = fp.ei((4.0 - 1.0j))\\n    assert ae(v, (14.806699492675420438 - 12.280015176673582616j), tol=ATOL)\\n    assert ae(v.real, 14.806699492675420438, tol=PTOL)\\n    assert ae(v.imag, -12.280015176673582616, tol=PTOL)\\n    v = fp.ei((8.0 - 2.0j))\\n    assert ae(v, (-54.633252667426386294 - 416.34477429173650012j), tol=ATOL)\\n    assert ae(v.real, -54.633252667426386294, tol=PTOL)\\n    assert ae(v.imag, -416.34477429173650012, tol=PTOL)\\n    v = fp.ei((20.0 - 5.0j))\\n    assert ae(v, (711836.97165402624643 + 24745247.798103247366j), tol=ATOL)\\n    assert ae(v.real, 711836.97165402624643, tol=PTOL)\\n    assert ae(v.imag, 24745247.798103247366, tol=PTOL)\\n    v = fp.ei((80.0 - 20.0j))\\n    assert ae(v, (4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL)\\n    assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL)\\n    assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL)\\n    v = fp.ei((120.0 - 30.0j))\\n    assert ae(v, (-9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL)\\n    assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL)\\n    assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL)\\n    v = fp.ei((160.0 - 40.0j))\\n    assert ae(v, (-8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL)\\n    assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL)\\n    assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL)\\n    v = fp.ei((200.0 - 50.0j))\\n    assert ae(v, (3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL)\\n    assert ae(v.real, 3.070744996327018106e+84, tol=PTOL)\\n    assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL)\\n    v = fp.ei((320.0 - 80.0j))\\n    assert ae(v, (-9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL)\\n    assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL)\\n    assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL)\\n\\n\\n\\n\\nfrom mpmath import *\\n\\ndef test_special():\\n    assert inf == inf\\n    assert inf != -inf\\n    assert -inf == -inf\\n    assert inf != nan\\n    assert nan != nan\\n    assert isnan(nan)\\n    assert --inf == inf\\n    assert abs(inf) == inf\\n    assert abs(-inf) == inf\\n    assert abs(nan) != abs(nan)\\n\\n    assert isnan(inf - inf)\\n    assert isnan(inf + (-inf))\\n    assert isnan(-inf - (-inf))\\n\\n    assert isnan(inf + nan)\\n    assert isnan(-inf + nan)\\n\\n    assert mpf(2) + inf == inf\\n    assert 2 + inf == inf\\n    assert mpf(2) - inf == -inf\\n    assert 2 - inf == -inf\\n\\n    assert inf > 3\\n    assert 3 < inf\\n    assert 3 > -inf\\n    assert -inf < 3\\n    assert inf > mpf(3)\\n    assert mpf(3) < inf\\n    assert mpf(3) > -inf\\n    assert -inf < mpf(3)\\n\\n    assert not (nan < 3)\\n    assert not (nan > 3)\\n\\n    assert isnan(inf * 0)\\n    assert isnan(-inf * 0)\\n    assert inf * 3 == inf\\n    assert inf * -3 == -inf\\n    assert -inf * 3 == -inf\\n    assert -inf * -3 == inf\\n    assert inf * inf == inf\\n    assert -inf * -inf == inf\\n\\n    assert isnan(nan / 3)\\n    assert inf / -3 == -inf\\n    assert inf / 3 == inf\\n    assert 3 / inf == 0\\n    assert -3 / inf == 0\\n    assert 0 / inf == 0\\n    assert isnan(inf / inf)\\n    assert isnan(inf / -inf)\\n    assert isnan(inf / nan)\\n\\n    assert mpf('inf') == mpf('+inf') == inf\\n    assert mpf('-inf') == -inf\\n    assert isnan(mpf('nan'))\\n\\n    assert isinf(inf)\\n    assert isinf(-inf)\\n    assert not isinf(mpf(0))\\n    assert not isinf(nan)\\n\\ndef test_special_powers():\\n    assert inf**3 == inf\\n    assert isnan(inf**0)\\n    assert inf**-3 == 0\\n    assert (-inf)**2 == inf\\n    assert (-inf)**3 == -inf\\n    assert isnan((-inf)**0)\\n    assert (-inf)**-2 == 0\\n    assert (-inf)**-3 == 0\\n    assert isnan(nan**5)\\n    assert isnan(nan**0)\\n\\ndef test_functions_special():\\n    assert exp(inf) == inf\\n    assert exp(-inf) == 0\\n    assert isnan(exp(nan))\\n    assert log(inf) == inf\\n    assert isnan(log(nan))\\n    assert isnan(sin(inf))\\n    assert isnan(sin(nan))\\n    assert atan(inf).ae(pi/2)\\n    assert atan(-inf).ae(-pi/2)\\n    assert isnan(sqrt(nan))\\n    assert sqrt(inf) == inf\\n\\ndef test_convert_special():\\n    float_inf = 1e300 * 1e300\\n    float_ninf = -float_inf\\n    float_nan = float_inf/float_ninf\\n    assert mpf(3) * float_inf == inf\\n    assert mpf(3) * float_ninf == -inf\\n    assert isnan(mpf(3) * float_nan)\\n    assert not (mpf(3) < float_nan)\\n    assert not (mpf(3) > float_nan)\\n    assert not (mpf(3) <= float_nan)\\n    assert not (mpf(3) >= float_nan)\\n    assert float(mpf('1e1000')) == float_inf\\n    assert float(mpf('-1e1000')) == float_ninf\\n    assert float(mpf('1e100000000000000000')) == float_inf\\n    assert float(mpf('-1e100000000000000000')) == float_ninf\\n    assert float(mpf('1e-100000000000000000')) == 0.0\\n\\ndef test_div_bug():\\n    assert isnan(nan/1)\\n    assert isnan(nan/2)\\n    assert inf/2 == inf\\n    assert (-inf)/2 == -inf\\n\\n\\nfrom mpmath.libmp import *\\nfrom mpmath import mpf, mp\\n\\nfrom random import randint, choice, seed\\n\\nall_modes = [round_floor, round_ceiling, round_down, round_up, round_nearest]\\n\\nfb = from_bstr\\nfi = from_int\\nff = from_float\\n\\n\\ndef test_div_1_3():\\n    a = fi(1)\\n    b = fi(3)\\n    c = fi(-1)\\n\\n    # floor rounds down, ceiling rounds up\\n    assert mpf_div(a, b, 7, round_floor)   == fb('0.01010101')\\n    assert mpf_div(a, b, 7, round_ceiling) == fb('0.01010110')\\n    assert mpf_div(a, b, 7, round_down)    == fb('0.01010101')\\n    assert mpf_div(a, b, 7, round_up)      == fb('0.01010110')\\n    assert mpf_div(a, b, 7, round_nearest) == fb('0.01010101')\\n\\n    # floor rounds up, ceiling rounds down\\n    assert mpf_div(c, b, 7, round_floor)   == fb('-0.01010110')\\n    assert mpf_div(c, b, 7, round_ceiling) == fb('-0.01010101')\\n    assert mpf_div(c, b, 7, round_down)    == fb('-0.01010101')\\n    assert mpf_div(c, b, 7, round_up)      == fb('-0.01010110')\\n    assert mpf_div(c, b, 7, round_nearest) == fb('-0.01010101')\\n\\ndef test_mpf_divi_1_3():\\n    a = 1\\n    b = fi(3)\\n    c = -1\\n    assert mpf_rdiv_int(a, b, 7, round_floor)   == fb('0.01010101')\\n    assert mpf_rdiv_int(a, b, 7, round_ceiling) == fb('0.01010110')\\n    assert mpf_rdiv_int(a, b, 7, round_down)    == fb('0.01010101')\\n    assert mpf_rdiv_int(a, b, 7, round_up)      == fb('0.01010110')\\n    assert mpf_rdiv_int(a, b, 7, round_nearest) == fb('0.01010101')\\n    assert mpf_rdiv_int(c, b, 7, round_floor)   == fb('-0.01010110')\\n    assert mpf_rdiv_int(c, b, 7, round_ceiling) == fb('-0.01010101')\\n    assert mpf_rdiv_int(c, b, 7, round_down)    == fb('-0.01010101')\\n    assert mpf_rdiv_int(c, b, 7, round_up)      == fb('-0.01010110')\\n    assert mpf_rdiv_int(c, b, 7, round_nearest) == fb('-0.01010101')\\n\\n\\ndef test_div_300():\\n\\n    q = fi(1000000)\\n    a = fi(300499999)    # a/q is a little less than a half-integer\\n    b = fi(300500000)    # b/q exactly a half-integer\\n    c = fi(300500001)    # c/q is a little more than a half-integer\\n\\n    # Check nearest integer rounding (prec=9 as 2**8 < 300 < 2**9)\\n\\n    assert mpf_div(a, q, 9, round_down) == fi(300)\\n    assert mpf_div(b, q, 9, round_down) == fi(300)\\n    assert mpf_div(c, q, 9, round_down) == fi(300)\\n    assert mpf_div(a, q, 9, round_up) == fi(301)\\n    assert mpf_div(b, q, 9, round_up) == fi(301)\\n    assert mpf_div(c, q, 9, round_up) == fi(301)\\n\\n    # Nearest even integer is down\\n    assert mpf_div(a, q, 9, round_nearest) == fi(300)\\n    assert mpf_div(b, q, 9, round_nearest) == fi(300)\\n    assert mpf_div(c, q, 9, round_nearest) == fi(301)\\n\\n    # Nearest even integer is up\\n    a = fi(301499999)\\n    b = fi(301500000)\\n    c = fi(301500001)\\n    assert mpf_div(a, q, 9, round_nearest) == fi(301)\\n    assert mpf_div(b, q, 9, round_nearest) == fi(302)\\n    assert mpf_div(c, q, 9, round_nearest) == fi(302)\\n\\n\\ndef test_tight_integer_division():\\n    # Test that integer division at tightest possible precision is exact\\n    N = 100\\n    seed(1)\\n    for i in range(N):\\n        a = choice([1, -1]) * randint(1, 1<<randint(10, 100))\\n        b = choice([1, -1]) * randint(1, 1<<randint(10, 100))\\n        p = a * b\\n        width = bitcount(abs(b)) - trailing(b)\\n        a = fi(a); b = fi(b); p = fi(p)\\n        for mode in all_modes:\\n            assert mpf_div(p, a, width, mode) == b\\n\\n\\ndef test_epsilon_rounding():\\n    # Verify that mpf_div uses infinite precision; this result will\\n    # appear to be exactly 0.101 to a near-sighted algorithm\\n\\n    a = fb('0.101' + ('0'*200) + '1')\\n    b = fb('1.10101')\\n    c = mpf_mul(a, b, 250, round_floor) # exact\\n    assert mpf_div(c, b, bitcount(a[1]), round_floor) == a # exact\\n\\n    assert mpf_div(c, b, 2, round_down) == fb('0.10')\\n    assert mpf_div(c, b, 3, round_down) == fb('0.101')\\n    assert mpf_div(c, b, 2, round_up) == fb('0.11')\\n    assert mpf_div(c, b, 3, round_up) == fb('0.110')\\n    assert mpf_div(c, b, 2, round_floor) == fb('0.10')\\n    assert mpf_div(c, b, 3, round_floor) == fb('0.101')\\n    assert mpf_div(c, b, 2, round_ceiling) == fb('0.11')\\n    assert mpf_div(c, b, 3, round_ceiling) == fb('0.110')\\n\\n    # The same for negative numbers\\n    a = fb('-0.101' + ('0'*200) + '1')\\n    b = fb('1.10101')\\n    c = mpf_mul(a, b, 250, round_floor)\\n    assert mpf_div(c, b, bitcount(a[1]), round_floor) == a\\n\\n    assert mpf_div(c, b, 2, round_down) == fb('-0.10')\\n    assert mpf_div(c, b, 3, round_up) == fb('-0.110')\\n\\n    # Floor goes up, ceiling goes down\\n    assert mpf_div(c, b, 2, round_floor) == fb('-0.11')\\n    assert mpf_div(c, b, 3, round_floor) == fb('-0.110')\\n    assert mpf_div(c, b, 2, round_ceiling) == fb('-0.10')\\n    assert mpf_div(c, b, 3, round_ceiling) == fb('-0.101')\\n\\n\\ndef test_mod():\\n    mp.dps = 15\\n    assert mpf(234) % 1 == 0\\n    assert mpf(-3) % 256 == 253\\n    assert mpf(0.25) % 23490.5 == 0.25\\n    assert mpf(0.25) % -23490.5 == -23490.25\\n    assert mpf(-0.25) % 23490.5 == 23490.25\\n    assert mpf(-0.25) % -23490.5 == -0.25\\n    # Check that these cases are handled efficiently\\n    assert mpf('1e10000000000') % 1 == 0\\n    assert mpf('1.23e-1000000000') % 1 == mpf('1.23e-1000000000')\\n    # test __rmod__\\n    assert 3 % mpf('1.75') == 1.25\\n\\ndef test_div_negative_rnd_bug():\\n    mp.dps = 15\\n    assert (-3) / mpf('0.1531879017645047') == mpf('-19.583791966887116')\\n    assert mpf('-2.6342475750861301') / mpf('0.35126216427941814') == mpf('-7.4993775104985909')\\n\\n\\n#!/usr/bin/env python\\n\\n\\\"\\\"\\\"\\npython runtests.py -py\\n  Use py.test to run tests (more useful for debugging)\\n\\npython runtests.py -coverage\\n  Generate test coverage report. Statistics are written to /tmp\\n\\npython runtests.py -profile\\n  Generate profile stats (this is much slower)\\n\\npython runtests.py -nogmpy\\n  Run tests without using GMPY even if it exists\\n\\npython runtests.py -strict\\n  Enforce extra tests in normalize()\\n\\npython runtests.py -local\\n  Insert '../..' at the beginning of sys.path to use local mpmath\\n\\npython runtests.py -skip ...\\n  Skip tests from the listed modules\\n\\nAdditional arguments are used to filter the tests to run. Only files that have\\none of the arguments in their name are executed.\\n\\n\\\"\\\"\\\"\\n\\nimport sys, os, traceback\\n\\nprofile = False\\nif \\\"-profile\\\" in sys.argv:\\n    sys.argv.remove('-profile')\\n    profile = True\\n\\ncoverage = False\\nif \\\"-coverage\\\" in sys.argv:\\n    sys.argv.remove('-coverage')\\n    coverage = True\\n\\nif \\\"-nogmpy\\\" in sys.argv:\\n    sys.argv.remove('-nogmpy')\\n    os.environ['MPMATH_NOGMPY'] = 'Y'\\n\\nif \\\"-strict\\\" in sys.argv:\\n    sys.argv.remove('-strict')\\n    os.environ['MPMATH_STRICT'] = 'Y'\\n\\nif \\\"-local\\\" in sys.argv:\\n    sys.argv.remove('-local')\\n    importdir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),\\n                                             '../..'))\\nelse:\\n    importdir = ''\\n\\n# TODO: add a flag for this\\ntestdir = ''\\n\\ndef testit(importdir='', testdir='', exit_on_fail=False):\\n    \\\"\\\"\\\"Run all tests in testdir while importing from importdir.\\\"\\\"\\\"\\n    if importdir:\\n        sys.path.insert(1, importdir)\\n    if testdir:\\n        sys.path.insert(1, testdir)\\n    import os.path\\n    import mpmath\\n    print(\\\"mpmath imported from %s\\\" % os.path.dirname(mpmath.__file__))\\n    print(\\\"mpmath backend: %s\\\" % mpmath.libmp.backend.BACKEND)\\n    print(\\\"mpmath mp class: %s\\\" % repr(mpmath.mp))\\n    print(\\\"mpmath version: %s\\\" % mpmath.__version__)\\n    print(\\\"Python version: %s\\\" % sys.version)\\n    print(\\\"\\\")\\n    if \\\"-py\\\" in sys.argv:\\n        sys.argv.remove('-py')\\n        import py\\n        py.test.cmdline.main()\\n    else:\\n        import glob\\n        from timeit import default_timer as clock\\n        modules = []\\n        args = sys.argv[1:]\\n        excluded = []\\n        if '-skip' in args:\\n            excluded = args[args.index('-skip')+1:]\\n            args = args[:args.index('-skip')]\\n        # search for tests in directory of this file if not otherwise specified\\n        if not testdir:\\n            pattern = os.path.dirname(sys.argv[0])\\n        else:\\n            pattern = testdir\\n        if pattern:\\n            pattern += '/'\\n        pattern += 'test*.py'\\n        # look for tests (respecting specified filter)\\n        for f in glob.glob(pattern):\\n            name = os.path.splitext(os.path.basename(f))[0]\\n            # If run as a script, only run tests given as args, if any are given\\n            if args and __name__ == \\\"__main__\\\":\\n                ok = False\\n                for arg in args:\\n                    if arg in name:\\n                        ok = True\\n                        break\\n                if not ok:\\n                    continue\\n            elif name in excluded:\\n                continue\\n            module = __import__(name)\\n            priority = module.__dict__.get('priority', 100)\\n            if priority == 666:\\n                modules = [[priority, name, module]]\\n                break\\n            modules.append([priority, name, module])\\n        # execute tests\\n        modules.sort()\\n        tstart = clock()\\n        for priority, name, module in modules:\\n            print(name)\\n            for f in sorted(module.__dict__.keys()):\\n                if f.startswith('test_'):\\n                    if coverage and ('numpy' in f):\\n                        continue\\n                    sys.stdout.write(\\\"    \\\" + f[5:].ljust(25) + \\\" \\\")\\n                    t1 = clock()\\n                    try:\\n                        module.__dict__[f]()\\n                    except:\\n                        etype, evalue, trb = sys.exc_info()\\n                        if etype in (KeyboardInterrupt, SystemExit):\\n                            raise\\n                        print(\\\"\\\")\\n                        print(\\\"TEST FAILED!\\\")\\n                        print(\\\"\\\")\\n                        traceback.print_exc()\\n                        if exit_on_fail:\\n                            return\\n                    t2 = clock()\\n                    print(\\\"ok \\\" + \\\"       \\\" + (\\\"%.7f\\\" % (t2-t1)) + \\\" s\\\")\\n        tend = clock()\\n        print(\\\"\\\")\\n        print(\\\"finished tests in \\\" + (\\\"%.2f\\\" % (tend-tstart)) + \\\" seconds\\\")\\n        # clean sys.path\\n        if importdir:\\n            sys.path.remove(importdir)\\n        if testdir:\\n            sys.path.remove(testdir)\\n\\nif __name__ == '__main__':\\n    if profile:\\n        import cProfile\\n        cProfile.run(\\\"testit('%s', '%s')\\\" % (importdir, testdir), sort=1)\\n    elif coverage:\\n        import trace\\n        tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix],\\n            trace=0, count=1)\\n        tracer.run('testit(importdir, testdir)')\\n        r = tracer.results()\\n        r.write_results(show_missing=True, summary=True, coverdir=\\\"/tmp\\\")\\n    else:\\n        testit(importdir, testdir)\\n\\n\\n\\\"\\\"\\\"\\nTorture tests for asymptotics and high precision evaluation of\\nspecial functions.\\n\\n(Other torture tests may also be placed here.)\\n\\nRunning this file (gmpy recommended!) takes several CPU minutes.\\nWith Python 2.6+, multiprocessing is used automatically to run tests\\nin parallel if many cores are available. (A single test may take between\\na second and several minutes; possibly more.)\\n\\nThe idea:\\n\\n* We evaluate functions at positive, negative, imaginary, 45- and 135-degree\\n  complex values with magnitudes between 10^-20 to 10^20, at precisions between\\n  5 and 150 digits (we can go even higher for fast functions).\\n\\n* Comparing the result from two different precision levels provides\\n  a strong consistency check (particularly for functions that use\\n  different algorithms at different precision levels).\\n\\n* That the computation finishes at all (without failure), within reasonable\\n  time, provides a check that evaluation works at all: that the code runs,\\n  that it doesn't get stuck in an infinite loop, and that it doesn't use\\n  some extremely slowly algorithm where it could use a faster one.\\n\\nTODO:\\n\\n* Speed up those functions that take long to finish!\\n* Generalize to test more cases; more options.\\n* Implement a timeout mechanism.\\n* Some functions are notably absent, including the following:\\n  * inverse trigonometric functions (some become inaccurate for complex arguments)\\n  * ci, si (not implemented properly for large complex arguments)\\n  * zeta functions (need to modify test not to try too large imaginary values)\\n  * and others...\\n\\n\\\"\\\"\\\"\\n\\n\\nimport sys, os\\nfrom timeit import default_timer as clock\\n\\nif \\\"-nogmpy\\\" in sys.argv:\\n    sys.argv.remove('-nogmpy')\\n    os.environ['MPMATH_NOGMPY'] = 'Y'\\n\\nfilt = ''\\nif not sys.argv[-1].endswith(\\\".py\\\"):\\n    filt = sys.argv[-1]\\n\\nfrom mpmath import *\\nfrom mpmath.libmp.backend import exec_\\n\\ndef test_asymp(f, maxdps=150, verbose=False, huge_range=False):\\n    dps = [5,15,25,50,90,150,500,1500,5000,10000]\\n    dps = [p for p in dps if p <= maxdps]\\n    def check(x,y,p,inpt):\\n        if abs(x-y)/abs(y) < workprec(20)(power)(10, -p+1):\\n            return\\n        print()\\n        print(\\\"Error!\\\")\\n        print(\\\"Input:\\\", inpt)\\n        print(\\\"dps =\\\", p)\\n        print(\\\"Result 1:\\\", x)\\n        print(\\\"Result 2:\\\", y)\\n        print(\\\"Absolute error:\\\", abs(x-y))\\n        print(\\\"Relative error:\\\", abs(x-y)/abs(y))\\n        raise AssertionError\\n    exponents = range(-20,20)\\n    if huge_range:\\n        exponents += [-1000, -100, -50, 50, 100, 1000]\\n    for n in exponents:\\n        if verbose:\\n            sys.stdout.write(\\\". \\\")\\n        mp.dps = 25\\n        xpos = mpf(10)**n / 1.1287\\n        xneg = -xpos\\n        ximag = xpos*j\\n        xcomplex1 = xpos*(1+j)\\n        xcomplex2 = xpos*(-1+j)\\n        for i in range(len(dps)):\\n            if verbose:\\n                print(\\\"Testing dps = %s\\\" % dps[i])\\n            mp.dps = dps[i]\\n            new = f(xpos), f(xneg), f(ximag), f(xcomplex1), f(xcomplex2)\\n            if i != 0:\\n                p = dps[i-1]\\n                check(prev[0], new[0], p, xpos)\\n                check(prev[1], new[1], p, xneg)\\n                check(prev[2], new[2], p, ximag)\\n                check(prev[3], new[3], p, xcomplex1)\\n                check(prev[4], new[4], p, xcomplex2)\\n            prev = new\\n    if verbose:\\n        print()\\n\\na1, a2, a3, a4, a5 = 1.5, -2.25, 3.125, 4, 2\\n\\ndef test_bernoulli_huge():\\n    p, q = bernfrac(9000)\\n    assert p % 10**10 == 9636701091\\n    assert q == 4091851784687571609141381951327092757255270\\n    mp.dps = 15\\n    assert str(bernoulli(10**100)) == '-2.58183325604736e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623'\\n    mp.dps = 50\\n    assert str(bernoulli(10**100)) == '-2.5818332560473632073252488656039475548106223822913e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623'\\n    mp.dps = 15\\n\\ncases = \\\"\\\"\\\"\\\\\\ntest_bernoulli_huge()\\ntest_asymp(lambda z: +pi, maxdps=10000)\\ntest_asymp(lambda z: +e, maxdps=10000)\\ntest_asymp(lambda z: +ln2, maxdps=10000)\\ntest_asymp(lambda z: +ln10, maxdps=10000)\\ntest_asymp(lambda z: +phi, maxdps=10000)\\ntest_asymp(lambda z: +catalan, maxdps=5000)\\ntest_asymp(lambda z: +euler, maxdps=5000)\\ntest_asymp(lambda z: +glaisher, maxdps=1000)\\ntest_asymp(lambda z: +khinchin, maxdps=1000)\\ntest_asymp(lambda z: +twinprime, maxdps=150)\\ntest_asymp(lambda z: stieltjes(2), maxdps=150)\\ntest_asymp(lambda z: +mertens, maxdps=150)\\ntest_asymp(lambda z: +apery, maxdps=5000)\\ntest_asymp(sqrt, maxdps=10000, huge_range=True)\\ntest_asymp(cbrt, maxdps=5000, huge_range=True)\\ntest_asymp(lambda z: root(z,4), maxdps=5000, huge_range=True)\\ntest_asymp(lambda z: root(z,-5), maxdps=5000, huge_range=True)\\ntest_asymp(exp, maxdps=5000, huge_range=True)\\ntest_asymp(expm1, maxdps=1500)\\ntest_asymp(ln, maxdps=5000, huge_range=True)\\ntest_asymp(cosh, maxdps=5000)\\ntest_asymp(sinh, maxdps=5000)\\ntest_asymp(tanh, maxdps=1500)\\ntest_asymp(sin, maxdps=5000, huge_range=True)\\ntest_asymp(cos, maxdps=5000, huge_range=True)\\ntest_asymp(tan, maxdps=1500)\\ntest_asymp(agm, maxdps=1500, huge_range=True)\\ntest_asymp(ellipk, maxdps=1500)\\ntest_asymp(ellipe, maxdps=1500)\\ntest_asymp(lambertw, huge_range=True)\\ntest_asymp(lambda z: lambertw(z,-1))\\ntest_asymp(lambda z: lambertw(z,1))\\ntest_asymp(lambda z: lambertw(z,4))\\ntest_asymp(gamma)\\ntest_asymp(loggamma)  # huge_range=True ?\\ntest_asymp(ei)\\ntest_asymp(e1)\\ntest_asymp(li, huge_range=True)\\ntest_asymp(ci)\\ntest_asymp(si)\\ntest_asymp(chi)\\ntest_asymp(shi)\\ntest_asymp(erf)\\ntest_asymp(erfc)\\ntest_asymp(erfi)\\ntest_asymp(lambda z: besselj(2, z))\\ntest_asymp(lambda z: bessely(2, z))\\ntest_asymp(lambda z: besseli(2, z))\\ntest_asymp(lambda z: besselk(2, z))\\ntest_asymp(lambda z: besselj(-2.25, z))\\ntest_asymp(lambda z: bessely(-2.25, z))\\ntest_asymp(lambda z: besseli(-2.25, z))\\ntest_asymp(lambda z: besselk(-2.25, z))\\ntest_asymp(airyai)\\ntest_asymp(airybi)\\ntest_asymp(lambda z: hyp0f1(a1, z))\\ntest_asymp(lambda z: hyp1f1(a1, a2, z))\\ntest_asymp(lambda z: hyp1f2(a1, a2, a3, z))\\ntest_asymp(lambda z: hyp2f0(a1, a2, z))\\ntest_asymp(lambda z: hyperu(a1, a2, z))\\ntest_asymp(lambda z: hyp2f1(a1, a2, a3, z))\\ntest_asymp(lambda z: hyp2f2(a1, a2, a3, a4, z))\\ntest_asymp(lambda z: hyp2f3(a1, a2, a3, a4, a5, z))\\ntest_asymp(lambda z: coulombf(a1, a2, z))\\ntest_asymp(lambda z: coulombg(a1, a2, z))\\ntest_asymp(lambda z: polylog(2,z))\\ntest_asymp(lambda z: polylog(3,z))\\ntest_asymp(lambda z: polylog(-2,z))\\ntest_asymp(lambda z: expint(4, z))\\ntest_asymp(lambda z: expint(-4, z))\\ntest_asymp(lambda z: expint(2.25, z))\\ntest_asymp(lambda z: gammainc(2.5, z, 5))\\ntest_asymp(lambda z: gammainc(2.5, 5, z))\\ntest_asymp(lambda z: hermite(3, z))\\ntest_asymp(lambda z: hermite(2.5, z))\\ntest_asymp(lambda z: legendre(3, z))\\ntest_asymp(lambda z: legendre(4, z))\\ntest_asymp(lambda z: legendre(2.5, z))\\ntest_asymp(lambda z: legenp(a1, a2, z))\\ntest_asymp(lambda z: legenq(a1, a2, z), maxdps=90)   # abnormally slow\\ntest_asymp(lambda z: jtheta(1, z, 0.5))\\ntest_asymp(lambda z: jtheta(2, z, 0.5))\\ntest_asymp(lambda z: jtheta(3, z, 0.5))\\ntest_asymp(lambda z: jtheta(4, z, 0.5))\\ntest_asymp(lambda z: jtheta(1, z, 0.5, 1))\\ntest_asymp(lambda z: jtheta(2, z, 0.5, 1))\\ntest_asymp(lambda z: jtheta(3, z, 0.5, 1))\\ntest_asymp(lambda z: jtheta(4, z, 0.5, 1))\\ntest_asymp(barnesg, maxdps=90)\\n\\\"\\\"\\\"\\n\\ndef testit(line):\\n    if filt in line:\\n        print(line)\\n        t1 = clock()\\n        exec_(line, globals(), locals())\\n        t2 = clock()\\n        elapsed = t2-t1\\n        print(\\\"Time:\\\", elapsed, \\\"for\\\", line, \\\"(OK)\\\")\\n\\nif __name__ == '__main__':\\n    try:\\n        from multiprocessing import Pool\\n        mapf = Pool(None).map\\n        print(\\\"Running tests with multiprocessing\\\")\\n    except ImportError:\\n        print(\\\"Not using multiprocessing\\\")\\n        mapf = map\\n    t1 = clock()\\n    tasks = cases.splitlines()\\n    mapf(testit, tasks)\\n    t2 = clock()\\n    print(\\\"Cumulative wall time:\\\", t2-t1)\\n\\n\\n\\\"\\\"\\\"\\nThe function zetazero(n) computes the n-th nontrivial zero of zeta(s).\\n\\nThe general strategy is to locate a block of Gram intervals B where we\\nknow exactly the number of zeros contained and which of those zeros\\nis that which we search.\\n\\nIf n <= 400 000 000  we know exactly the Rosser exceptions, contained\\nin a list in this file. Hence for n<=400 000 000 we simply\\nlook at these list of exceptions. If our zero is implicated in one of\\nthese exceptions we have our block B.  In other case we simply locate\\nthe good Rosser block containing our zero.\\n\\nFor n > 400 000 000 we apply the method of Turing, as complemented by\\nLehman, Brent and Trudgian  to find a suitable B.\\n\\\"\\\"\\\"\\n\\nfrom .functions import defun, defun_wrapped\\n\\ndef find_rosser_block_zero(ctx, n):\\n    \\\"\\\"\\\"for n<400 000 000 determines a block were one find our zero\\\"\\\"\\\"\\n    for k in range(len(_ROSSER_EXCEPTIONS)//2):\\n        a=_ROSSER_EXCEPTIONS[2*k][0]\\n        b=_ROSSER_EXCEPTIONS[2*k][1]\\n        if ((a<= n-2) and (n-1 <= b)):\\n            t0 = ctx.grampoint(a)\\n            t1 = ctx.grampoint(b)\\n            v0 = ctx._fp.siegelz(t0)\\n            v1 = ctx._fp.siegelz(t1)\\n            my_zero_number = n-a-1\\n            zero_number_block = b-a\\n            pattern = _ROSSER_EXCEPTIONS[2*k+1]\\n            return (my_zero_number, [a,b], [t0,t1], [v0,v1])\\n    k = n-2\\n    t,v,b = compute_triple_tvb(ctx, k)\\n    T = [t]\\n    V = [v]\\n    while b < 0:\\n        k -= 1\\n        t,v,b = compute_triple_tvb(ctx, k)\\n        T.insert(0,t)\\n        V.insert(0,v)\\n    my_zero_number = n-k-1\\n    m = n-1\\n    t,v,b = compute_triple_tvb(ctx, m)\\n    T.append(t)\\n    V.append(v)\\n    while b < 0:\\n        m += 1\\n        t,v,b = compute_triple_tvb(ctx, m)\\n        T.append(t)\\n        V.append(v)\\n    return (my_zero_number, [k,m], T, V)\\n\\ndef wpzeros(t):\\n    \\\"\\\"\\\"Precision needed to compute higher zeros\\\"\\\"\\\"\\n    wp = 53\\n    if t > 3*10**8:\\n        wp = 63\\n    if t > 10**11:\\n        wp = 70\\n    if t > 10**14:\\n        wp = 83\\n    return wp\\n\\ndef separate_zeros_in_block(ctx, zero_number_block, T, V, limitloop=None,\\n    fp_tolerance=None):\\n    \\\"\\\"\\\"Separate the zeros contained in the block T, limitloop\\n    determines how long one must search\\\"\\\"\\\"\\n    if limitloop is None:\\n        limitloop = ctx.inf\\n    loopnumber = 0\\n    variations = count_variations(V)\\n    while ((variations < zero_number_block) and (loopnumber <limitloop)):\\n        a = T[0]\\n        v = V[0]\\n        newT = [a]\\n        newV = [v]\\n        variations = 0\\n        for n in range(1,len(T)):\\n            b2 = T[n]\\n            u = V[n]\\n            if (u*v>0):\\n                alpha = ctx.sqrt(u/v)\\n                b= (alpha*a+b2)/(alpha+1)\\n            else:\\n                b = (a+b2)/2\\n            if fp_tolerance < 10:\\n                w = ctx._fp.siegelz(b)\\n                if abs(w)<fp_tolerance:\\n                    w = ctx.siegelz(b)\\n            else:\\n                w=ctx.siegelz(b)\\n            if v*w<0:\\n                variations += 1\\n            newT.append(b)\\n            newV.append(w)\\n            u = V[n]\\n            if u*w <0:\\n                variations += 1\\n            newT.append(b2)\\n            newV.append(u)\\n            a = b2\\n            v = u\\n        T = newT\\n        V = newV\\n        loopnumber +=1\\n        if (limitloop>ITERATION_LIMIT)and(loopnumber>2)and(variations+2==zero_number_block):\\n            dtMax=0\\n            dtSec=0\\n            kMax = 0\\n            for k1 in range(1,len(T)):\\n                dt = T[k1]-T[k1-1]\\n                if dt > dtMax:\\n                    kMax=k1\\n                    dtSec = dtMax\\n                    dtMax = dt\\n                elif  (dt<dtMax) and(dt >dtSec):\\n                    dtSec = dt\\n            if dtMax>3*dtSec:\\n                f = lambda x: ctx.rs_z(x,derivative=1)\\n                t0=T[kMax-1]\\n                t1 = T[kMax]\\n                t=ctx.findroot(f,  (t0,t1), solver ='illinois',verify=False, verbose=False)\\n                v = ctx.siegelz(t)\\n                if (t0<t) and (t<t1) and (v*V[kMax]<0):\\n                    T.insert(kMax,t)\\n                    V.insert(kMax,v)\\n        variations = count_variations(V)\\n    if variations == zero_number_block:\\n        separated = True\\n    else:\\n        separated = False\\n    return (T,V, separated)\\n\\ndef separate_my_zero(ctx, my_zero_number, zero_number_block, T, V, prec):\\n    \\\"\\\"\\\"If we know which zero of this block is mine,\\n    the function separates the zero\\\"\\\"\\\"\\n    variations = 0\\n    v0 = V[0]\\n    for k in range(1,len(V)):\\n        v1 = V[k]\\n        if v0*v1 < 0:\\n            variations +=1\\n            if variations == my_zero_number:\\n                k0 = k\\n                leftv = v0\\n                rightv = v1\\n        v0 = v1\\n    t1 = T[k0]\\n    t0 = T[k0-1]\\n    ctx.prec = prec\\n    wpz = wpzeros(my_zero_number*ctx.log(my_zero_number))\\n\\n    guard = 4*ctx.mag(my_zero_number)\\n    precs = [ctx.prec+4]\\n    index=0\\n    while precs[0] > 2*wpz:\\n        index +=1\\n        precs = [precs[0] // 2 +3+2*index] + precs\\n    ctx.prec = precs[0] + guard\\n    r = ctx.findroot(lambda x:ctx.siegelz(x), (t0,t1), solver ='illinois', verbose=False)\\n    #print \\\"first step at\\\", ctx.dps, \\\"digits\\\"\\n    z=ctx.mpc(0.5,r)\\n    for prec in precs[1:]:\\n        ctx.prec = prec + guard\\n        #print \\\"refining to\\\", ctx.dps, \\\"digits\\\"\\n        znew = z - ctx.zeta(z) / ctx.zeta(z, derivative=1)\\n        #print \\\"difference\\\", ctx.nstr(abs(z-znew))\\n        z=ctx.mpc(0.5,ctx.im(znew))\\n    return ctx.im(z)\\n\\ndef sure_number_block(ctx, n):\\n    \\\"\\\"\\\"The number of good Rosser blocks needed to apply\\n    Turing method\\n    References:\\n    R. P. Brent, On the Zeros of the Riemann Zeta Function\\n    in the Critical Strip, Math. Comp. 33 (1979) 1361--1372\\n    T. Trudgian, Improvements to Turing Method, Math. Comp.\\\"\\\"\\\"\\n    if n < 9*10**5:\\n        return(2)\\n    g = ctx.grampoint(n-100)\\n    lg = ctx._fp.ln(g)\\n    brent = 0.0061 * lg**2 +0.08*lg\\n    trudgian = 0.0031 * lg**2 +0.11*lg\\n    N = ctx.ceil(min(brent,trudgian))\\n    N = int(N)\\n    return N\\n\\ndef compute_triple_tvb(ctx, n):\\n    t = ctx.grampoint(n)\\n    v = ctx._fp.siegelz(t)\\n    if ctx.mag(abs(v))<ctx.mag(t)-45:\\n        v = ctx.siegelz(t)\\n    b = v*(-1)**n\\n    return t,v,b\\n\\n\\n\\nITERATION_LIMIT = 4\\n\\ndef search_supergood_block(ctx, n, fp_tolerance):\\n    \\\"\\\"\\\"To use for n>400 000 000\\\"\\\"\\\"\\n    sb = sure_number_block(ctx, n)\\n    number_goodblocks = 0\\n    m2 = n-1\\n    t, v, b = compute_triple_tvb(ctx, m2)\\n    Tf = [t]\\n    Vf = [v]\\n    while b < 0:\\n        m2 += 1\\n        t,v,b = compute_triple_tvb(ctx, m2)\\n        Tf.append(t)\\n        Vf.append(v)\\n    goodpoints = [m2]\\n    T = [t]\\n    V = [v]\\n    while number_goodblocks < 2*sb:\\n        m2 += 1\\n        t, v, b = compute_triple_tvb(ctx, m2)\\n        T.append(t)\\n        V.append(v)\\n        while b < 0:\\n            m2 += 1\\n            t,v,b = compute_triple_tvb(ctx, m2)\\n            T.append(t)\\n            V.append(v)\\n        goodpoints.append(m2)\\n        zn = len(T)-1\\n        A, B, separated =\\\\\\n           separate_zeros_in_block(ctx, zn, T, V, limitloop=ITERATION_LIMIT,\\n                fp_tolerance=fp_tolerance)\\n        Tf.pop()\\n        Tf.extend(A)\\n        Vf.pop()\\n        Vf.extend(B)\\n        if separated:\\n            number_goodblocks += 1\\n        else:\\n            number_goodblocks = 0\\n        T = [t]\\n        V = [v]\\n    # Now the same procedure to the left\\n    number_goodblocks = 0\\n    m2 = n-2\\n    t, v, b = compute_triple_tvb(ctx, m2)\\n    Tf.insert(0,t)\\n    Vf.insert(0,v)\\n    while b < 0:\\n        m2 -= 1\\n        t,v,b = compute_triple_tvb(ctx, m2)\\n        Tf.insert(0,t)\\n        Vf.insert(0,v)\\n    goodpoints.insert(0,m2)\\n    T = [t]\\n    V = [v]\\n    while number_goodblocks < 2*sb:\\n        m2 -= 1\\n        t, v, b = compute_triple_tvb(ctx, m2)\\n        T.insert(0,t)\\n        V.insert(0,v)\\n        while b < 0:\\n            m2 -= 1\\n            t,v,b = compute_triple_tvb(ctx, m2)\\n            T.insert(0,t)\\n            V.insert(0,v)\\n        goodpoints.insert(0,m2)\\n        zn = len(T)-1\\n        A, B, separated =\\\\\\n           separate_zeros_in_block(ctx, zn, T, V, limitloop=ITERATION_LIMIT, fp_tolerance=fp_tolerance)\\n        A.pop()\\n        Tf = A+Tf\\n        B.pop()\\n        Vf = B+Vf\\n        if separated:\\n            number_goodblocks += 1\\n        else:\\n            number_goodblocks = 0\\n        T = [t]\\n        V = [v]\\n    r = goodpoints[2*sb]\\n    lg = len(goodpoints)\\n    s = goodpoints[lg-2*sb-1]\\n    tr, vr, br = compute_triple_tvb(ctx, r)\\n    ar = Tf.index(tr)\\n    ts, vs, bs = compute_triple_tvb(ctx, s)\\n    as1 = Tf.index(ts)\\n    T = Tf[ar:as1+1]\\n    V = Vf[ar:as1+1]\\n    zn = s-r\\n    A, B, separated =\\\\\\n       separate_zeros_in_block(ctx, zn,T,V,limitloop=ITERATION_LIMIT, fp_tolerance=fp_tolerance)\\n    if separated:\\n        return (n-r-1,[r,s],A,B)\\n    q = goodpoints[sb]\\n    lg = len(goodpoints)\\n    t = goodpoints[lg-sb-1]\\n    tq, vq, bq = compute_triple_tvb(ctx, q)\\n    aq = Tf.index(tq)\\n    tt, vt, bt = compute_triple_tvb(ctx, t)\\n    at = Tf.index(tt)\\n    T = Tf[aq:at+1]\\n    V = Vf[aq:at+1]\\n    return (n-q-1,[q,t],T,V)\\n\\ndef count_variations(V):\\n    count = 0\\n    vold = V[0]\\n    for n in range(1, len(V)):\\n        vnew = V[n]\\n        if vold*vnew < 0:\\n            count +=1\\n        vold = vnew\\n    return count\\n\\ndef pattern_construct(ctx, block, T, V):\\n    pattern = '('\\n    a = block[0]\\n    b = block[1]\\n    t0,v0,b0 = compute_triple_tvb(ctx, a)\\n    k = 0\\n    k0 = 0\\n    for n in range(a+1,b+1):\\n        t1,v1,b1 = compute_triple_tvb(ctx, n)\\n        lgT =len(T)\\n        while (k < lgT) and (T[k] <= t1):\\n            k += 1\\n        L = V[k0:k]\\n        L.append(v1)\\n        L.insert(0,v0)\\n        count = count_variations(L)\\n        pattern = pattern + (\\\"%s\\\" % count)\\n        if b1 > 0:\\n            pattern = pattern + ')('\\n        k0 = k\\n        t0,v0,b0 = t1,v1,b1\\n    pattern = pattern[:-1]\\n    return pattern\\n\\n@defun\\ndef zetazero(ctx, n, info=False, round=True):\\n    r\\\"\\\"\\\"\\n    Computes the `n`-th nontrivial zero of `\\\\zeta(s)` on the critical line,\\n    i.e. returns an approximation of the `n`-th largest complex number\\n    `s = \\\\frac{1}{2} + ti` for which `\\\\zeta(s) = 0`. Equivalently, the\\n    imaginary part `t` is a zero of the Z-function (:func:`~mpmath.siegelz`).\\n\\n    **Examples**\\n\\n    The first few zeros::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> zetazero(1)\\n        (0.5 + 14.13472514173469379045725j)\\n        >>> zetazero(2)\\n        (0.5 + 21.02203963877155499262848j)\\n        >>> zetazero(20)\\n        (0.5 + 77.14484006887480537268266j)\\n\\n    Verifying that the values are zeros::\\n\\n        >>> for n in range(1,5):\\n        ...     s = zetazero(n)\\n        ...     chop(zeta(s)), chop(siegelz(s.imag))\\n        ...\\n        (0.0, 0.0)\\n        (0.0, 0.0)\\n        (0.0, 0.0)\\n        (0.0, 0.0)\\n\\n    Negative indices give the conjugate zeros (`n = 0` is undefined)::\\n\\n        >>> zetazero(-1)\\n        (0.5 - 14.13472514173469379045725j)\\n\\n    :func:`~mpmath.zetazero` supports arbitrarily large `n` and arbitrary precision::\\n\\n        >>> mp.dps = 15\\n        >>> zetazero(1234567)\\n        (0.5 + 727690.906948208j)\\n        >>> mp.dps = 50\\n        >>> zetazero(1234567)\\n        (0.5 + 727690.9069482075392389420041147142092708393819935j)\\n        >>> chop(zeta(_)/_)\\n        0.0\\n\\n    with *info=True*, :func:`~mpmath.zetazero` gives additional information::\\n\\n        >>> mp.dps = 15\\n        >>> zetazero(542964976,info=True)\\n        ((0.5 + 209039046.578535j), [542964969, 542964978], 6, '(013111110)')\\n\\n    This means that the zero is between Gram points 542964969 and 542964978;\\n    it is the 6-th zero between them. Finally (01311110) is the pattern\\n    of zeros in this interval. The numbers indicate the number of zeros\\n    in each Gram interval (Rosser blocks between parenthesis). In this case\\n    there is only one Rosser block of length nine.\\n    \\\"\\\"\\\"\\n    n = int(n)\\n    if n < 0:\\n        return ctx.zetazero(-n).conjugate()\\n    if n == 0:\\n        raise ValueError(\\\"n must be nonzero\\\")\\n    wpinitial = ctx.prec\\n    try:\\n        wpz, fp_tolerance = comp_fp_tolerance(ctx, n)\\n        ctx.prec = wpz\\n        if n < 400000000:\\n            my_zero_number, block, T, V =\\\\\\n             find_rosser_block_zero(ctx, n)\\n        else:\\n            my_zero_number, block, T, V =\\\\\\n             search_supergood_block(ctx, n, fp_tolerance)\\n        zero_number_block = block[1]-block[0]\\n        T, V, separated = separate_zeros_in_block(ctx, zero_number_block, T, V,\\n            limitloop=ctx.inf, fp_tolerance=fp_tolerance)\\n        if info:\\n            pattern = pattern_construct(ctx,block,T,V)\\n        prec = max(wpinitial, wpz)\\n        t = separate_my_zero(ctx, my_zero_number, zero_number_block,T,V,prec)\\n        v = ctx.mpc(0.5,t)\\n    finally:\\n        ctx.prec = wpinitial\\n    if round:\\n        v =+v\\n    if info:\\n        return (v,block,my_zero_number,pattern)\\n    else:\\n        return v\\n\\ndef gram_index(ctx, t):\\n    if t > 10**13:\\n        wp = 3*ctx.log(t, 10)\\n    else:\\n        wp = 0\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += wp\\n        h = int(ctx.siegeltheta(t)/ctx.pi)\\n    finally:\\n        ctx.prec = prec\\n    return(h)\\n\\ndef count_to(ctx, t, T, V):\\n    count = 0\\n    vold = V[0]\\n    told = T[0]\\n    tnew = T[1]\\n    k = 1\\n    while tnew < t:\\n        vnew = V[k]\\n        if vold*vnew < 0:\\n            count += 1\\n        vold = vnew\\n        k += 1\\n        tnew = T[k]\\n    a = ctx.siegelz(t)\\n    if a*vold < 0:\\n        count += 1\\n    return count\\n\\ndef comp_fp_tolerance(ctx, n):\\n    wpz = wpzeros(n*ctx.log(n))\\n    if n < 15*10**8:\\n        fp_tolerance = 0.0005\\n    elif n <= 10**14:\\n        fp_tolerance = 0.1\\n    else:\\n        fp_tolerance = 100\\n    return wpz, fp_tolerance\\n\\n@defun\\ndef nzeros(ctx, t):\\n    r\\\"\\\"\\\"\\n    Computes the number of zeros of the Riemann zeta function in\\n    `(0,1) \\\\times (0,t]`, usually denoted by `N(t)`.\\n\\n    **Examples**\\n\\n    The first zero has imaginary part between 14 and 15::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> nzeros(14)\\n        0\\n        >>> nzeros(15)\\n        1\\n        >>> zetazero(1)\\n        (0.5 + 14.1347251417347j)\\n\\n    Some closely spaced zeros::\\n\\n        >>> nzeros(10**7)\\n        21136125\\n        >>> zetazero(21136125)\\n        (0.5 + 9999999.32718175j)\\n        >>> zetazero(21136126)\\n        (0.5 + 10000000.2400236j)\\n        >>> nzeros(545439823.215)\\n        1500000001\\n        >>> zetazero(1500000001)\\n        (0.5 + 545439823.201985j)\\n        >>> zetazero(1500000002)\\n        (0.5 + 545439823.325697j)\\n\\n    This confirms the data given by J. van de Lune,\\n    H. J. J. te Riele and D. T. Winter in 1986.\\n    \\\"\\\"\\\"\\n    if t < 14.1347251417347:\\n        return 0\\n    x = gram_index(ctx, t)\\n    k = int(ctx.floor(x))\\n    wpinitial = ctx.prec\\n    wpz, fp_tolerance = comp_fp_tolerance(ctx, k)\\n    ctx.prec = wpz\\n    a = ctx.siegelz(t)\\n    if k == -1 and a < 0:\\n        return 0\\n    elif k == -1 and a > 0:\\n        return 1\\n    if k+2 < 400000000:\\n        Rblock = find_rosser_block_zero(ctx, k+2)\\n    else:\\n        Rblock = search_supergood_block(ctx, k+2, fp_tolerance)\\n    n1, n2 = Rblock[1]\\n    if n2-n1 == 1:\\n        b = Rblock[3][0]\\n        if a*b > 0:\\n            ctx.prec = wpinitial\\n            return k+1\\n        else:\\n            ctx.prec = wpinitial\\n            return k+2\\n    my_zero_number,block, T, V = Rblock\\n    zero_number_block = n2-n1\\n    T, V, separated = separate_zeros_in_block(ctx,\\\\\\n                                              zero_number_block, T, V,\\\\\\n                                              limitloop=ctx.inf,\\\\\\n                                            fp_tolerance=fp_tolerance)\\n    n = count_to(ctx, t, T, V)\\n    ctx.prec = wpinitial\\n    return n+n1+1\\n\\n@defun_wrapped\\ndef backlunds(ctx, t):\\n    r\\\"\\\"\\\"\\n    Computes the function\\n    `S(t) = \\\\operatorname{arg} \\\\zeta(\\\\frac{1}{2} + it) / \\\\pi`.\\n\\n    See Titchmarsh Section 9.3 for details of the definition.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> backlunds(217.3)\\n        0.16302205431184\\n\\n    Generally, the value is a small number. At Gram points it is an integer,\\n    frequently equal to 0::\\n\\n        >>> chop(backlunds(grampoint(200)))\\n        0.0\\n        >>> backlunds(extraprec(10)(grampoint)(211))\\n        1.0\\n        >>> backlunds(extraprec(10)(grampoint)(232))\\n        -1.0\\n\\n    The number of zeros of the Riemann zeta function up to height `t`\\n    satisfies `N(t) = \\\\theta(t)/\\\\pi + 1 + S(t)` (see :func:nzeros` and\\n    :func:`siegeltheta`)::\\n\\n        >>> t = 1234.55\\n        >>> nzeros(t)\\n        842\\n        >>> siegeltheta(t)/pi+1+backlunds(t)\\n        842.0\\n\\n    \\\"\\\"\\\"\\n    return ctx.nzeros(t)-1-ctx.siegeltheta(t)/ctx.pi\\n\\n\\n\\\"\\\"\\\"\\n_ROSSER_EXCEPTIONS is a list of all  exceptions to\\nRosser's rule for n <= 400 000 000.\\n\\nAlternately the  entry is of type   [n,m], or a string.\\nThe string is the zero pattern of the Block and the relevant\\nadjacent.  For example (010)3 corresponds to a block\\ncomposed of three Gram intervals, the first ant third without\\na zero and the intermediate with a zero. The next Gram interval\\ncontain three zeros. So that in total we have 4 zeros in 4 Gram\\nblocks. n and m are the indices of the Gram points  of this\\ninterval of four Gram intervals. The Rosser exception is therefore\\nformed by the three Gram intervals that are signaled between\\nparenthesis.\\n\\nWe have included also some Rosser's exceptions beyond n=400 000 000\\nthat are noted in the literature by some reason.\\n\\nThe list is composed from the data published in the references:\\n\\nR. P. Brent, J. van de Lune, H. J. J. te Riele, D. T. Winter,\\n'On the Zeros of the Riemann Zeta Function in the Critical Strip. II',\\nMath. Comp. 39 (1982) 681--688.\\nSee also Corrigenda in Math. Comp. 46 (1986) 771.\\n\\nJ. van de Lune, H. J. J. te Riele,\\n'On the Zeros of the Riemann Zeta Function in the Critical Strip. III',\\nMath. Comp. 41 (1983) 759--767.\\nSee also  Corrigenda in Math. Comp. 46 (1986) 771.\\n\\nJ. van de Lune,\\n'Sums of Equal Powers of Positive Integers',\\nDissertation,\\nVrije Universiteit te Amsterdam, Centrum voor Wiskunde en Informatica,\\nAmsterdam, 1984.\\n\\nThanks to the authors all this papers and those others that have\\ncontributed to make this possible.\\n\\\"\\\"\\\"\\n\\n\\n\\n\\n\\n\\n\\n_ROSSER_EXCEPTIONS = \\\\\\n[[13999525, 13999528], '(00)3',\\n[30783329, 30783332], '(00)3',\\n[30930926, 30930929], '3(00)',\\n[37592215, 37592218], '(00)3',\\n[40870156, 40870159], '(00)3',\\n[43628107, 43628110], '(00)3',\\n[46082042, 46082045], '(00)3',\\n[46875667, 46875670], '(00)3',\\n[49624540, 49624543], '3(00)',\\n[50799238, 50799241], '(00)3',\\n[55221453, 55221456], '3(00)',\\n[56948779, 56948782], '3(00)',\\n[60515663, 60515666], '(00)3',\\n[61331766, 61331770], '(00)40',\\n[69784843, 69784846], '3(00)',\\n[75052114, 75052117], '(00)3',\\n[79545240, 79545243], '3(00)',\\n[79652247, 79652250], '3(00)',\\n[83088043, 83088046], '(00)3',\\n[83689522, 83689525], '3(00)',\\n[85348958, 85348961], '(00)3',\\n[86513820, 86513823], '(00)3',\\n[87947596, 87947599], '3(00)',\\n[88600095, 88600098], '(00)3',\\n[93681183, 93681186], '(00)3',\\n[100316551, 100316554], '3(00)',\\n[100788444, 100788447], '(00)3',\\n[106236172, 106236175], '(00)3',\\n[106941327, 106941330], '3(00)',\\n[107287955, 107287958], '(00)3',\\n[107532016, 107532019], '3(00)',\\n[110571044, 110571047], '(00)3',\\n[111885253, 111885256], '3(00)',\\n[113239783, 113239786], '(00)3',\\n[120159903, 120159906], '(00)3',\\n[121424391, 121424394], '3(00)',\\n[121692931, 121692934], '3(00)',\\n[121934170, 121934173], '3(00)',\\n[122612848, 122612851], '3(00)',\\n[126116567, 126116570], '(00)3',\\n[127936513, 127936516], '(00)3',\\n[128710277, 128710280], '3(00)',\\n[129398902, 129398905], '3(00)',\\n[130461096, 130461099], '3(00)',\\n[131331947, 131331950], '3(00)',\\n[137334071, 137334074], '3(00)',\\n[137832603, 137832606], '(00)3',\\n[138799471, 138799474], '3(00)',\\n[139027791, 139027794], '(00)3',\\n[141617806, 141617809], '(00)3',\\n[144454931, 144454934], '(00)3',\\n[145402379, 145402382], '3(00)',\\n[146130245, 146130248], '3(00)',\\n[147059770, 147059773], '(00)3',\\n[147896099, 147896102], '3(00)',\\n[151097113, 151097116], '(00)3',\\n[152539438, 152539441], '(00)3',\\n[152863168, 152863171], '3(00)',\\n[153522726, 153522729], '3(00)',\\n[155171524, 155171527], '3(00)',\\n[155366607, 155366610], '(00)3',\\n[157260686, 157260689], '3(00)',\\n[157269224, 157269227], '(00)3',\\n[157755123, 157755126], '(00)3',\\n[158298484, 158298487], '3(00)',\\n[160369050, 160369053], '3(00)',\\n[162962787, 162962790], '(00)3',\\n[163724709, 163724712], '(00)3',\\n[164198113, 164198116], '3(00)',\\n[164689301, 164689305], '(00)40',\\n[164880228, 164880231], '3(00)',\\n[166201932, 166201935], '(00)3',\\n[168573836, 168573839], '(00)3',\\n[169750763, 169750766], '(00)3',\\n[170375507, 170375510], '(00)3',\\n[170704879, 170704882], '3(00)',\\n[172000992, 172000995], '3(00)',\\n[173289941, 173289944], '(00)3',\\n[173737613, 173737616], '3(00)',\\n[174102513, 174102516], '(00)3',\\n[174284990, 174284993], '(00)3',\\n[174500513, 174500516], '(00)3',\\n[175710609, 175710612], '(00)3',\\n[176870843, 176870846], '3(00)',\\n[177332732, 177332735], '3(00)',\\n[177902861, 177902864], '3(00)',\\n[179979095, 179979098], '(00)3',\\n[181233726, 181233729], '3(00)',\\n[181625435, 181625438], '(00)3',\\n[182105255, 182105259], '22(00)',\\n[182223559, 182223562], '3(00)',\\n[191116404, 191116407], '3(00)',\\n[191165599, 191165602], '3(00)',\\n[191297535, 191297539], '(00)22',\\n[192485616, 192485619], '(00)3',\\n[193264634, 193264638], '22(00)',\\n[194696968, 194696971], '(00)3',\\n[195876805, 195876808], '(00)3',\\n[195916548, 195916551], '3(00)',\\n[196395160, 196395163], '3(00)',\\n[196676303, 196676306], '(00)3',\\n[197889882, 197889885], '3(00)',\\n[198014122, 198014125], '(00)3',\\n[199235289, 199235292], '(00)3',\\n[201007375, 201007378], '(00)3',\\n[201030605, 201030608], '3(00)',\\n[201184290, 201184293], '3(00)',\\n[201685414, 201685418], '(00)22',\\n[202762875, 202762878], '3(00)',\\n[202860957, 202860960], '3(00)',\\n[203832577, 203832580], '3(00)',\\n[205880544, 205880547], '(00)3',\\n[206357111, 206357114], '(00)3',\\n[207159767, 207159770], '3(00)',\\n[207167343, 207167346], '3(00)',\\n[207482539, 207482543], '3(010)',\\n[207669540, 207669543], '3(00)',\\n[208053426, 208053429], '(00)3',\\n[208110027, 208110030], '3(00)',\\n[209513826, 209513829], '3(00)',\\n[212623522, 212623525], '(00)3',\\n[213841715, 213841718], '(00)3',\\n[214012333, 214012336], '(00)3',\\n[214073567, 214073570], '(00)3',\\n[215170600, 215170603], '3(00)',\\n[215881039, 215881042], '3(00)',\\n[216274604, 216274607], '3(00)',\\n[216957120, 216957123], '3(00)',\\n[217323208, 217323211], '(00)3',\\n[218799264, 218799267], '(00)3',\\n[218803557, 218803560], '3(00)',\\n[219735146, 219735149], '(00)3',\\n[219830062, 219830065], '3(00)',\\n[219897904, 219897907], '(00)3',\\n[221205545, 221205548], '(00)3',\\n[223601929, 223601932], '(00)3',\\n[223907076, 223907079], '3(00)',\\n[223970397, 223970400], '(00)3',\\n[224874044, 224874048], '22(00)',\\n[225291157, 225291160], '(00)3',\\n[227481734, 227481737], '(00)3',\\n[228006442, 228006445], '3(00)',\\n[228357900, 228357903], '(00)3',\\n[228386399, 228386402], '(00)3',\\n[228907446, 228907449], '(00)3',\\n[228984552, 228984555], '3(00)',\\n[229140285, 229140288], '3(00)',\\n[231810024, 231810027], '(00)3',\\n[232838062, 232838065], '3(00)',\\n[234389088, 234389091], '3(00)',\\n[235588194, 235588197], '(00)3',\\n[236645695, 236645698], '(00)3',\\n[236962876, 236962879], '3(00)',\\n[237516723, 237516727], '04(00)',\\n[240004911, 240004914], '(00)3',\\n[240221306, 240221309], '3(00)',\\n[241389213, 241389217], '(010)3',\\n[241549003, 241549006], '(00)3',\\n[241729717, 241729720], '(00)3',\\n[241743684, 241743687], '3(00)',\\n[243780200, 243780203], '3(00)',\\n[243801317, 243801320], '(00)3',\\n[244122072, 244122075], '(00)3',\\n[244691224, 244691227], '3(00)',\\n[244841577, 244841580], '(00)3',\\n[245813461, 245813464], '(00)3',\\n[246299475, 246299478], '(00)3',\\n[246450176, 246450179], '3(00)',\\n[249069349, 249069352], '(00)3',\\n[250076378, 250076381], '(00)3',\\n[252442157, 252442160], '3(00)',\\n[252904231, 252904234], '3(00)',\\n[255145220, 255145223], '(00)3',\\n[255285971, 255285974], '3(00)',\\n[256713230, 256713233], '(00)3',\\n[257992082, 257992085], '(00)3',\\n[258447955, 258447959], '22(00)',\\n[259298045, 259298048], '3(00)',\\n[262141503, 262141506], '(00)3',\\n[263681743, 263681746], '3(00)',\\n[266527881, 266527885], '(010)3',\\n[266617122, 266617125], '(00)3',\\n[266628044, 266628047], '3(00)',\\n[267305763, 267305766], '(00)3',\\n[267388404, 267388407], '3(00)',\\n[267441672, 267441675], '3(00)',\\n[267464886, 267464889], '(00)3',\\n[267554907, 267554910], '3(00)',\\n[269787480, 269787483], '(00)3',\\n[270881434, 270881437], '(00)3',\\n[270997583, 270997586], '3(00)',\\n[272096378, 272096381], '3(00)',\\n[272583009, 272583012], '(00)3',\\n[274190881, 274190884], '3(00)',\\n[274268747, 274268750], '(00)3',\\n[275297429, 275297432], '3(00)',\\n[275545476, 275545479], '3(00)',\\n[275898479, 275898482], '3(00)',\\n[275953000, 275953003], '(00)3',\\n[277117197, 277117201], '(00)22',\\n[277447310, 277447313], '3(00)',\\n[279059657, 279059660], '3(00)',\\n[279259144, 279259147], '3(00)',\\n[279513636, 279513639], '3(00)',\\n[279849069, 279849072], '3(00)',\\n[280291419, 280291422], '(00)3',\\n[281449425, 281449428], '3(00)',\\n[281507953, 281507956], '3(00)',\\n[281825600, 281825603], '(00)3',\\n[282547093, 282547096], '3(00)',\\n[283120963, 283120966], '3(00)',\\n[283323493, 283323496], '(00)3',\\n[284764535, 284764538], '3(00)',\\n[286172639, 286172642], '3(00)',\\n[286688824, 286688827], '(00)3',\\n[287222172, 287222175], '3(00)',\\n[287235534, 287235537], '3(00)',\\n[287304861, 287304864], '3(00)',\\n[287433571, 287433574], '(00)3',\\n[287823551, 287823554], '(00)3',\\n[287872422, 287872425], '3(00)',\\n[288766615, 288766618], '3(00)',\\n[290122963, 290122966], '3(00)',\\n[290450849, 290450853], '(00)22',\\n[291426141, 291426144], '3(00)',\\n[292810353, 292810356], '3(00)',\\n[293109861, 293109864], '3(00)',\\n[293398054, 293398057], '3(00)',\\n[294134426, 294134429], '3(00)',\\n[294216438, 294216441], '(00)3',\\n[295367141, 295367144], '3(00)',\\n[297834111, 297834114], '3(00)',\\n[299099969, 299099972], '3(00)',\\n[300746958, 300746961], '3(00)',\\n[301097423, 301097426], '(00)3',\\n[301834209, 301834212], '(00)3',\\n[302554791, 302554794], '(00)3',\\n[303497445, 303497448], '3(00)',\\n[304165344, 304165347], '3(00)',\\n[304790218, 304790222], '3(010)',\\n[305302352, 305302355], '(00)3',\\n[306785996, 306785999], '3(00)',\\n[307051443, 307051446], '3(00)',\\n[307481539, 307481542], '3(00)',\\n[308605569, 308605572], '3(00)',\\n[309237610, 309237613], '3(00)',\\n[310509287, 310509290], '(00)3',\\n[310554057, 310554060], '3(00)',\\n[310646345, 310646348], '3(00)',\\n[311274896, 311274899], '(00)3',\\n[311894272, 311894275], '3(00)',\\n[312269470, 312269473], '(00)3',\\n[312306601, 312306605], '(00)40',\\n[312683193, 312683196], '3(00)',\\n[314499804, 314499807], '3(00)',\\n[314636802, 314636805], '(00)3',\\n[314689897, 314689900], '3(00)',\\n[314721319, 314721322], '3(00)',\\n[316132890, 316132893], '3(00)',\\n[316217470, 316217474], '(010)3',\\n[316465705, 316465708], '3(00)',\\n[316542790, 316542793], '(00)3',\\n[320822347, 320822350], '3(00)',\\n[321733242, 321733245], '3(00)',\\n[324413970, 324413973], '(00)3',\\n[325950140, 325950143], '(00)3',\\n[326675884, 326675887], '(00)3',\\n[326704208, 326704211], '3(00)',\\n[327596247, 327596250], '3(00)',\\n[328123172, 328123175], '3(00)',\\n[328182212, 328182215], '(00)3',\\n[328257498, 328257501], '3(00)',\\n[328315836, 328315839], '(00)3',\\n[328800974, 328800977], '(00)3',\\n[328998509, 328998512], '3(00)',\\n[329725370, 329725373], '(00)3',\\n[332080601, 332080604], '(00)3',\\n[332221246, 332221249], '(00)3',\\n[332299899, 332299902], '(00)3',\\n[332532822, 332532825], '(00)3',\\n[333334544, 333334548], '(00)22',\\n[333881266, 333881269], '3(00)',\\n[334703267, 334703270], '3(00)',\\n[334875138, 334875141], '3(00)',\\n[336531451, 336531454], '3(00)',\\n[336825907, 336825910], '(00)3',\\n[336993167, 336993170], '(00)3',\\n[337493998, 337494001], '3(00)',\\n[337861034, 337861037], '3(00)',\\n[337899191, 337899194], '(00)3',\\n[337958123, 337958126], '(00)3',\\n[342331982, 342331985], '3(00)',\\n[342676068, 342676071], '3(00)',\\n[347063781, 347063784], '3(00)',\\n[347697348, 347697351], '3(00)',\\n[347954319, 347954322], '3(00)',\\n[348162775, 348162778], '3(00)',\\n[349210702, 349210705], '(00)3',\\n[349212913, 349212916], '3(00)',\\n[349248650, 349248653], '(00)3',\\n[349913500, 349913503], '3(00)',\\n[350891529, 350891532], '3(00)',\\n[351089323, 351089326], '3(00)',\\n[351826158, 351826161], '3(00)',\\n[352228580, 352228583], '(00)3',\\n[352376244, 352376247], '3(00)',\\n[352853758, 352853761], '(00)3',\\n[355110439, 355110442], '(00)3',\\n[355808090, 355808094], '(00)40',\\n[355941556, 355941559], '3(00)',\\n[356360231, 356360234], '(00)3',\\n[356586657, 356586660], '3(00)',\\n[356892926, 356892929], '(00)3',\\n[356908232, 356908235], '3(00)',\\n[357912730, 357912733], '3(00)',\\n[358120344, 358120347], '3(00)',\\n[359044096, 359044099], '(00)3',\\n[360819357, 360819360], '3(00)',\\n[361399662, 361399666], '(010)3',\\n[362361315, 362361318], '(00)3',\\n[363610112, 363610115], '(00)3',\\n[363964804, 363964807], '3(00)',\\n[364527375, 364527378], '(00)3',\\n[365090327, 365090330], '(00)3',\\n[365414539, 365414542], '3(00)',\\n[366738474, 366738477], '3(00)',\\n[368714778, 368714783], '04(010)',\\n[368831545, 368831548], '(00)3',\\n[368902387, 368902390], '(00)3',\\n[370109769, 370109772], '3(00)',\\n[370963333, 370963336], '3(00)',\\n[372541136, 372541140], '3(010)',\\n[372681562, 372681565], '(00)3',\\n[373009410, 373009413], '(00)3',\\n[373458970, 373458973], '3(00)',\\n[375648658, 375648661], '3(00)',\\n[376834728, 376834731], '3(00)',\\n[377119945, 377119948], '(00)3',\\n[377335703, 377335706], '(00)3',\\n[378091745, 378091748], '3(00)',\\n[379139522, 379139525], '3(00)',\\n[380279160, 380279163], '(00)3',\\n[380619442, 380619445], '3(00)',\\n[381244231, 381244234], '3(00)',\\n[382327446, 382327450], '(010)3',\\n[382357073, 382357076], '3(00)',\\n[383545479, 383545482], '3(00)',\\n[384363766, 384363769], '(00)3',\\n[384401786, 384401790], '22(00)',\\n[385198212, 385198215], '3(00)',\\n[385824476, 385824479], '(00)3',\\n[385908194, 385908197], '3(00)',\\n[386946806, 386946809], '3(00)',\\n[387592175, 387592179], '22(00)',\\n[388329293, 388329296], '(00)3',\\n[388679566, 388679569], '3(00)',\\n[388832142, 388832145], '3(00)',\\n[390087103, 390087106], '(00)3',\\n[390190926, 390190930], '(00)22',\\n[390331207, 390331210], '3(00)',\\n[391674495, 391674498], '3(00)',\\n[391937831, 391937834], '3(00)',\\n[391951632, 391951636], '(00)22',\\n[392963986, 392963989], '(00)3',\\n[393007921, 393007924], '3(00)',\\n[393373210, 393373213], '3(00)',\\n[393759572, 393759575], '(00)3',\\n[394036662, 394036665], '(00)3',\\n[395813866, 395813869], '(00)3',\\n[395956690, 395956693], '3(00)',\\n[396031670, 396031673], '3(00)',\\n[397076433, 397076436], '3(00)',\\n[397470601, 397470604], '3(00)',\\n[398289458, 398289461], '3(00)',\\n#\\n[368714778, 368714783], '04(010)',\\n[437953499, 437953504], '04(010)',\\n[526196233, 526196238], '032(00)',\\n[744719566, 744719571], '(010)40',\\n[750375857, 750375862], '032(00)',\\n[958241932, 958241937], '04(010)',\\n[983377342, 983377347], '(00)410',\\n[1003780080, 1003780085], '04(010)',\\n[1070232754, 1070232759], '(00)230',\\n[1209834865, 1209834870], '032(00)',\\n[1257209100, 1257209105], '(00)410',\\n[1368002233, 1368002238], '(00)230'\\n]\\n\\n\\nfrom .functions import defun_wrapped\\n\\n@defun_wrapped\\ndef squarew(ctx, t, amplitude=1, period=1):\\n    P = period\\n    A = amplitude\\n    return A*((-1)**ctx.floor(2*t/P))\\n\\n@defun_wrapped\\ndef trianglew(ctx, t, amplitude=1, period=1):\\n    A = amplitude\\n    P = period\\n\\n    return 2*A*(0.5 - ctx.fabs(1 - 2*ctx.frac(t/P + 0.25)))\\n\\n@defun_wrapped\\ndef sawtoothw(ctx, t, amplitude=1, period=1):\\n    A = amplitude\\n    P = period\\n    return A*ctx.frac(t/P)\\n\\n@defun_wrapped\\ndef unit_triangle(ctx, t, amplitude=1):\\n    A = amplitude\\n    if t <= -1 or t >= 1:\\n        return ctx.zero\\n    return A*(-ctx.fabs(t) + 1)\\n\\n@defun_wrapped\\ndef sigmoid(ctx, t, amplitude=1):\\n    A = amplitude\\n    return A / (1 + ctx.exp(-t))\\n\\n\\nfrom .functions import defun, defun_wrapped\\n\\n@defun_wrapped\\ndef _erf_complex(ctx, z):\\n    z2 = ctx.square_exp_arg(z, -1)\\n    #z2 = -z**2\\n    v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2)\\n    if not ctx._re(z):\\n        v = ctx._im(v)*ctx.j\\n    return v\\n\\n@defun_wrapped\\ndef _erfc_complex(ctx, z):\\n    if ctx.re(z) > 2:\\n        z2 = ctx.square_exp_arg(z)\\n        nz2 = ctx.fneg(z2, exact=True)\\n        v = ctx.exp(nz2)/ctx.sqrt(ctx.pi) * ctx.hyperu((1,2),(1,2), z2)\\n    else:\\n        v = 1 - ctx._erf_complex(z)\\n    if not ctx._re(z):\\n        v = 1+ctx._im(v)*ctx.j\\n    return v\\n\\n@defun\\ndef erf(ctx, z):\\n    z = ctx.convert(z)\\n    if ctx._is_real_type(z):\\n        try:\\n            return ctx._erf(z)\\n        except NotImplementedError:\\n            pass\\n    if ctx._is_complex_type(z) and not z.imag:\\n        try:\\n            return type(z)(ctx._erf(z.real))\\n        except NotImplementedError:\\n            pass\\n    return ctx._erf_complex(z)\\n\\n@defun\\ndef erfc(ctx, z):\\n    z = ctx.convert(z)\\n    if ctx._is_real_type(z):\\n        try:\\n            return ctx._erfc(z)\\n        except NotImplementedError:\\n            pass\\n    if ctx._is_complex_type(z) and not z.imag:\\n        try:\\n            return type(z)(ctx._erfc(z.real))\\n        except NotImplementedError:\\n            pass\\n    return ctx._erfc_complex(z)\\n\\n@defun\\ndef square_exp_arg(ctx, z, mult=1, reciprocal=False):\\n    prec = ctx.prec*4+20\\n    if reciprocal:\\n        z2 = ctx.fmul(z, z, prec=prec)\\n        z2 = ctx.fdiv(ctx.one, z2, prec=prec)\\n    else:\\n        z2 = ctx.fmul(z, z, prec=prec)\\n    if mult != 1:\\n        z2 = ctx.fmul(z2, mult, exact=True)\\n    return z2\\n\\n@defun_wrapped\\ndef erfi(ctx, z):\\n    if not z:\\n        return z\\n    z2 = ctx.square_exp_arg(z)\\n    v = (2/ctx.sqrt(ctx.pi)*z) * ctx.hyp1f1((1,2), (3,2), z2)\\n    if not ctx._re(z):\\n        v = ctx._im(v)*ctx.j\\n    return v\\n\\n@defun_wrapped\\ndef erfinv(ctx, x):\\n    xre = ctx._re(x)\\n    if (xre != x) or (xre < -1) or (xre > 1):\\n        return ctx.bad_domain(\\\"erfinv(x) is defined only for -1 <= x <= 1\\\")\\n    x = xre\\n    #if ctx.isnan(x): return x\\n    if not x: return x\\n    if x == 1: return ctx.inf\\n    if x == -1: return ctx.ninf\\n    if abs(x) < 0.9:\\n        a = 0.53728*x**3 + 0.813198*x\\n    else:\\n        # An asymptotic formula\\n        u = ctx.ln(2/ctx.pi/(abs(x)-1)**2)\\n        a = ctx.sign(x) * ctx.sqrt(u - ctx.ln(u))/ctx.sqrt(2)\\n    ctx.prec += 10\\n    return ctx.findroot(lambda t: ctx.erf(t)-x, a)\\n\\n@defun_wrapped\\ndef npdf(ctx, x, mu=0, sigma=1):\\n    sigma = ctx.convert(sigma)\\n    return ctx.exp(-(x-mu)**2/(2*sigma**2)) / (sigma*ctx.sqrt(2*ctx.pi))\\n\\n@defun_wrapped\\ndef ncdf(ctx, x, mu=0, sigma=1):\\n    a = (x-mu)/(sigma*ctx.sqrt(2))\\n    if a < 0:\\n        return ctx.erfc(-a)/2\\n    else:\\n        return (1+ctx.erf(a))/2\\n\\n@defun_wrapped\\ndef betainc(ctx, a, b, x1=0, x2=1, regularized=False):\\n    if x1 == x2:\\n        v = 0\\n    elif not x1:\\n        if x1 == 0 and x2 == 1:\\n            v = ctx.beta(a, b)\\n        else:\\n            v = x2**a * ctx.hyp2f1(a, 1-b, a+1, x2) / a\\n    else:\\n        m, d = ctx.nint_distance(a)\\n        if m <= 0:\\n            if d < -ctx.prec:\\n                h = +ctx.eps\\n                ctx.prec *= 2\\n                a += h\\n            elif d < -4:\\n                ctx.prec -= d\\n        s1 = x2**a * ctx.hyp2f1(a,1-b,a+1,x2)\\n        s2 = x1**a * ctx.hyp2f1(a,1-b,a+1,x1)\\n        v = (s1 - s2) / a\\n    if regularized:\\n        v /= ctx.beta(a,b)\\n    return v\\n\\n@defun\\ndef gammainc(ctx, z, a=0, b=None, regularized=False):\\n    regularized = bool(regularized)\\n    z = ctx.convert(z)\\n    if a is None:\\n        a = ctx.zero\\n        lower_modified = False\\n    else:\\n        a = ctx.convert(a)\\n        lower_modified = a != ctx.zero\\n    if b is None:\\n        b = ctx.inf\\n        upper_modified = False\\n    else:\\n        b = ctx.convert(b)\\n        upper_modified = b != ctx.inf\\n    # Complete gamma function\\n    if not (upper_modified or lower_modified):\\n        if regularized:\\n            if ctx.re(z) < 0:\\n                return ctx.inf\\n            elif ctx.re(z) > 0:\\n                return ctx.one\\n            else:\\n                return ctx.nan\\n        return ctx.gamma(z)\\n    if a == b:\\n        return ctx.zero\\n    # Standardize\\n    if ctx.re(a) > ctx.re(b):\\n        return -ctx.gammainc(z, b, a, regularized)\\n    # Generalized gamma\\n    if upper_modified and lower_modified:\\n        return +ctx._gamma3(z, a, b, regularized)\\n    # Upper gamma\\n    elif lower_modified:\\n        return ctx._upper_gamma(z, a, regularized)\\n    # Lower gamma\\n    elif upper_modified:\\n        return ctx._lower_gamma(z, b, regularized)\\n\\n@defun\\ndef _lower_gamma(ctx, z, b, regularized=False):\\n    # Pole\\n    if ctx.isnpint(z):\\n        return type(z)(ctx.inf)\\n    G = [z] * regularized\\n    negb = ctx.fneg(b, exact=True)\\n    def h(z):\\n        T1 = [ctx.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b\\n        return (T1,)\\n    return ctx.hypercomb(h, [z])\\n\\n@defun\\ndef _upper_gamma(ctx, z, a, regularized=False):\\n    # Fast integer case, when available\\n    if ctx.isint(z):\\n        try:\\n            if regularized:\\n                # Gamma pole\\n                if ctx.isnpint(z):\\n                    return type(z)(ctx.zero)\\n                orig = ctx.prec\\n                try:\\n                    ctx.prec += 10\\n                    return ctx._gamma_upper_int(z, a) / ctx.gamma(z)\\n                finally:\\n                    ctx.prec = orig\\n            else:\\n                return ctx._gamma_upper_int(z, a)\\n        except NotImplementedError:\\n            pass\\n    # hypercomb is unable to detect the exact zeros, so handle them here\\n    if z == 2 and a == -1:\\n        return (z+a)*0\\n    if z == 3 and (a == -1-1j or a == -1+1j):\\n        return (z+a)*0\\n    nega = ctx.fneg(a, exact=True)\\n    G = [z] * regularized\\n    # Use 2F0 series when possible; fall back to lower gamma representation\\n    try:\\n        def h(z):\\n            r = z-1\\n            return [([ctx.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]\\n        return ctx.hypercomb(h, [z], force_series=True)\\n    except ctx.NoConvergence:\\n        def h(z):\\n            T1 = [], [1, z-1], [z], G, [], [], 0\\n            T2 = [-ctx.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a\\n            return T1, T2\\n        return ctx.hypercomb(h, [z])\\n\\n@defun\\ndef _gamma3(ctx, z, a, b, regularized=False):\\n    pole = ctx.isnpint(z)\\n    if regularized and pole:\\n        return ctx.zero\\n    try:\\n        ctx.prec += 15\\n        # We don't know in advance whether it's better to write as a difference\\n        # of lower or upper gamma functions, so try both\\n        T1 = ctx.gammainc(z, a, regularized=regularized)\\n        T2 = ctx.gammainc(z, b, regularized=regularized)\\n        R = T1 - T2\\n        if ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10:\\n            return R\\n        if not pole:\\n            T1 = ctx.gammainc(z, 0, b, regularized=regularized)\\n            T2 = ctx.gammainc(z, 0, a, regularized=regularized)\\n            R = T1 - T2\\n            # May be ok, but should probably at least print a warning\\n            # about possible cancellation\\n            if 1: #ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10:\\n                return R\\n    finally:\\n        ctx.prec -= 15\\n    raise NotImplementedError\\n\\n@defun_wrapped\\ndef expint(ctx, n, z):\\n    if ctx.isint(n) and ctx._is_real_type(z):\\n        try:\\n            return ctx._expint_int(n, z)\\n        except NotImplementedError:\\n            pass\\n    if ctx.isnan(n) or ctx.isnan(z):\\n        return z*n\\n    if z == ctx.inf:\\n        return 1/z\\n    if z == 0:\\n        # integral from 1 to infinity of t^n\\n        if ctx.re(n) <= 1:\\n            # TODO: reasonable sign of infinity\\n            return type(z)(ctx.inf)\\n        else:\\n            return ctx.one/(n-1)\\n    if n == 0:\\n        return ctx.exp(-z)/z\\n    if n == -1:\\n        return ctx.exp(-z)*(z+1)/z**2\\n    return z**(n-1) * ctx.gammainc(1-n, z)\\n\\n@defun_wrapped\\ndef li(ctx, z, offset=False):\\n    if offset:\\n        if z == 2:\\n            return ctx.zero\\n        return ctx.ei(ctx.ln(z)) - ctx.ei(ctx.ln2)\\n    if not z:\\n        return z\\n    if z == 1:\\n        return ctx.ninf\\n    return ctx.ei(ctx.ln(z))\\n\\n@defun\\ndef ei(ctx, z):\\n    try:\\n        return ctx._ei(z)\\n    except NotImplementedError:\\n        return ctx._ei_generic(z)\\n\\n@defun_wrapped\\ndef _ei_generic(ctx, z):\\n    # Note: the following is currently untested because mp and fp\\n    # both use special-case ei code\\n    if z == ctx.inf:\\n        return z\\n    if z == ctx.ninf:\\n        return ctx.zero\\n    if ctx.mag(z) > 1:\\n        try:\\n            r = ctx.one/z\\n            v = ctx.exp(z)*ctx.hyper([1,1],[],r,\\n                maxterms=ctx.prec, force_series=True)/z\\n            im = ctx._im(z)\\n            if im > 0:\\n                v += ctx.pi*ctx.j\\n            if im < 0:\\n                v -= ctx.pi*ctx.j\\n            return v\\n        except ctx.NoConvergence:\\n            pass\\n    v = z*ctx.hyp2f2(1,1,2,2,z) + ctx.euler\\n    if ctx._im(z):\\n        v += 0.5*(ctx.log(z) - ctx.log(ctx.one/z))\\n    else:\\n        v += ctx.log(abs(z))\\n    return v\\n\\n@defun\\ndef e1(ctx, z):\\n    try:\\n        return ctx._e1(z)\\n    except NotImplementedError:\\n        return ctx.expint(1, z)\\n\\n@defun\\ndef ci(ctx, z):\\n    try:\\n        return ctx._ci(z)\\n    except NotImplementedError:\\n        return ctx._ci_generic(z)\\n\\n@defun_wrapped\\ndef _ci_generic(ctx, z):\\n    if ctx.isinf(z):\\n        if z == ctx.inf: return ctx.zero\\n        if z == ctx.ninf: return ctx.pi*1j\\n    jz = ctx.fmul(ctx.j,z,exact=True)\\n    njz = ctx.fneg(jz,exact=True)\\n    v = 0.5*(ctx.ei(jz) + ctx.ei(njz))\\n    zreal = ctx._re(z)\\n    zimag = ctx._im(z)\\n    if zreal == 0:\\n        if zimag > 0: v += ctx.pi*0.5j\\n        if zimag < 0: v -= ctx.pi*0.5j\\n    if zreal < 0:\\n        if zimag >= 0: v += ctx.pi*1j\\n        if zimag <  0: v -= ctx.pi*1j\\n    if ctx._is_real_type(z) and zreal > 0:\\n        v = ctx._re(v)\\n    return v\\n\\n@defun\\ndef si(ctx, z):\\n    try:\\n        return ctx._si(z)\\n    except NotImplementedError:\\n        return ctx._si_generic(z)\\n\\n@defun_wrapped\\ndef _si_generic(ctx, z):\\n    if ctx.isinf(z):\\n        if z == ctx.inf: return 0.5*ctx.pi\\n        if z == ctx.ninf: return -0.5*ctx.pi\\n    # Suffers from cancellation near 0\\n    if ctx.mag(z) >= -1:\\n        jz = ctx.fmul(ctx.j,z,exact=True)\\n        njz = ctx.fneg(jz,exact=True)\\n        v = (-0.5j)*(ctx.ei(jz) - ctx.ei(njz))\\n        zreal = ctx._re(z)\\n        if zreal > 0:\\n            v -= 0.5*ctx.pi\\n        if zreal < 0:\\n            v += 0.5*ctx.pi\\n        if ctx._is_real_type(z):\\n            v = ctx._re(v)\\n        return v\\n    else:\\n        return z*ctx.hyp1f2((1,2),(3,2),(3,2),-0.25*z*z)\\n\\n@defun_wrapped\\ndef chi(ctx, z):\\n    nz = ctx.fneg(z, exact=True)\\n    v = 0.5*(ctx.ei(z) + ctx.ei(nz))\\n    zreal = ctx._re(z)\\n    zimag = ctx._im(z)\\n    if zimag > 0:\\n        v += ctx.pi*0.5j\\n    elif zimag < 0:\\n        v -= ctx.pi*0.5j\\n    elif zreal < 0:\\n        v += ctx.pi*1j\\n    return v\\n\\n@defun_wrapped\\ndef shi(ctx, z):\\n    # Suffers from cancellation near 0\\n    if ctx.mag(z) >= -1:\\n        nz = ctx.fneg(z, exact=True)\\n        v = 0.5*(ctx.ei(z) - ctx.ei(nz))\\n        zimag = ctx._im(z)\\n        if zimag > 0: v -= 0.5j*ctx.pi\\n        if zimag < 0: v += 0.5j*ctx.pi\\n        return v\\n    else:\\n        return z * ctx.hyp1f2((1,2),(3,2),(3,2),0.25*z*z)\\n\\n@defun_wrapped\\ndef fresnels(ctx, z):\\n    if z == ctx.inf:\\n        return ctx.mpf(0.5)\\n    if z == ctx.ninf:\\n        return ctx.mpf(-0.5)\\n    return ctx.pi*z**3/6*ctx.hyp1f2((3,4),(3,2),(7,4),-ctx.pi**2*z**4/16)\\n\\n@defun_wrapped\\ndef fresnelc(ctx, z):\\n    if z == ctx.inf:\\n        return ctx.mpf(0.5)\\n    if z == ctx.ninf:\\n        return ctx.mpf(-0.5)\\n    return z*ctx.hyp1f2((1,4),(1,2),(5,4),-ctx.pi**2*z**4/16)\\n\\n\\nfrom ..libmp.backend import xrange\\nfrom .functions import defun, defun_wrapped\\n\\ndef _check_need_perturb(ctx, terms, prec, discard_known_zeros):\\n    perturb = recompute = False\\n    extraprec = 0\\n    discard = []\\n    for term_index, term in enumerate(terms):\\n        w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term\\n        have_singular_nongamma_weight = False\\n        # Avoid division by zero in leading factors (TODO:\\n        # also check for near division by zero?)\\n        for k, w in enumerate(w_s):\\n            if not w:\\n                if ctx.re(c_s[k]) <= 0 and c_s[k]:\\n                    perturb = recompute = True\\n                    have_singular_nongamma_weight = True\\n        pole_count = [0, 0, 0]\\n        # Check for gamma and series poles and near-poles\\n        for data_index, data in enumerate([alpha_s, beta_s, b_s]):\\n            for i, x in enumerate(data):\\n                n, d = ctx.nint_distance(x)\\n                # Poles\\n                if n > 0:\\n                    continue\\n                if d == ctx.ninf:\\n                    # OK if we have a polynomial\\n                    # ------------------------------\\n                    ok = False\\n                    if data_index == 2:\\n                        for u in a_s:\\n                            if ctx.isnpint(u) and u >= int(n):\\n                                ok = True\\n                                break\\n                    if ok:\\n                        continue\\n                    pole_count[data_index] += 1\\n                    # ------------------------------\\n                    #perturb = recompute = True\\n                    #return perturb, recompute, extraprec\\n                elif d < -4:\\n                    extraprec += -d\\n                    recompute = True\\n        if discard_known_zeros and pole_count[1] > pole_count[0] + pole_count[2] \\\\\\n            and not have_singular_nongamma_weight:\\n            discard.append(term_index)\\n        elif sum(pole_count):\\n            perturb = recompute = True\\n    return perturb, recompute, extraprec, discard\\n\\n_hypercomb_msg = \\\"\\\"\\\"\\nhypercomb() failed to converge to the requested %i bits of accuracy\\nusing a working precision of %i bits. The function value may be zero or\\ninfinite; try passing zeroprec=N or infprec=M to bound finite values between\\n2^(-N) and 2^M. Otherwise try a higher maxprec or maxterms.\\n\\\"\\\"\\\"\\n\\n@defun\\ndef hypercomb(ctx, function, params=[], discard_known_zeros=True, **kwargs):\\n    orig = ctx.prec\\n    sumvalue = ctx.zero\\n    dist = ctx.nint_distance\\n    ninf = ctx.ninf\\n    orig_params = params[:]\\n    verbose = kwargs.get('verbose', False)\\n    maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(orig))\\n    kwargs['maxprec'] = maxprec   # For calls to hypsum\\n    zeroprec = kwargs.get('zeroprec')\\n    infprec = kwargs.get('infprec')\\n    perturbed_reference_value = None\\n    hextra = 0\\n    try:\\n        while 1:\\n            ctx.prec += 10\\n            if ctx.prec > maxprec:\\n                raise ValueError(_hypercomb_msg % (orig, ctx.prec))\\n            orig2 = ctx.prec\\n            params = orig_params[:]\\n            terms = function(*params)\\n            if verbose:\\n                print()\\n                print(\\\"ENTERING hypercomb main loop\\\")\\n                print(\\\"prec =\\\", ctx.prec)\\n                print(\\\"hextra\\\", hextra)\\n            perturb, recompute, extraprec, discard = \\\\\\n                _check_need_perturb(ctx, terms, orig, discard_known_zeros)\\n            ctx.prec += extraprec\\n            if perturb:\\n                if \\\"hmag\\\" in kwargs:\\n                    hmag = kwargs[\\\"hmag\\\"]\\n                elif ctx._fixed_precision:\\n                    hmag = int(ctx.prec*0.3)\\n                else:\\n                    hmag = orig + 10 + hextra\\n                h = ctx.ldexp(ctx.one, -hmag)\\n                ctx.prec = orig2 + 10 + hmag + 10\\n                for k in range(len(params)):\\n                    params[k] += h\\n                    # Heuristically ensure that the perturbations\\n                    # are \\\"independent\\\" so that two perturbations\\n                    # don't accidentally cancel each other out\\n                    # in a subtraction.\\n                    h += h/(k+1)\\n            if recompute:\\n                terms = function(*params)\\n            if discard_known_zeros:\\n                terms = [term for (i, term) in enumerate(terms) if i not in discard]\\n            if not terms:\\n                return ctx.zero\\n            evaluated_terms = []\\n            for term_index, term_data in enumerate(terms):\\n                w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term_data\\n                if verbose:\\n                    print()\\n                    print(\\\"  Evaluating term %i/%i : %iF%i\\\" % \\\\\\n                        (term_index+1, len(terms), len(a_s), len(b_s)))\\n                    print(\\\"    powers\\\", ctx.nstr(w_s), ctx.nstr(c_s))\\n                    print(\\\"    gamma\\\", ctx.nstr(alpha_s), ctx.nstr(beta_s))\\n                    print(\\\"    hyper\\\", ctx.nstr(a_s), ctx.nstr(b_s))\\n                    print(\\\"    z\\\", ctx.nstr(z))\\n                #v = ctx.hyper(a_s, b_s, z, **kwargs)\\n                #for a in alpha_s: v *= ctx.gamma(a)\\n                #for b in beta_s: v *= ctx.rgamma(b)\\n                #for w, c in zip(w_s, c_s): v *= ctx.power(w, c)\\n                v = ctx.fprod([ctx.hyper(a_s, b_s, z, **kwargs)] + \\\\\\n                    [ctx.gamma(a) for a in alpha_s] + \\\\\\n                    [ctx.rgamma(b) for b in beta_s] + \\\\\\n                    [ctx.power(w,c) for (w,c) in zip(w_s,c_s)])\\n                if verbose:\\n                    print(\\\"    Value:\\\", v)\\n                evaluated_terms.append(v)\\n\\n            if len(terms) == 1 and (not perturb):\\n                sumvalue = evaluated_terms[0]\\n                break\\n\\n            if ctx._fixed_precision:\\n                sumvalue = ctx.fsum(evaluated_terms)\\n                break\\n\\n            sumvalue = ctx.fsum(evaluated_terms)\\n            term_magnitudes = [ctx.mag(x) for x in evaluated_terms]\\n            max_magnitude = max(term_magnitudes)\\n            sum_magnitude = ctx.mag(sumvalue)\\n            cancellation = max_magnitude - sum_magnitude\\n            if verbose:\\n                print()\\n                print(\\\"  Cancellation:\\\", cancellation, \\\"bits\\\")\\n                print(\\\"  Increased precision:\\\", ctx.prec - orig, \\\"bits\\\")\\n\\n            precision_ok = cancellation < ctx.prec - orig\\n\\n            if zeroprec is None:\\n                zero_ok = False\\n            else:\\n                zero_ok = max_magnitude - ctx.prec < -zeroprec\\n            if infprec is None:\\n                inf_ok = False\\n            else:\\n                inf_ok = max_magnitude > infprec\\n\\n            if precision_ok and (not perturb) or ctx.isnan(cancellation):\\n                break\\n            elif precision_ok:\\n                if perturbed_reference_value is None:\\n                    hextra += 20\\n                    perturbed_reference_value = sumvalue\\n                    continue\\n                elif ctx.mag(sumvalue - perturbed_reference_value) <= \\\\\\n                        ctx.mag(sumvalue) - orig:\\n                    break\\n                elif zero_ok:\\n                    sumvalue = ctx.zero\\n                    break\\n                elif inf_ok:\\n                    sumvalue = ctx.inf\\n                    break\\n                elif 'hmag' in kwargs:\\n                    break\\n                else:\\n                    hextra *= 2\\n                    perturbed_reference_value = sumvalue\\n            # Increase precision\\n            else:\\n                increment = min(max(cancellation, orig//2), max(extraprec,orig))\\n                ctx.prec += increment\\n                if verbose:\\n                    print(\\\"  Must start over with increased precision\\\")\\n                continue\\n    finally:\\n        ctx.prec = orig\\n    return +sumvalue\\n\\n@defun\\ndef hyper(ctx, a_s, b_s, z, **kwargs):\\n    \\\"\\\"\\\"\\n    Hypergeometric function, general case.\\n    \\\"\\\"\\\"\\n    z = ctx.convert(z)\\n    p = len(a_s)\\n    q = len(b_s)\\n    a_s = [ctx._convert_param(a) for a in a_s]\\n    b_s = [ctx._convert_param(b) for b in b_s]\\n    # Reduce degree by eliminating common parameters\\n    if kwargs.get('eliminate', True):\\n        elim_nonpositive = kwargs.get('eliminate_all', False)\\n        i = 0\\n        while i < q and a_s:\\n            b = b_s[i]\\n            if b in a_s and (elim_nonpositive or not ctx.isnpint(b[0])):\\n                a_s.remove(b)\\n                b_s.remove(b)\\n                p -= 1\\n                q -= 1\\n            else:\\n                i += 1\\n    # Handle special cases\\n    if p == 0:\\n        if   q == 1: return ctx._hyp0f1(b_s, z, **kwargs)\\n        elif q == 0: return ctx.exp(z)\\n    elif p == 1:\\n        if   q == 1: return ctx._hyp1f1(a_s, b_s, z, **kwargs)\\n        elif q == 2: return ctx._hyp1f2(a_s, b_s, z, **kwargs)\\n        elif q == 0: return ctx._hyp1f0(a_s[0][0], z)\\n    elif p == 2:\\n        if   q == 1: return ctx._hyp2f1(a_s, b_s, z, **kwargs)\\n        elif q == 2: return ctx._hyp2f2(a_s, b_s, z, **kwargs)\\n        elif q == 3: return ctx._hyp2f3(a_s, b_s, z, **kwargs)\\n        elif q == 0: return ctx._hyp2f0(a_s, b_s, z, **kwargs)\\n    elif p == q+1:\\n        return ctx._hypq1fq(p, q, a_s, b_s, z, **kwargs)\\n    elif p > q+1 and not kwargs.get('force_series'):\\n        return ctx._hyp_borel(p, q, a_s, b_s, z, **kwargs)\\n    coeffs, types = zip(*(a_s+b_s))\\n    return ctx.hypsum(p, q, types, coeffs, z, **kwargs)\\n\\n@defun\\ndef hyp0f1(ctx,b,z,**kwargs):\\n    return ctx.hyper([],[b],z,**kwargs)\\n\\n@defun\\ndef hyp1f1(ctx,a,b,z,**kwargs):\\n    return ctx.hyper([a],[b],z,**kwargs)\\n\\n@defun\\ndef hyp1f2(ctx,a1,b1,b2,z,**kwargs):\\n    return ctx.hyper([a1],[b1,b2],z,**kwargs)\\n\\n@defun\\ndef hyp2f1(ctx,a,b,c,z,**kwargs):\\n    return ctx.hyper([a,b],[c],z,**kwargs)\\n\\n@defun\\ndef hyp2f2(ctx,a1,a2,b1,b2,z,**kwargs):\\n    return ctx.hyper([a1,a2],[b1,b2],z,**kwargs)\\n\\n@defun\\ndef hyp2f3(ctx,a1,a2,b1,b2,b3,z,**kwargs):\\n    return ctx.hyper([a1,a2],[b1,b2,b3],z,**kwargs)\\n\\n@defun\\ndef hyp2f0(ctx,a,b,z,**kwargs):\\n    return ctx.hyper([a,b],[],z,**kwargs)\\n\\n@defun\\ndef hyp3f2(ctx,a1,a2,a3,b1,b2,z,**kwargs):\\n    return ctx.hyper([a1,a2,a3],[b1,b2],z,**kwargs)\\n\\n@defun_wrapped\\ndef _hyp1f0(ctx, a, z):\\n    return (1-z) ** (-a)\\n\\n@defun\\ndef _hyp0f1(ctx, b_s, z, **kwargs):\\n    (b, btype), = b_s\\n    if z:\\n        magz = ctx.mag(z)\\n    else:\\n        magz = 0\\n    if magz >= 8 and not kwargs.get('force_series'):\\n        try:\\n            # http://functions.wolfram.com/HypergeometricFunctions/\\n            # Hypergeometric0F1/06/02/03/0004/\\n            # TODO: handle the all-real case more efficiently!\\n            # TODO: figure out how much precision is needed (exponential growth)\\n            orig = ctx.prec\\n            try:\\n                ctx.prec += 12 + magz//2\\n                def h():\\n                    w = ctx.sqrt(-z)\\n                    jw = ctx.j*w\\n                    u = 1/(4*jw)\\n                    c = ctx.mpq_1_2 - b\\n                    E = ctx.exp(2*jw)\\n                    T1 = ([-jw,E], [c,-1], [], [], [b-ctx.mpq_1_2, ctx.mpq_3_2-b], [], -u)\\n                    T2 = ([jw,E], [c,1], [], [], [b-ctx.mpq_1_2, ctx.mpq_3_2-b], [], u)\\n                    return T1, T2\\n                v = ctx.hypercomb(h, [], force_series=True)\\n                v = ctx.gamma(b)/(2*ctx.sqrt(ctx.pi))*v\\n            finally:\\n                ctx.prec = orig\\n            if ctx._is_real_type(b) and ctx._is_real_type(z):\\n                v = ctx._re(v)\\n            return +v\\n        except ctx.NoConvergence:\\n            pass\\n    return ctx.hypsum(0, 1, (btype,), [b], z, **kwargs)\\n\\n@defun\\ndef _hyp1f1(ctx, a_s, b_s, z, **kwargs):\\n    (a, atype), = a_s\\n    (b, btype), = b_s\\n    if not z:\\n        return ctx.one+z\\n    magz = ctx.mag(z)\\n    if magz >= 7 and not (ctx.isint(a) and ctx.re(a) <= 0):\\n        if ctx.isinf(z):\\n            if ctx.sign(a) == ctx.sign(b) == ctx.sign(z) == 1:\\n                return ctx.inf\\n            return ctx.nan * z\\n        try:\\n            try:\\n                ctx.prec += magz\\n                sector = ctx._im(z) < 0\\n                def h(a,b):\\n                    if sector:\\n                        E = ctx.expjpi(ctx.fneg(a, exact=True))\\n                    else:\\n                        E = ctx.expjpi(a)\\n                    rz = 1/z\\n                    T1 = ([E,z], [1,-a], [b], [b-a], [a, 1+a-b], [], -rz)\\n                    T2 = ([ctx.exp(z),z], [1,a-b], [b], [a], [b-a, 1-a], [], rz)\\n                    return T1, T2\\n                v = ctx.hypercomb(h, [a,b], force_series=True)\\n                if ctx._is_real_type(a) and ctx._is_real_type(b) and ctx._is_real_type(z):\\n                    v = ctx._re(v)\\n                return +v\\n            except ctx.NoConvergence:\\n                pass\\n        finally:\\n            ctx.prec -= magz\\n    v = ctx.hypsum(1, 1, (atype, btype), [a, b], z, **kwargs)\\n    return v\\n\\ndef _hyp2f1_gosper(ctx,a,b,c,z,**kwargs):\\n    # Use Gosper's recurrence\\n    # See http://www.math.utexas.edu/pipermail/maxima/2006/000126.html\\n    _a,_b,_c,_z = a, b, c, z\\n    orig = ctx.prec\\n    maxprec = kwargs.get('maxprec', 100*orig)\\n    extra = 10\\n    while 1:\\n        ctx.prec = orig + extra\\n        #a = ctx.convert(_a)\\n        #b = ctx.convert(_b)\\n        #c = ctx.convert(_c)\\n        z = ctx.convert(_z)\\n        d = ctx.mpf(0)\\n        e = ctx.mpf(1)\\n        f = ctx.mpf(0)\\n        k = 0\\n        # Common subexpression elimination, unfortunately making\\n        # things a bit unreadable. The formula is quite messy to begin\\n        # with, though...\\n        abz = a*b*z\\n        ch = c * ctx.mpq_1_2\\n        c1h = (c+1) * ctx.mpq_1_2\\n        nz = 1-z\\n        g = z/nz\\n        abg = a*b*g\\n        cba = c-b-a\\n        z2 = z-2\\n        tol = -ctx.prec - 10\\n        nstr = ctx.nstr\\n        nprint = ctx.nprint\\n        mag = ctx.mag\\n        maxmag = ctx.ninf\\n        while 1:\\n            kch = k+ch\\n            kakbz = (k+a)*(k+b)*z / (4*(k+1)*kch*(k+c1h))\\n            d1 = kakbz*(e-(k+cba)*d*g)\\n            e1 = kakbz*(d*abg+(k+c)*e)\\n            ft = d*(k*(cba*z+k*z2-c)-abz)/(2*kch*nz)\\n            f1 = f + e - ft\\n            maxmag = max(maxmag, mag(f1))\\n            if mag(f1-f) < tol:\\n                break\\n            d, e, f = d1, e1, f1\\n            k += 1\\n        cancellation = maxmag - mag(f1)\\n        if cancellation < extra:\\n            break\\n        else:\\n            extra += cancellation\\n            if extra > maxprec:\\n                raise ctx.NoConvergence\\n    return f1\\n\\n@defun\\ndef _hyp2f1(ctx, a_s, b_s, z, **kwargs):\\n    (a, atype), (b, btype) = a_s\\n    (c, ctype), = b_s\\n    if z == 1:\\n        # TODO: the following logic can be simplified\\n        convergent = ctx.re(c-a-b) > 0\\n        finite = (ctx.isint(a) and a <= 0) or (ctx.isint(b) and b <= 0)\\n        zerodiv = ctx.isint(c) and c <= 0 and not \\\\\\n            ((ctx.isint(a) and c <= a <= 0) or (ctx.isint(b) and c <= b <= 0))\\n        #print \\\"bz\\\", a, b, c, z, convergent, finite, zerodiv\\n        # Gauss's theorem gives the value if convergent\\n        if (convergent or finite) and not zerodiv:\\n            return ctx.gammaprod([c, c-a-b], [c-a, c-b], _infsign=True)\\n        # Otherwise, there is a pole and we take the\\n        # sign to be that when approaching from below\\n        # XXX: this evaluation is not necessarily correct in all cases\\n        return ctx.hyp2f1(a,b,c,1-ctx.eps*2) * ctx.inf\\n\\n    # Equal to 1 (first term), unless there is a subsequent\\n    # division by zero\\n    if not z:\\n        # Division by zero but power of z is higher than\\n        # first order so cancels\\n        if c or a == 0 or b == 0:\\n            return 1+z\\n        # Indeterminate\\n        return ctx.nan\\n\\n    # Hit zero denominator unless numerator goes to 0 first\\n    if ctx.isint(c) and c <= 0:\\n        if (ctx.isint(a) and c <= a <= 0) or \\\\\\n           (ctx.isint(b) and c <= b <= 0):\\n            pass\\n        else:\\n            # Pole in series\\n            return ctx.inf\\n\\n    absz = abs(z)\\n\\n    # Fast case: standard series converges rapidly,\\n    # possibly in finitely many terms\\n    if absz <= 0.8 or (ctx.isint(a) and a <= 0 and a >= -1000) or \\\\\\n                      (ctx.isint(b) and b <= 0 and b >= -1000):\\n        return ctx.hypsum(2, 1, (atype, btype, ctype), [a, b, c], z, **kwargs)\\n\\n    orig = ctx.prec\\n    try:\\n        ctx.prec += 10\\n\\n        # Use 1/z transformation\\n        if absz >= 1.3:\\n            def h(a,b):\\n                t = ctx.mpq_1-c; ab = a-b; rz = 1/z\\n                T1 = ([-z],[-a], [c,-ab],[b,c-a], [a,t+a],[ctx.mpq_1+ab],  rz)\\n                T2 = ([-z],[-b], [c,ab],[a,c-b], [b,t+b],[ctx.mpq_1-ab],  rz)\\n                return T1, T2\\n            v = ctx.hypercomb(h, [a,b], **kwargs)\\n\\n        # Use 1-z transformation\\n        elif abs(1-z) <= 0.75:\\n            def h(a,b):\\n                t = c-a-b; ca = c-a; cb = c-b; rz = 1-z\\n                T1 = [], [], [c,t], [ca,cb], [a,b], [1-t], rz\\n                T2 = [rz], [t], [c,a+b-c], [a,b], [ca,cb], [1+t], rz\\n                return T1, T2\\n            v = ctx.hypercomb(h, [a,b], **kwargs)\\n\\n        # Use z/(z-1) transformation\\n        elif abs(z/(z-1)) <= 0.75:\\n            v = ctx.hyp2f1(a, c-b, c, z/(z-1)) / (1-z)**a\\n\\n        # Remaining part of unit circle\\n        else:\\n            v = _hyp2f1_gosper(ctx,a,b,c,z,**kwargs)\\n\\n    finally:\\n        ctx.prec = orig\\n    return +v\\n\\n@defun\\ndef _hypq1fq(ctx, p, q, a_s, b_s, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates 3F2, 4F3, 5F4, ...\\n    \\\"\\\"\\\"\\n    a_s, a_types = zip(*a_s)\\n    b_s, b_types = zip(*b_s)\\n    a_s = list(a_s)\\n    b_s = list(b_s)\\n    absz = abs(z)\\n    ispoly = False\\n    for a in a_s:\\n        if ctx.isint(a) and a <= 0:\\n            ispoly = True\\n            break\\n    # Direct summation\\n    if absz < 1 or ispoly:\\n        try:\\n            return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs)\\n        except ctx.NoConvergence:\\n            if absz > 1.1 or ispoly:\\n                raise\\n    # Use expansion at |z-1| -> 0.\\n    # Reference: Wolfgang Buhring, \\\"Generalized Hypergeometric Functions at\\n    #   Unit Argument\\\", Proc. Amer. Math. Soc., Vol. 114, No. 1 (Jan. 1992),\\n    #   pp.145-153\\n    # The current implementation has several problems:\\n    # 1. We only implement it for 3F2. The expansion coefficients are\\n    #    given by extremely messy nested sums in the higher degree cases\\n    #    (see reference). Is efficient sequential generation of the coefficients\\n    #    possible in the > 3F2 case?\\n    # 2. Although the series converges, it may do so slowly, so we need\\n    #    convergence acceleration. The acceleration implemented by\\n    #    nsum does not always help, so results returned are sometimes\\n    #    inaccurate! Can we do better?\\n    # 3. We should check conditions for convergence, and possibly\\n    #    do a better job of cancelling out gamma poles if possible.\\n    if z == 1:\\n        # XXX: should also check for division by zero in the\\n        # denominator of the series (cf. hyp2f1)\\n        S = ctx.re(sum(b_s)-sum(a_s))\\n        if S <= 0:\\n            #return ctx.hyper(a_s, b_s, 1-ctx.eps*2, **kwargs) * ctx.inf\\n            return ctx.hyper(a_s, b_s, 0.9, **kwargs) * ctx.inf\\n    if (p,q) == (3,2) and abs(z-1) < 0.05:   # and kwargs.get('sum1')\\n        #print \\\"Using alternate summation (experimental)\\\"\\n        a1,a2,a3 = a_s\\n        b1,b2 = b_s\\n        u = b1+b2-a3\\n        initial = ctx.gammaprod([b2-a3,b1-a3,a1,a2],[b2-a3,b1-a3,1,u])\\n        def term(k, _cache={0:initial}):\\n            u = b1+b2-a3+k\\n            if k in _cache:\\n                t = _cache[k]\\n            else:\\n                t = _cache[k-1]\\n                t *= (b1+k-a3-1)*(b2+k-a3-1)\\n                t /= k*(u-1)\\n                _cache[k] = t\\n            return t * ctx.hyp2f1(a1,a2,u,z)\\n        try:\\n            S = ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'),\\n                strict=kwargs.get('strict', True))\\n            return S * ctx.gammaprod([b1,b2],[a1,a2,a3])\\n        except ctx.NoConvergence:\\n            pass\\n    # Try to use convergence acceleration on and close to the unit circle.\\n    # Problem: the convergence acceleration degenerates as |z-1| -> 0,\\n    # except for special cases. Everywhere else, the Shanks transformation\\n    # is very efficient.\\n    if absz < 1.1 and ctx._re(z) <= 1:\\n\\n        def term(kk, _cache={0:ctx.one}):\\n            k = int(kk)\\n            if k != kk:\\n                t = z ** ctx.mpf(kk) / ctx.fac(kk)\\n                for a in a_s: t *= ctx.rf(a,kk)\\n                for b in b_s: t /= ctx.rf(b,kk)\\n                return t\\n            if k in _cache:\\n                return _cache[k]\\n            t = term(k-1)\\n            m = k-1\\n            for j in xrange(p): t *= (a_s[j]+m)\\n            for j in xrange(q): t /= (b_s[j]+m)\\n            t *= z\\n            t /= k\\n            _cache[k] = t\\n            return t\\n\\n        sum_method = kwargs.get('sum_method', 'r+s+e')\\n\\n        try:\\n            return ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'),\\n                strict=kwargs.get('strict', True),\\n                method=sum_method.replace('e',''))\\n        except ctx.NoConvergence:\\n            if 'e' not in sum_method:\\n                raise\\n            pass\\n\\n        if kwargs.get('verbose'):\\n            print(\\\"Attempting Euler-Maclaurin summation\\\")\\n\\n\\n        \\\"\\\"\\\"\\n        Somewhat slower version (one diffs_exp for each factor).\\n        However, this would be faster with fast direct derivatives\\n        of the gamma function.\\n\\n        def power_diffs(k0):\\n            r = 0\\n            l = ctx.log(z)\\n            while 1:\\n                yield z**ctx.mpf(k0) * l**r\\n                r += 1\\n\\n        def loggamma_diffs(x, reciprocal=False):\\n            sign = (-1) ** reciprocal\\n            yield sign * ctx.loggamma(x)\\n            i = 0\\n            while 1:\\n                yield sign * ctx.psi(i,x)\\n                i += 1\\n\\n        def hyper_diffs(k0):\\n            b2 = b_s + [1]\\n            A = [ctx.diffs_exp(loggamma_diffs(a+k0)) for a in a_s]\\n            B = [ctx.diffs_exp(loggamma_diffs(b+k0,True)) for b in b2]\\n            Z = [power_diffs(k0)]\\n            C = ctx.gammaprod([b for b in b2], [a for a in a_s])\\n            for d in ctx.diffs_prod(A + B + Z):\\n                v = C * d\\n                yield v\\n        \\\"\\\"\\\"\\n\\n        def log_diffs(k0):\\n            b2 = b_s + [1]\\n            yield sum(ctx.loggamma(a+k0) for a in a_s) - \\\\\\n                sum(ctx.loggamma(b+k0) for b in b2) + k0*ctx.log(z)\\n            i = 0\\n            while 1:\\n                v = sum(ctx.psi(i,a+k0) for a in a_s) - \\\\\\n                    sum(ctx.psi(i,b+k0) for b in b2)\\n                if i == 0:\\n                    v += ctx.log(z)\\n                yield v\\n                i += 1\\n\\n        def hyper_diffs(k0):\\n            C = ctx.gammaprod([b for b in b_s], [a for a in a_s])\\n            for d in ctx.diffs_exp(log_diffs(k0)):\\n                v = C * d\\n                yield v\\n\\n        tol = ctx.eps / 1024\\n        prec = ctx.prec\\n        try:\\n            trunc = 50 * ctx.dps\\n            ctx.prec += 20\\n            for i in xrange(5):\\n                head = ctx.fsum(term(k) for k in xrange(trunc))\\n                tail, err = ctx.sumem(term, [trunc, ctx.inf], tol=tol,\\n                    adiffs=hyper_diffs(trunc),\\n                    verbose=kwargs.get('verbose'),\\n                    error=True,\\n                    _fast_abort=True)\\n                if err < tol:\\n                    v = head + tail\\n                    break\\n                trunc *= 2\\n                # Need to increase precision because calculation of\\n                # derivatives may be inaccurate\\n                ctx.prec += ctx.prec//2\\n                if i == 4:\\n                    raise ctx.NoConvergence(\\\\\\n                        \\\"Euler-Maclaurin summation did not converge\\\")\\n        finally:\\n            ctx.prec = prec\\n        return +v\\n\\n    # Use 1/z transformation\\n    # http://functions.wolfram.com/HypergeometricFunctions/\\n    #   HypergeometricPFQ/06/01/05/02/0004/\\n    def h(*args):\\n        a_s = list(args[:p])\\n        b_s = list(args[p:])\\n        Ts = []\\n        recz = ctx.one/z\\n        negz = ctx.fneg(z, exact=True)\\n        for k in range(q+1):\\n            ak = a_s[k]\\n            C = [negz]\\n            Cp = [-ak]\\n            Gn = b_s + [ak] + [a_s[j]-ak for j in range(q+1) if j != k]\\n            Gd = a_s + [b_s[j]-ak for j in range(q)]\\n            Fn = [ak] + [ak-b_s[j]+1 for j in range(q)]\\n            Fd = [1-a_s[j]+ak for j in range(q+1) if j != k]\\n            Ts.append((C, Cp, Gn, Gd, Fn, Fd, recz))\\n        return Ts\\n    return ctx.hypercomb(h, a_s+b_s, **kwargs)\\n\\n@defun\\ndef _hyp_borel(ctx, p, q, a_s, b_s, z, **kwargs):\\n    if a_s:\\n        a_s, a_types = zip(*a_s)\\n        a_s = list(a_s)\\n    else:\\n        a_s, a_types = [], ()\\n    if b_s:\\n        b_s, b_types = zip(*b_s)\\n        b_s = list(b_s)\\n    else:\\n        b_s, b_types = [], ()\\n    kwargs['maxterms'] = kwargs.get('maxterms', ctx.prec)\\n    try:\\n        return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs)\\n    except ctx.NoConvergence:\\n        pass\\n    prec = ctx.prec\\n    try:\\n        tol = kwargs.get('asymp_tol', ctx.eps/4)\\n        ctx.prec += 10\\n        # hypsum is has a conservative tolerance. So we try again:\\n        def term(k, cache={0:ctx.one}):\\n            if k in cache:\\n                return cache[k]\\n            t = term(k-1)\\n            for a in a_s: t *= (a+(k-1))\\n            for b in b_s: t /= (b+(k-1))\\n            t *= z\\n            t /= k\\n            cache[k] = t\\n            return t\\n        s = ctx.one\\n        for k in xrange(1, ctx.prec):\\n            t = term(k)\\n            s += t\\n            if abs(t) <= tol:\\n                return s\\n    finally:\\n        ctx.prec = prec\\n    if p <= q+3:\\n        contour = kwargs.get('contour')\\n        if not contour:\\n            if ctx.arg(z) < 0.25:\\n                u = z / max(1, abs(z))\\n                if ctx.arg(z) >= 0:\\n                    contour = [0, 2j, (2j+2)/u, 2/u, ctx.inf]\\n                else:\\n                    contour = [0, -2j, (-2j+2)/u, 2/u, ctx.inf]\\n                #contour = [0, 2j/z, 2/z, ctx.inf]\\n                #contour = [0, 2j, 2/z, ctx.inf]\\n                #contour = [0, 2j, ctx.inf]\\n            else:\\n                contour = [0, ctx.inf]\\n        quad_kwargs = kwargs.get('quad_kwargs', {})\\n        def g(t):\\n            return ctx.exp(-t)*ctx.hyper(a_s, b_s+[1], t*z)\\n        I, err = ctx.quad(g, contour, error=True, **quad_kwargs)\\n        if err <= abs(I)*ctx.eps*8:\\n            return I\\n    raise ctx.NoConvergence\\n\\n\\n@defun\\ndef _hyp2f2(ctx, a_s, b_s, z, **kwargs):\\n    (a1, a1type), (a2, a2type) = a_s\\n    (b1, b1type), (b2, b2type) = b_s\\n\\n    absz = abs(z)\\n    magz = ctx.mag(z)\\n    orig = ctx.prec\\n\\n    # Asymptotic expansion is ~ exp(z)\\n    asymp_extraprec = magz\\n\\n    # Asymptotic series is in terms of 3F1\\n    can_use_asymptotic = (not kwargs.get('force_series')) and \\\\\\n        (ctx.mag(absz) > 3)\\n\\n    # TODO: much of the following could be shared with 2F3 instead of\\n    # copypasted\\n    if can_use_asymptotic:\\n        #print \\\"using asymp\\\"\\n        try:\\n            try:\\n                ctx.prec += asymp_extraprec\\n                # http://functions.wolfram.com/HypergeometricFunctions/\\n                # Hypergeometric2F2/06/02/02/0002/\\n                def h(a1,a2,b1,b2):\\n                    X = a1+a2-b1-b2\\n                    A2 = a1+a2\\n                    B2 = b1+b2\\n                    c = {}\\n                    c[0] = ctx.one\\n                    c[1] = (A2-1)*X+b1*b2-a1*a2\\n                    s1 = 0\\n                    k = 0\\n                    tprev = 0\\n                    while 1:\\n                        if k not in c:\\n                            uu1 = 1-B2+2*a1+a1**2+2*a2+a2**2-A2*B2+a1*a2+b1*b2+(2*B2-3*(A2+1))*k+2*k**2\\n                            uu2 = (k-A2+b1-1)*(k-A2+b2-1)*(k-X-2)\\n                            c[k] = ctx.one/k * (uu1*c[k-1]-uu2*c[k-2])\\n                        t1 = c[k] * z**(-k)\\n                        if abs(t1) < 0.1*ctx.eps:\\n                            #print \\\"Convergence :)\\\"\\n                            break\\n                        # Quit if the series doesn't converge quickly enough\\n                        if k > 5 and abs(tprev) / abs(t1) < 1.5:\\n                            #print \\\"No convergence :(\\\"\\n                            raise ctx.NoConvergence\\n                        s1 += t1\\n                        tprev = t1\\n                        k += 1\\n                    S = ctx.exp(z)*s1\\n                    T1 = [z,S], [X,1], [b1,b2],[a1,a2],[],[],0\\n                    T2 = [-z],[-a1],[b1,b2,a2-a1],[a2,b1-a1,b2-a1],[a1,a1-b1+1,a1-b2+1],[a1-a2+1],-1/z\\n                    T3 = [-z],[-a2],[b1,b2,a1-a2],[a1,b1-a2,b2-a2],[a2,a2-b1+1,a2-b2+1],[-a1+a2+1],-1/z\\n                    return T1, T2, T3\\n                v = ctx.hypercomb(h, [a1,a2,b1,b2], force_series=True, maxterms=4*ctx.prec)\\n                if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,z]) == 5:\\n                    v = ctx.re(v)\\n                return v\\n            except ctx.NoConvergence:\\n                pass\\n        finally:\\n            ctx.prec = orig\\n\\n    return ctx.hypsum(2, 2, (a1type, a2type, b1type, b2type), [a1, a2, b1, b2], z, **kwargs)\\n\\n\\n\\n@defun\\ndef _hyp1f2(ctx, a_s, b_s, z, **kwargs):\\n    (a1, a1type), = a_s\\n    (b1, b1type), (b2, b2type) = b_s\\n\\n    absz = abs(z)\\n    magz = ctx.mag(z)\\n    orig = ctx.prec\\n\\n    # Asymptotic expansion is ~ exp(sqrt(z))\\n    asymp_extraprec = z and magz//2\\n\\n    # Asymptotic series is in terms of 3F0\\n    can_use_asymptotic = (not kwargs.get('force_series')) and \\\\\\n        (ctx.mag(absz) > 19) and \\\\\\n        (ctx.sqrt(absz) > 1.5*orig)  # and \\\\\\n    #   ctx._hyp_check_convergence([a1, a1-b1+1, a1-b2+1], [],\\n    #                              1/absz, orig+40+asymp_extraprec)\\n\\n    # TODO: much of the following could be shared with 2F3 instead of\\n    # copypasted\\n    if can_use_asymptotic:\\n        #print \\\"using asymp\\\"\\n        try:\\n            try:\\n                ctx.prec += asymp_extraprec\\n                # http://functions.wolfram.com/HypergeometricFunctions/\\n                # Hypergeometric1F2/06/02/03/\\n                def h(a1,b1,b2):\\n                    X = ctx.mpq_1_2*(a1-b1-b2+ctx.mpq_1_2)\\n                    c = {}\\n                    c[0] = ctx.one\\n                    c[1] = 2*(ctx.mpq_1_4*(3*a1+b1+b2-2)*(a1-b1-b2)+b1*b2-ctx.mpq_3_16)\\n                    c[2] = 2*(b1*b2+ctx.mpq_1_4*(a1-b1-b2)*(3*a1+b1+b2-2)-ctx.mpq_3_16)**2+\\\\\\n                        ctx.mpq_1_16*(-16*(2*a1-3)*b1*b2 + \\\\\\n                        4*(a1-b1-b2)*(-8*a1**2+11*a1+b1+b2-2)-3)\\n                    s1 = 0\\n                    s2 = 0\\n                    k = 0\\n                    tprev = 0\\n                    while 1:\\n                        if k not in c:\\n                            uu1 = (3*k**2+(-6*a1+2*b1+2*b2-4)*k + 3*a1**2 - \\\\\\n                                (b1-b2)**2 - 2*a1*(b1+b2-2) + ctx.mpq_1_4)\\n                            uu2 = (k-a1+b1-b2-ctx.mpq_1_2)*(k-a1-b1+b2-ctx.mpq_1_2)*\\\\\\n                                (k-a1+b1+b2-ctx.mpq_5_2)\\n                            c[k] = ctx.one/(2*k)*(uu1*c[k-1]-uu2*c[k-2])\\n                        w = c[k] * (-z)**(-0.5*k)\\n                        t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w\\n                        t2 = ctx.j**k * ctx.mpf(2)**(-k) * w\\n                        if abs(t1) < 0.1*ctx.eps:\\n                            #print \\\"Convergence :)\\\"\\n                            break\\n                        # Quit if the series doesn't converge quickly enough\\n                        if k > 5 and abs(tprev) / abs(t1) < 1.5:\\n                            #print \\\"No convergence :(\\\"\\n                            raise ctx.NoConvergence\\n                        s1 += t1\\n                        s2 += t2\\n                        tprev = t1\\n                        k += 1\\n                    S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \\\\\\n                        ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2\\n                    T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2], [a1],\\\\\\n                        [], [], 0\\n                    T2 = [-z], [-a1], [b1,b2],[b1-a1,b2-a1], \\\\\\n                        [a1,a1-b1+1,a1-b2+1], [], 1/z\\n                    return T1, T2\\n                v = ctx.hypercomb(h, [a1,b1,b2], force_series=True, maxterms=4*ctx.prec)\\n                if sum(ctx._is_real_type(u) for u in [a1,b1,b2,z]) == 4:\\n                    v = ctx.re(v)\\n                return v\\n            except ctx.NoConvergence:\\n                pass\\n        finally:\\n            ctx.prec = orig\\n\\n    #print \\\"not using asymp\\\"\\n    return ctx.hypsum(1, 2, (a1type, b1type, b2type), [a1, b1, b2], z, **kwargs)\\n\\n\\n\\n@defun\\ndef _hyp2f3(ctx, a_s, b_s, z, **kwargs):\\n    (a1, a1type), (a2, a2type) = a_s\\n    (b1, b1type), (b2, b2type), (b3, b3type) = b_s\\n\\n    absz = abs(z)\\n    magz = ctx.mag(z)\\n\\n    # Asymptotic expansion is ~ exp(sqrt(z))\\n    asymp_extraprec = z and magz//2\\n    orig = ctx.prec\\n\\n    # Asymptotic series is in terms of 4F1\\n    # The square root below empirically provides a plausible criterion\\n    # for the leading series to converge\\n    can_use_asymptotic = (not kwargs.get('force_series')) and \\\\\\n        (ctx.mag(absz) > 19) and (ctx.sqrt(absz) > 1.5*orig)\\n\\n    if can_use_asymptotic:\\n        #print \\\"using asymp\\\"\\n        try:\\n            try:\\n                ctx.prec += asymp_extraprec\\n                # http://functions.wolfram.com/HypergeometricFunctions/\\n                # Hypergeometric2F3/06/02/03/01/0002/\\n                def h(a1,a2,b1,b2,b3):\\n                    X = ctx.mpq_1_2*(a1+a2-b1-b2-b3+ctx.mpq_1_2)\\n                    A2 = a1+a2\\n                    B3 = b1+b2+b3\\n                    A = a1*a2\\n                    B = b1*b2+b3*b2+b1*b3\\n                    R = b1*b2*b3\\n                    c = {}\\n                    c[0] = ctx.one\\n                    c[1] = 2*(B - A + ctx.mpq_1_4*(3*A2+B3-2)*(A2-B3) - ctx.mpq_3_16)\\n                    c[2] = ctx.mpq_1_2*c[1]**2 + ctx.mpq_1_16*(-16*(2*A2-3)*(B-A) + 32*R +\\\\\\n                        4*(-8*A2**2 + 11*A2 + 8*A + B3 - 2)*(A2-B3)-3)\\n                    s1 = 0\\n                    s2 = 0\\n                    k = 0\\n                    tprev = 0\\n                    while 1:\\n                        if k not in c:\\n                            uu1 = (k-2*X-3)*(k-2*X-2*b1-1)*(k-2*X-2*b2-1)*\\\\\\n                                (k-2*X-2*b3-1)\\n                            uu2 = (4*(k-1)**3 - 6*(4*X+B3)*(k-1)**2 + \\\\\\n                                2*(24*X**2+12*B3*X+4*B+B3-1)*(k-1) - 32*X**3 - \\\\\\n                                24*B3*X**2 - 4*B - 8*R - 4*(4*B+B3-1)*X + 2*B3-1)\\n                            uu3 = (5*(k-1)**2+2*(-10*X+A2-3*B3+3)*(k-1)+2*c[1])\\n                            c[k] = ctx.one/(2*k)*(uu1*c[k-3]-uu2*c[k-2]+uu3*c[k-1])\\n                        w = c[k] * ctx.power(-z, -0.5*k)\\n                        t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w\\n                        t2 = ctx.j**k * ctx.mpf(2)**(-k) * w\\n                        if abs(t1) < 0.1*ctx.eps:\\n                            break\\n                        # Quit if the series doesn't converge quickly enough\\n                        if k > 5 and abs(tprev) / abs(t1) < 1.5:\\n                            raise ctx.NoConvergence\\n                        s1 += t1\\n                        s2 += t2\\n                        tprev = t1\\n                        k += 1\\n                    S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \\\\\\n                        ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2\\n                    T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2, b3], [a1, a2],\\\\\\n                        [], [], 0\\n                    T2 = [-z], [-a1], [b1,b2,b3,a2-a1],[a2,b1-a1,b2-a1,b3-a1], \\\\\\n                        [a1,a1-b1+1,a1-b2+1,a1-b3+1], [a1-a2+1], 1/z\\n                    T3 = [-z], [-a2], [b1,b2,b3,a1-a2],[a1,b1-a2,b2-a2,b3-a2], \\\\\\n                        [a2,a2-b1+1,a2-b2+1,a2-b3+1],[-a1+a2+1], 1/z\\n                    return T1, T2, T3\\n                v = ctx.hypercomb(h, [a1,a2,b1,b2,b3], force_series=True, maxterms=4*ctx.prec)\\n                if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,b3,z]) == 6:\\n                    v = ctx.re(v)\\n                return v\\n            except ctx.NoConvergence:\\n                pass\\n        finally:\\n            ctx.prec = orig\\n\\n    return ctx.hypsum(2, 3, (a1type, a2type, b1type, b2type, b3type), [a1, a2, b1, b2, b3], z, **kwargs)\\n\\n@defun\\ndef _hyp2f0(ctx, a_s, b_s, z, **kwargs):\\n    (a, atype), (b, btype) = a_s\\n    # We want to try aggressively to use the asymptotic expansion,\\n    # and fall back only when absolutely necessary\\n    try:\\n        kwargsb = kwargs.copy()\\n        kwargsb['maxterms'] = kwargsb.get('maxterms', ctx.prec)\\n        return ctx.hypsum(2, 0, (atype,btype), [a,b], z, **kwargsb)\\n    except ctx.NoConvergence:\\n        if kwargs.get('force_series'):\\n            raise\\n        pass\\n    def h(a, b):\\n        w = ctx.sinpi(b)\\n        rz = -1/z\\n        T1 = ([ctx.pi,w,rz],[1,-1,a],[],[a-b+1,b],[a],[b],rz)\\n        T2 = ([-ctx.pi,w,rz],[1,-1,1+a-b],[],[a,2-b],[a-b+1],[2-b],rz)\\n        return T1, T2\\n    return ctx.hypercomb(h, [a, 1+a-b], **kwargs)\\n\\n@defun\\ndef meijerg(ctx, a_s, b_s, z, r=1, series=None, **kwargs):\\n    an, ap = a_s\\n    bm, bq = b_s\\n    n = len(an)\\n    p = n + len(ap)\\n    m = len(bm)\\n    q = m + len(bq)\\n    a = an+ap\\n    b = bm+bq\\n    a = [ctx.convert(_) for _ in a]\\n    b = [ctx.convert(_) for _ in b]\\n    z = ctx.convert(z)\\n    if series is None:\\n        if p < q: series = 1\\n        if p > q: series = 2\\n        if p == q:\\n            if m+n == p and abs(z) > 1:\\n                series = 2\\n            else:\\n                series = 1\\n    if kwargs.get('verbose'):\\n        print(\\\"Meijer G m,n,p,q,series =\\\", m,n,p,q,series)\\n    if series == 1:\\n        def h(*args):\\n            a = args[:p]\\n            b = args[p:]\\n            terms = []\\n            for k in range(m):\\n                bases = [z]\\n                expts = [b[k]/r]\\n                gn = [b[j]-b[k] for j in range(m) if j != k]\\n                gn += [1-a[j]+b[k] for j in range(n)]\\n                gd = [a[j]-b[k] for j in range(n,p)]\\n                gd += [1-b[j]+b[k] for j in range(m,q)]\\n                hn = [1-a[j]+b[k] for j in range(p)]\\n                hd = [1-b[j]+b[k] for j in range(q) if j != k]\\n                hz = (-ctx.one)**(p-m-n) * z**(ctx.one/r)\\n                terms.append((bases, expts, gn, gd, hn, hd, hz))\\n            return terms\\n    else:\\n        def h(*args):\\n            a = args[:p]\\n            b = args[p:]\\n            terms = []\\n            for k in range(n):\\n                bases = [z]\\n                if r == 1:\\n                    expts = [a[k]-1]\\n                else:\\n                    expts = [(a[k]-1)/ctx.convert(r)]\\n                gn = [a[k]-a[j] for j in range(n) if j != k]\\n                gn += [1-a[k]+b[j] for j in range(m)]\\n                gd = [a[k]-b[j] for j in range(m,q)]\\n                gd += [1-a[k]+a[j] for j in range(n,p)]\\n                hn = [1-a[k]+b[j] for j in range(q)]\\n                hd = [1+a[j]-a[k] for j in range(p) if j != k]\\n                hz = (-ctx.one)**(q-m-n) / z**(ctx.one/r)\\n                terms.append((bases, expts, gn, gd, hn, hd, hz))\\n            return terms\\n    return ctx.hypercomb(h, a+b, **kwargs)\\n\\n@defun_wrapped\\ndef appellf1(ctx,a,b1,b2,c,x,y,**kwargs):\\n    # Assume x smaller\\n    # We will use x for the outer loop\\n    if abs(x) > abs(y):\\n        x, y = y, x\\n        b1, b2 = b2, b1\\n    def ok(x):\\n        return abs(x) < 0.99\\n    # Finite cases\\n    if ctx.isnpint(a):\\n        pass\\n    elif ctx.isnpint(b1):\\n        pass\\n    elif ctx.isnpint(b2):\\n        x, y, b1, b2 = y, x, b2, b1\\n    else:\\n        #print x, y\\n        # Note: ok if |y| > 1, because\\n        # 2F1 implements analytic continuation\\n        if not ok(x):\\n            u1 = (x-y)/(x-1)\\n            if not ok(u1):\\n                raise ValueError(\\\"Analytic continuation not implemented\\\")\\n            #print \\\"Using analytic continuation\\\"\\n            return (1-x)**(-b1)*(1-y)**(c-a-b2)*\\\\\\n                ctx.appellf1(c-a,b1,c-b1-b2,c,u1,y,**kwargs)\\n    return ctx.hyper2d({'m+n':[a],'m':[b1],'n':[b2]}, {'m+n':[c]}, x,y, **kwargs)\\n\\n@defun\\ndef appellf2(ctx,a,b1,b2,c1,c2,x,y,**kwargs):\\n    # TODO: continuation\\n    return ctx.hyper2d({'m+n':[a],'m':[b1],'n':[b2]},\\n        {'m':[c1],'n':[c2]}, x,y, **kwargs)\\n\\n@defun\\ndef appellf3(ctx,a1,a2,b1,b2,c,x,y,**kwargs):\\n    outer_polynomial = ctx.isnpint(a1) or ctx.isnpint(b1)\\n    inner_polynomial = ctx.isnpint(a2) or ctx.isnpint(b2)\\n    if not outer_polynomial:\\n        if inner_polynomial or abs(x) > abs(y):\\n            x, y = y, x\\n            a1,a2,b1,b2 = a2,a1,b2,b1\\n    return ctx.hyper2d({'m':[a1,b1],'n':[a2,b2]}, {'m+n':[c]},x,y,**kwargs)\\n\\n@defun\\ndef appellf4(ctx,a,b,c1,c2,x,y,**kwargs):\\n    # TODO: continuation\\n    return ctx.hyper2d({'m+n':[a,b]}, {'m':[c1],'n':[c2]},x,y,**kwargs)\\n\\n@defun\\ndef hyper2d(ctx, a, b, x, y, **kwargs):\\n    r\\\"\\\"\\\"\\n    Sums the generalized 2D hypergeometric series\\n\\n    .. math ::\\n\\n        \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n            \\\\frac{P((a),m,n)}{Q((b),m,n)}\\n            \\\\frac{x^m y^n} {m! n!}\\n\\n    where `(a) = (a_1,\\\\ldots,a_r)`, `(b) = (b_1,\\\\ldots,b_s)` and where\\n    `P` and `Q` are products of rising factorials such as `(a_j)_n` or\\n    `(a_j)_{m+n}`. `P` and `Q` are specified in the form of dicts, with\\n    the `m` and `n` dependence as keys and parameter lists as values.\\n    The supported rising factorials are given in the following table\\n    (note that only a few are supported in `Q`):\\n\\n    +------------+-------------------+--------+\\n    | Key        |  Rising factorial | `Q`    |\\n    +============+===================+========+\\n    | ``'m'``    |   `(a_j)_m`       | Yes    |\\n    +------------+-------------------+--------+\\n    | ``'n'``    |   `(a_j)_n`       | Yes    |\\n    +------------+-------------------+--------+\\n    | ``'m+n'``  |   `(a_j)_{m+n}`   | Yes    |\\n    +------------+-------------------+--------+\\n    | ``'m-n'``  |   `(a_j)_{m-n}`   | No     |\\n    +------------+-------------------+--------+\\n    | ``'n-m'``  |   `(a_j)_{n-m}`   | No     |\\n    +------------+-------------------+--------+\\n    | ``'2m+n'`` |   `(a_j)_{2m+n}`  | No     |\\n    +------------+-------------------+--------+\\n    | ``'2m-n'`` |   `(a_j)_{2m-n}`  | No     |\\n    +------------+-------------------+--------+\\n    | ``'2n-m'`` |   `(a_j)_{2n-m}`  | No     |\\n    +------------+-------------------+--------+\\n\\n    For example, the Appell F1 and F4 functions\\n\\n    .. math ::\\n\\n        F_1 = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n              \\\\frac{(a)_{m+n} (b)_m (c)_n}{(d)_{m+n}}\\n              \\\\frac{x^m y^n}{m! n!}\\n\\n        F_4 = \\\\sum_{m=0}^{\\\\infty} \\\\sum_{n=0}^{\\\\infty}\\n              \\\\frac{(a)_{m+n} (b)_{m+n}}{(c)_m (d)_{n}}\\n              \\\\frac{x^m y^n}{m! n!}\\n\\n    can be represented respectively as\\n\\n        ``hyper2d({'m+n':[a], 'm':[b], 'n':[c]}, {'m+n':[d]}, x, y)``\\n\\n        ``hyper2d({'m+n':[a,b]}, {'m':[c], 'n':[d]}, x, y)``\\n\\n    More generally, :func:`~mpmath.hyper2d` can evaluate any of the 34 distinct\\n    convergent second-order (generalized Gaussian) hypergeometric\\n    series enumerated by Horn, as well as the Kampe de Feriet\\n    function.\\n\\n    The series is computed by rewriting it so that the inner\\n    series (i.e. the series containing `n` and `y`) has the form of an\\n    ordinary generalized hypergeometric series and thereby can be\\n    evaluated efficiently using :func:`~mpmath.hyper`. If possible,\\n    manually swapping `x` and `y` and the corresponding parameters\\n    can sometimes give better results.\\n\\n    **Examples**\\n\\n    Two separable cases: a product of two geometric series, and a\\n    product of two Gaussian hypergeometric functions::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> x, y = mpf(0.25), mpf(0.5)\\n        >>> hyper2d({'m':1,'n':1}, {}, x,y)\\n        2.666666666666666666666667\\n        >>> 1/(1-x)/(1-y)\\n        2.666666666666666666666667\\n        >>> hyper2d({'m':[1,2],'n':[3,4]}, {'m':[5],'n':[6]}, x,y)\\n        4.164358531238938319669856\\n        >>> hyp2f1(1,2,5,x)*hyp2f1(3,4,6,y)\\n        4.164358531238938319669856\\n\\n    Some more series that can be done in closed form::\\n\\n        >>> hyper2d({'m':1,'n':1},{'m+n':1},x,y)\\n        2.013417124712514809623881\\n        >>> (exp(x)*x-exp(y)*y)/(x-y)\\n        2.013417124712514809623881\\n\\n    Six of the 34 Horn functions, G1-G3 and H1-H3::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 10; mp.pretty = True\\n        >>> x, y = 0.0625, 0.125\\n        >>> a1,a2,b1,b2,c1,c2,d = 1.1,-1.2,-1.3,-1.4,1.5,-1.6,1.7\\n        >>> hyper2d({'m+n':a1,'n-m':b1,'m-n':b2},{},x,y)  # G1\\n        1.139090746\\n        >>> nsum(lambda m,n: rf(a1,m+n)*rf(b1,n-m)*rf(b2,m-n)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        1.139090746\\n        >>> hyper2d({'m':a1,'n':a2,'n-m':b1,'m-n':b2},{},x,y)  # G2\\n        0.9503682696\\n        >>> nsum(lambda m,n: rf(a1,m)*rf(a2,n)*rf(b1,n-m)*rf(b2,m-n)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        0.9503682696\\n        >>> hyper2d({'2n-m':a1,'2m-n':a2},{},x,y)  # G3\\n        1.029372029\\n        >>> nsum(lambda m,n: rf(a1,2*n-m)*rf(a2,2*m-n)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        1.029372029\\n        >>> hyper2d({'m-n':a1,'m+n':b1,'n':c1},{'m':d},x,y)  # H1\\n        -1.605331256\\n        >>> nsum(lambda m,n: rf(a1,m-n)*rf(b1,m+n)*rf(c1,n)/rf(d,m)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        -1.605331256\\n        >>> hyper2d({'m-n':a1,'m':b1,'n':[c1,c2]},{'m':d},x,y)  # H2\\n        -2.35405404\\n        >>> nsum(lambda m,n: rf(a1,m-n)*rf(b1,m)*rf(c1,n)*rf(c2,n)/rf(d,m)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        -2.35405404\\n        >>> hyper2d({'2m+n':a1,'n':b1},{'m+n':c1},x,y)  # H3\\n        0.974479074\\n        >>> nsum(lambda m,n: rf(a1,2*m+n)*rf(b1,n)/rf(c1,m+n)*\\\\\\n        ...     x**m*y**n/fac(m)/fac(n), [0,inf], [0,inf])\\n        0.974479074\\n\\n    **References**\\n\\n    1. [SrivastavaKarlsson]_\\n    2. [Weisstein]_ http://mathworld.wolfram.com/HornFunction.html\\n    3. [Weisstein]_ http://mathworld.wolfram.com/AppellHypergeometricFunction.html\\n\\n    \\\"\\\"\\\"\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    def parse(dct, key):\\n        args = dct.pop(key, [])\\n        try:\\n            args = list(args)\\n        except TypeError:\\n            args = [args]\\n        return [ctx.convert(arg) for arg in args]\\n    a_s = dict(a)\\n    b_s = dict(b)\\n    a_m = parse(a, 'm')\\n    a_n = parse(a, 'n')\\n    a_m_add_n = parse(a, 'm+n')\\n    a_m_sub_n = parse(a, 'm-n')\\n    a_n_sub_m = parse(a, 'n-m')\\n    a_2m_add_n = parse(a, '2m+n')\\n    a_2m_sub_n = parse(a, '2m-n')\\n    a_2n_sub_m = parse(a, '2n-m')\\n    b_m = parse(b, 'm')\\n    b_n = parse(b, 'n')\\n    b_m_add_n = parse(b, 'm+n')\\n    if a: raise ValueError(\\\"unsupported key: %r\\\" % a.keys()[0])\\n    if b: raise ValueError(\\\"unsupported key: %r\\\" % b.keys()[0])\\n    s = 0\\n    outer = ctx.one\\n    m = ctx.mpf(0)\\n    ok_count = 0\\n    prec = ctx.prec\\n    maxterms = kwargs.get('maxterms', 20*prec)\\n    try:\\n        ctx.prec += 10\\n        tol = +ctx.eps\\n        while 1:\\n            inner_sign = 1\\n            outer_sign = 1\\n            inner_a = list(a_n)\\n            inner_b = list(b_n)\\n            outer_a = [a+m for a in a_m]\\n            outer_b = [b+m for b in b_m]\\n            # (a)_{m+n} = (a)_m (a+m)_n\\n            for a in a_m_add_n:\\n                a = a+m\\n                inner_a.append(a)\\n                outer_a.append(a)\\n            # (b)_{m+n} = (b)_m (b+m)_n\\n            for b in b_m_add_n:\\n                b = b+m\\n                inner_b.append(b)\\n                outer_b.append(b)\\n            # (a)_{n-m} = (a-m)_n / (a-m)_m\\n            for a in a_n_sub_m:\\n                inner_a.append(a-m)\\n                outer_b.append(a-m-1)\\n            # (a)_{m-n} = (-1)^(m+n) (1-a-m)_m / (1-a-m)_n\\n            for a in a_m_sub_n:\\n                inner_sign *= (-1)\\n                outer_sign *= (-1)**(m)\\n                inner_b.append(1-a-m)\\n                outer_a.append(-a-m)\\n            # (a)_{2m+n} = (a)_{2m} (a+2m)_n\\n            for a in a_2m_add_n:\\n                inner_a.append(a+2*m)\\n                outer_a.append((a+2*m)*(1+a+2*m))\\n            # (a)_{2m-n} = (-1)^(2m+n) (1-a-2m)_{2m} / (1-a-2m)_n\\n            for a in a_2m_sub_n:\\n                inner_sign *= (-1)\\n                inner_b.append(1-a-2*m)\\n                outer_a.append((a+2*m)*(1+a+2*m))\\n            # (a)_{2n-m} = 4^n ((a-m)/2)_n ((a-m+1)/2)_n / (a-m)_m\\n            for a in a_2n_sub_m:\\n                inner_sign *= 4\\n                inner_a.append(0.5*(a-m))\\n                inner_a.append(0.5*(a-m+1))\\n                outer_b.append(a-m-1)\\n            inner = ctx.hyper(inner_a, inner_b, inner_sign*y,\\n                zeroprec=ctx.prec, **kwargs)\\n            term = outer * inner * outer_sign\\n            if abs(term) < tol:\\n                ok_count += 1\\n            else:\\n                ok_count = 0\\n            if ok_count >= 3 or not outer:\\n                break\\n            s += term\\n            for a in outer_a: outer *= a\\n            for b in outer_b: outer /= b\\n            m += 1\\n            outer = outer * x / m\\n            if m > maxterms:\\n                raise ctx.NoConvergence(\\\"maxterms exceeded in hyper2d\\\")\\n    finally:\\n        ctx.prec = prec\\n    return +s\\n\\n\\\"\\\"\\\"\\n@defun\\ndef kampe_de_feriet(ctx,a,b,c,d,e,f,x,y,**kwargs):\\n    return ctx.hyper2d({'m+n':a,'m':b,'n':c},\\n        {'m+n':d,'m':e,'n':f}, x,y, **kwargs)\\n\\\"\\\"\\\"\\n\\n@defun\\ndef bihyper(ctx, a_s, b_s, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the bilateral hypergeometric series\\n\\n    .. math ::\\n\\n        \\\\,_AH_B(a_1, \\\\ldots, a_k; b_1, \\\\ldots, b_B; z) =\\n            \\\\sum_{n=-\\\\infty}^{\\\\infty}\\n            \\\\frac{(a_1)_n \\\\ldots (a_A)_n}\\n                 {(b_1)_n \\\\ldots (b_B)_n} \\\\, z^n\\n\\n    where, for direct convergence, `A = B` and `|z| = 1`, although a\\n    regularized sum exists more generally by considering the\\n    bilateral series as a sum of two ordinary hypergeometric\\n    functions. In order for the series to make sense, none of the\\n    parameters may be integers.\\n\\n    **Examples**\\n\\n    The value of `\\\\,_2H_2` at `z = 1` is given by Dougall's formula::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> a,b,c,d = 0.5, 1.5, 2.25, 3.25\\n        >>> bihyper([a,b],[c,d],1)\\n        -14.49118026212345786148847\\n        >>> gammaprod([c,d,1-a,1-b,c+d-a-b-1],[c-a,d-a,c-b,d-b])\\n        -14.49118026212345786148847\\n\\n    The regularized function `\\\\,_1H_0` can be expressed as the\\n    sum of one `\\\\,_2F_0` function and one `\\\\,_1F_1` function::\\n\\n        >>> a = mpf(0.25)\\n        >>> z = mpf(0.75)\\n        >>> bihyper([a], [], z)\\n        (0.2454393389657273841385582 + 0.2454393389657273841385582j)\\n        >>> hyper([a,1],[],z) + (hyper([1],[1-a],-1/z)-1)\\n        (0.2454393389657273841385582 + 0.2454393389657273841385582j)\\n        >>> hyper([a,1],[],z) + hyper([1],[2-a],-1/z)/z/(a-1)\\n        (0.2454393389657273841385582 + 0.2454393389657273841385582j)\\n\\n    **References**\\n\\n    1. [Slater]_ (chapter 6: \\\"Bilateral Series\\\", pp. 180-189)\\n    2. [Wikipedia]_ http://en.wikipedia.org/wiki/Bilateral_hypergeometric_series\\n\\n    \\\"\\\"\\\"\\n    z = ctx.convert(z)\\n    c_s = a_s + b_s\\n    p = len(a_s)\\n    q = len(b_s)\\n    if (p, q) == (0,0) or (p, q) == (1,1):\\n        return ctx.zero * z\\n    neg = (p-q) % 2\\n    def h(*c_s):\\n        a_s = list(c_s[:p])\\n        b_s = list(c_s[p:])\\n        aa_s = [2-b for b in b_s]\\n        bb_s = [2-a for a in a_s]\\n        rp = [(-1)**neg * z] + [1-b for b in b_s] + [1-a for a in a_s]\\n        rc = [-1] + [1]*len(b_s) + [-1]*len(a_s)\\n        T1 = [], [], [], [], a_s + [1], b_s, z\\n        T2 = rp, rc, [], [], aa_s + [1], bb_s, (-1)**neg / z\\n        return T1, T2\\n    return ctx.hypercomb(h, c_s, **kwargs)\\n\\n\\nfrom __future__ import print_function\\n\\nfrom ..libmp.backend import xrange\\nfrom .functions import defun, defun_wrapped, defun_static\\n\\n@defun\\ndef stieltjes(ctx, n, a=1):\\n    n = ctx.convert(n)\\n    a = ctx.convert(a)\\n    if n < 0:\\n        return ctx.bad_domain(\\\"Stieltjes constants defined for n >= 0\\\")\\n    if hasattr(ctx, \\\"stieltjes_cache\\\"):\\n        stieltjes_cache = ctx.stieltjes_cache\\n    else:\\n        stieltjes_cache = ctx.stieltjes_cache = {}\\n    if a == 1:\\n        if n == 0:\\n            return +ctx.euler\\n        if n in stieltjes_cache:\\n            prec, s = stieltjes_cache[n]\\n            if prec >= ctx.prec:\\n                return +s\\n    mag = 1\\n    def f(x):\\n        xa = x/a\\n        v = (xa-ctx.j)*ctx.ln(a-ctx.j*x)**n/(1+xa**2)/(ctx.exp(2*ctx.pi*x)-1)\\n        return ctx._re(v) / mag\\n    orig = ctx.prec\\n    try:\\n        # Normalize integrand by approx. magnitude to\\n        # speed up quadrature (which uses absolute error)\\n        if n > 50:\\n            ctx.prec = 20\\n            mag = ctx.quad(f, [0,ctx.inf], maxdegree=3)\\n        ctx.prec = orig + 10 + int(n**0.5)\\n        s = ctx.quad(f, [0,ctx.inf], maxdegree=20)\\n        v = ctx.ln(a)**n/(2*a) - ctx.ln(a)**(n+1)/(n+1) + 2*s/a*mag\\n    finally:\\n        ctx.prec = orig\\n    if a == 1 and ctx.isint(n):\\n        stieltjes_cache[n] = (ctx.prec, v)\\n    return +v\\n\\n@defun_wrapped\\ndef siegeltheta(ctx, t, derivative=0):\\n    d = int(derivative)\\n    if  (t == ctx.inf or t == ctx.ninf):\\n        if d < 2:\\n            if t == ctx.ninf and d == 0:\\n                return ctx.ninf\\n            return ctx.inf\\n        else:\\n            return ctx.zero\\n    if d == 0:\\n        if ctx._im(t):\\n            # XXX: cancellation occurs\\n            a = ctx.loggamma(0.25+0.5j*t)\\n            b = ctx.loggamma(0.25-0.5j*t)\\n            return -ctx.ln(ctx.pi)/2*t - 0.5j*(a-b)\\n        else:\\n            if ctx.isinf(t):\\n                return t\\n            return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t\\n    if d > 0:\\n        a = (-0.5j)**(d-1)*ctx.polygamma(d-1, 0.25-0.5j*t)\\n        b = (0.5j)**(d-1)*ctx.polygamma(d-1, 0.25+0.5j*t)\\n        if ctx._im(t):\\n            if d == 1:\\n                return -0.5*ctx.log(ctx.pi)+0.25*(a+b)\\n            else:\\n                return 0.25*(a+b)\\n        else:\\n            if d == 1:\\n                return ctx._re(-0.5*ctx.log(ctx.pi)+0.25*(a+b))\\n            else:\\n                return ctx._re(0.25*(a+b))\\n\\n@defun_wrapped\\ndef grampoint(ctx, n):\\n    # asymptotic expansion, from\\n    # http://mathworld.wolfram.com/GramPoint.html\\n    g = 2*ctx.pi*ctx.exp(1+ctx.lambertw((8*n+1)/(8*ctx.e)))\\n    return ctx.findroot(lambda t: ctx.siegeltheta(t)-ctx.pi*n, g)\\n\\n\\n@defun_wrapped\\ndef siegelz(ctx, t, **kwargs):\\n    d = int(kwargs.get(\\\"derivative\\\", 0))\\n    t = ctx.convert(t)\\n    t1 = ctx._re(t)\\n    t2 = ctx._im(t)\\n    prec = ctx.prec\\n    try:\\n        if abs(t1) > 500*prec and t2**2 < t1:\\n            v = ctx.rs_z(t, d)\\n            if ctx._is_real_type(t):\\n                return ctx._re(v)\\n            return v\\n    except NotImplementedError:\\n        pass\\n    ctx.prec += 21\\n    e1 = ctx.expj(ctx.siegeltheta(t))\\n    z = ctx.zeta(0.5+ctx.j*t)\\n    if d == 0:\\n        v = e1*z\\n        ctx.prec=prec\\n        if ctx._is_real_type(t):\\n            return ctx._re(v)\\n        return +v\\n    z1 = ctx.zeta(0.5+ctx.j*t, derivative=1)\\n    theta1 = ctx.siegeltheta(t, derivative=1)\\n    if d == 1:\\n        v =  ctx.j*e1*(z1+z*theta1)\\n        ctx.prec=prec\\n        if ctx._is_real_type(t):\\n            return ctx._re(v)\\n        return +v\\n    z2 = ctx.zeta(0.5+ctx.j*t, derivative=2)\\n    theta2 = ctx.siegeltheta(t, derivative=2)\\n    comb1 = theta1**2-ctx.j*theta2\\n    if d == 2:\\n        def terms():\\n            return [2*z1*theta1, z2, z*comb1]\\n        v = ctx.sum_accurately(terms, 1)\\n        v =  -e1*v\\n        ctx.prec = prec\\n        if ctx._is_real_type(t):\\n            return ctx._re(v)\\n        return +v\\n    ctx.prec += 10\\n    z3 = ctx.zeta(0.5+ctx.j*t, derivative=3)\\n    theta3 = ctx.siegeltheta(t, derivative=3)\\n    comb2 = theta1**3-3*ctx.j*theta1*theta2-theta3\\n    if d == 3:\\n        def terms():\\n            return  [3*theta1*z2, 3*z1*comb1, z3+z*comb2]\\n        v = ctx.sum_accurately(terms, 1)\\n        v =  -ctx.j*e1*v\\n        ctx.prec = prec\\n        if ctx._is_real_type(t):\\n            return ctx._re(v)\\n        return +v\\n    z4 = ctx.zeta(0.5+ctx.j*t, derivative=4)\\n    theta4 = ctx.siegeltheta(t, derivative=4)\\n    def terms():\\n        return [theta1**4, -6*ctx.j*theta1**2*theta2, -3*theta2**2,\\n            -4*theta1*theta3, ctx.j*theta4]\\n    comb3 = ctx.sum_accurately(terms, 1)\\n    if d == 4:\\n        def terms():\\n            return  [6*theta1**2*z2, -6*ctx.j*z2*theta2, 4*theta1*z3,\\n                 4*z1*comb2, z4, z*comb3]\\n        v = ctx.sum_accurately(terms, 1)\\n        v =  e1*v\\n        ctx.prec = prec\\n        if ctx._is_real_type(t):\\n            return ctx._re(v)\\n        return +v\\n    if d > 4:\\n        h = lambda x: ctx.siegelz(x, derivative=4)\\n        return ctx.diff(h, t, n=d-4)\\n\\n\\n_zeta_zeros = [\\n14.134725142,21.022039639,25.010857580,30.424876126,32.935061588,\\n37.586178159,40.918719012,43.327073281,48.005150881,49.773832478,\\n52.970321478,56.446247697,59.347044003,60.831778525,65.112544048,\\n67.079810529,69.546401711,72.067157674,75.704690699,77.144840069,\\n79.337375020,82.910380854,84.735492981,87.425274613,88.809111208,\\n92.491899271,94.651344041,95.870634228,98.831194218,101.317851006,\\n103.725538040,105.446623052,107.168611184,111.029535543,111.874659177,\\n114.320220915,116.226680321,118.790782866,121.370125002,122.946829294,\\n124.256818554,127.516683880,129.578704200,131.087688531,133.497737203,\\n134.756509753,138.116042055,139.736208952,141.123707404,143.111845808,\\n146.000982487,147.422765343,150.053520421,150.925257612,153.024693811,\\n156.112909294,157.597591818,158.849988171,161.188964138,163.030709687,\\n165.537069188,167.184439978,169.094515416,169.911976479,173.411536520,\\n174.754191523,176.441434298,178.377407776,179.916484020,182.207078484,\\n184.874467848,185.598783678,187.228922584,189.416158656,192.026656361,\\n193.079726604,195.265396680,196.876481841,198.015309676,201.264751944,\\n202.493594514,204.189671803,205.394697202,207.906258888,209.576509717,\\n211.690862595,213.347919360,214.547044783,216.169538508,219.067596349,\\n220.714918839,221.430705555,224.007000255,224.983324670,227.421444280,\\n229.337413306,231.250188700,231.987235253,233.693404179,236.524229666,\\n]\\n\\ndef _load_zeta_zeros(url):\\n    import urllib\\n    d = urllib.urlopen(url)\\n    L = [float(x) for x in d.readlines()]\\n    # Sanity check\\n    assert round(L[0]) == 14\\n    _zeta_zeros[:] = L\\n\\n@defun\\ndef oldzetazero(ctx, n, url='http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1'):\\n    n = int(n)\\n    if n < 0:\\n        return ctx.zetazero(-n).conjugate()\\n    if n == 0:\\n        raise ValueError(\\\"n must be nonzero\\\")\\n    if n > len(_zeta_zeros) and n <= 100000:\\n        _load_zeta_zeros(url)\\n    if n > len(_zeta_zeros):\\n        raise NotImplementedError(\\\"n too large for zetazeros\\\")\\n    return ctx.mpc(0.5, ctx.findroot(ctx.siegelz, _zeta_zeros[n-1]))\\n\\n@defun_wrapped\\ndef riemannr(ctx, x):\\n    if x == 0:\\n        return ctx.zero\\n    # Check if a simple asymptotic estimate is accurate enough\\n    if abs(x) > 1000:\\n        a = ctx.li(x)\\n        b = 0.5*ctx.li(ctx.sqrt(x))\\n        if abs(b) < abs(a)*ctx.eps:\\n            return a\\n    if abs(x) < 0.01:\\n        # XXX\\n        ctx.prec += int(-ctx.log(abs(x),2))\\n    # Sum Gram's series\\n    s = t = ctx.one\\n    u = ctx.ln(x)\\n    k = 1\\n    while abs(t) > abs(s)*ctx.eps:\\n        t = t * u / k\\n        s += t / (k * ctx._zeta_int(k+1))\\n        k += 1\\n    return s\\n\\n@defun_static\\ndef primepi(ctx, x):\\n    x = int(x)\\n    if x < 2:\\n        return 0\\n    return len(ctx.list_primes(x))\\n\\n# TODO: fix the interface wrt contexts\\n@defun_wrapped\\ndef primepi2(ctx, x):\\n    x = int(x)\\n    if x < 2:\\n        return ctx._iv.zero\\n    if x < 2657:\\n        return ctx._iv.mpf(ctx.primepi(x))\\n    mid = ctx.li(x)\\n    # Schoenfeld's estimate for x >= 2657, assuming RH\\n    err = ctx.sqrt(x,rounding='u')*ctx.ln(x,rounding='u')/8/ctx.pi(rounding='d')\\n    a = ctx.floor((ctx._iv.mpf(mid)-err).a, rounding='d')\\n    b = ctx.ceil((ctx._iv.mpf(mid)+err).b, rounding='u')\\n    return ctx._iv.mpf([a,b])\\n\\n@defun_wrapped\\ndef primezeta(ctx, s):\\n    if ctx.isnan(s):\\n        return s\\n    if ctx.re(s) <= 0:\\n        raise ValueError(\\\"prime zeta function defined only for re(s) > 0\\\")\\n    if s == 1:\\n        return ctx.inf\\n    if s == 0.5:\\n        return ctx.mpc(ctx.ninf, ctx.pi)\\n    r = ctx.re(s)\\n    if r > ctx.prec:\\n        return 0.5**s\\n    else:\\n        wp = ctx.prec + int(r)\\n        def terms():\\n            orig = ctx.prec\\n            # zeta ~ 1+eps; need to set precision\\n            # to get logarithm accurately\\n            k = 0\\n            while 1:\\n                k += 1\\n                u = ctx.moebius(k)\\n                if not u:\\n                    continue\\n                ctx.prec = wp\\n                t = u*ctx.ln(ctx.zeta(k*s))/k\\n                if not t:\\n                    return\\n                #print ctx.prec, ctx.nstr(t)\\n                ctx.prec = orig\\n                yield t\\n    return ctx.sum_accurately(terms)\\n\\n# TODO: for bernpoly and eulerpoly, ensure that all exact zeros are covered\\n\\n@defun_wrapped\\ndef bernpoly(ctx, n, z):\\n    # Slow implementation:\\n    #return sum(ctx.binomial(n,k)*ctx.bernoulli(k)*z**(n-k) for k in xrange(0,n+1))\\n    n = int(n)\\n    if n < 0:\\n        raise ValueError(\\\"Bernoulli polynomials only defined for n >= 0\\\")\\n    if z == 0 or (z == 1 and n > 1):\\n        return ctx.bernoulli(n)\\n    if z == 0.5:\\n        return (ctx.ldexp(1,1-n)-1)*ctx.bernoulli(n)\\n    if n <= 3:\\n        if n == 0: return z ** 0\\n        if n == 1: return z - 0.5\\n        if n == 2: return (6*z*(z-1)+1)/6\\n        if n == 3: return z*(z*(z-1.5)+0.5)\\n    if ctx.isinf(z):\\n        return z ** n\\n    if ctx.isnan(z):\\n        return z\\n    if abs(z) > 2:\\n        def terms():\\n            t = ctx.one\\n            yield t\\n            r = ctx.one/z\\n            k = 1\\n            while k <= n:\\n                t = t*(n+1-k)/k*r\\n                if not (k > 2 and k & 1):\\n                    yield t*ctx.bernoulli(k)\\n                k += 1\\n        return ctx.sum_accurately(terms) * z**n\\n    else:\\n        def terms():\\n            yield ctx.bernoulli(n)\\n            t = ctx.one\\n            k = 1\\n            while k <= n:\\n                t = t*(n+1-k)/k * z\\n                m = n-k\\n                if not (m > 2 and m & 1):\\n                    yield t*ctx.bernoulli(m)\\n                k += 1\\n        return ctx.sum_accurately(terms)\\n\\n@defun_wrapped\\ndef eulerpoly(ctx, n, z):\\n    n = int(n)\\n    if n < 0:\\n        raise ValueError(\\\"Euler polynomials only defined for n >= 0\\\")\\n    if n <= 2:\\n        if n == 0: return z ** 0\\n        if n == 1: return z - 0.5\\n        if n == 2: return z*(z-1)\\n    if ctx.isinf(z):\\n        return z**n\\n    if ctx.isnan(z):\\n        return z\\n    m = n+1\\n    if z == 0:\\n        return -2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0\\n    if z == 1:\\n        return 2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0\\n    if z == 0.5:\\n        if n % 2:\\n            return ctx.zero\\n        # Use exact code for Euler numbers\\n        if n < 100 or n*ctx.mag(0.46839865*n) < ctx.prec*0.25:\\n            return ctx.ldexp(ctx._eulernum(n), -n)\\n    # http://functions.wolfram.com/Polynomials/EulerE2/06/01/02/01/0002/\\n    def terms():\\n        t = ctx.one\\n        k = 0\\n        w = ctx.ldexp(1,n+2)\\n        while 1:\\n            v = n-k+1\\n            if not (v > 2 and v & 1):\\n                yield (2-w)*ctx.bernoulli(v)*t\\n            k += 1\\n            if k > n:\\n                break\\n            t = t*z*(n-k+2)/k\\n            w *= 0.5\\n    return ctx.sum_accurately(terms) / m\\n\\n@defun\\ndef eulernum(ctx, n, exact=False):\\n    n = int(n)\\n    if exact:\\n        return int(ctx._eulernum(n))\\n    if n < 100:\\n        return ctx.mpf(ctx._eulernum(n))\\n    if n % 2:\\n        return ctx.zero\\n    return ctx.ldexp(ctx.eulerpoly(n,0.5), n)\\n\\n# TODO: this should be implemented low-level\\ndef polylog_series(ctx, s, z):\\n    tol = +ctx.eps\\n    l = ctx.zero\\n    k = 1\\n    zk = z\\n    while 1:\\n        term = zk / k**s\\n        l += term\\n        if abs(term) < tol:\\n            break\\n        zk *= z\\n        k += 1\\n    return l\\n\\ndef polylog_continuation(ctx, n, z):\\n    if n < 0:\\n        return z*0\\n    twopij = 2j * ctx.pi\\n    a = -twopij**n/ctx.fac(n) * ctx.bernpoly(n, ctx.ln(z)/twopij)\\n    if ctx._is_real_type(z) and z < 0:\\n        a = ctx._re(a)\\n    if ctx._im(z) < 0 or (ctx._im(z) == 0 and ctx._re(z) >= 1):\\n        a -= twopij*ctx.ln(z)**(n-1)/ctx.fac(n-1)\\n    return a\\n\\ndef polylog_unitcircle(ctx, n, z):\\n    tol = +ctx.eps\\n    if n > 1:\\n        l = ctx.zero\\n        logz = ctx.ln(z)\\n        logmz = ctx.one\\n        m = 0\\n        while 1:\\n            if (n-m) != 1:\\n                term = ctx.zeta(n-m) * logmz / ctx.fac(m)\\n                if term and abs(term) < tol:\\n                    break\\n                l += term\\n            logmz *= logz\\n            m += 1\\n        l += ctx.ln(z)**(n-1)/ctx.fac(n-1)*(ctx.harmonic(n-1)-ctx.ln(-ctx.ln(z)))\\n    elif n < 1:  # else\\n        l = ctx.fac(-n)*(-ctx.ln(z))**(n-1)\\n        logz = ctx.ln(z)\\n        logkz = ctx.one\\n        k = 0\\n        while 1:\\n            b = ctx.bernoulli(k-n+1)\\n            if b:\\n                term = b*logkz/(ctx.fac(k)*(k-n+1))\\n                if abs(term) < tol:\\n                    break\\n                l -= term\\n            logkz *= logz\\n            k += 1\\n    else:\\n        raise ValueError\\n    if ctx._is_real_type(z) and z < 0:\\n        l = ctx._re(l)\\n    return l\\n\\ndef polylog_general(ctx, s, z):\\n    v = ctx.zero\\n    u = ctx.ln(z)\\n    if not abs(u) < 5: # theoretically |u| < 2*pi\\n        j = ctx.j\\n        v = 1-s\\n        y = ctx.ln(-z)/(2*ctx.pi*j)\\n        return ctx.gamma(v)*(j**v*ctx.zeta(v,0.5+y) + j**-v*ctx.zeta(v,0.5-y))/(2*ctx.pi)**v\\n    t = 1\\n    k = 0\\n    while 1:\\n        term = ctx.zeta(s-k) * t\\n        if abs(term) < ctx.eps:\\n            break\\n        v += term\\n        k += 1\\n        t *= u\\n        t /= k\\n    return ctx.gamma(1-s)*(-u)**(s-1) + v\\n\\n@defun_wrapped\\ndef polylog(ctx, s, z):\\n    s = ctx.convert(s)\\n    z = ctx.convert(z)\\n    if z == 1:\\n        return ctx.zeta(s)\\n    if z == -1:\\n        return -ctx.altzeta(s)\\n    if s == 0:\\n        return z/(1-z)\\n    if s == 1:\\n        return -ctx.ln(1-z)\\n    if s == -1:\\n        return z/(1-z)**2\\n    if abs(z) <= 0.75 or (not ctx.isint(s) and abs(z) < 0.9):\\n        return polylog_series(ctx, s, z)\\n    if abs(z) >= 1.4 and ctx.isint(s):\\n        return (-1)**(s+1)*polylog_series(ctx, s, 1/z) + polylog_continuation(ctx, int(ctx.re(s)), z)\\n    if ctx.isint(s):\\n        return polylog_unitcircle(ctx, int(ctx.re(s)), z)\\n    return polylog_general(ctx, s, z)\\n\\n@defun_wrapped\\ndef clsin(ctx, s, z, pi=False):\\n    if ctx.isint(s) and s < 0 and int(s) % 2 == 1:\\n        return z*0\\n    if pi:\\n        a = ctx.expjpi(z)\\n    else:\\n        a = ctx.expj(z)\\n    if ctx._is_real_type(z) and ctx._is_real_type(s):\\n        return ctx.im(ctx.polylog(s,a))\\n    b = 1/a\\n    return (-0.5j)*(ctx.polylog(s,a) - ctx.polylog(s,b))\\n\\n@defun_wrapped\\ndef clcos(ctx, s, z, pi=False):\\n    if ctx.isint(s) and s < 0 and int(s) % 2 == 0:\\n        return z*0\\n    if pi:\\n        a = ctx.expjpi(z)\\n    else:\\n        a = ctx.expj(z)\\n    if ctx._is_real_type(z) and ctx._is_real_type(s):\\n        return ctx.re(ctx.polylog(s,a))\\n    b = 1/a\\n    return 0.5*(ctx.polylog(s,a) + ctx.polylog(s,b))\\n\\n@defun\\ndef altzeta(ctx, s, **kwargs):\\n    try:\\n        return ctx._altzeta(s, **kwargs)\\n    except NotImplementedError:\\n        return ctx._altzeta_generic(s)\\n\\n@defun_wrapped\\ndef _altzeta_generic(ctx, s):\\n    if s == 1:\\n        return ctx.ln2 + 0*s\\n    return -ctx.powm1(2, 1-s) * ctx.zeta(s)\\n\\n@defun\\ndef zeta(ctx, s, a=1, derivative=0, method=None, **kwargs):\\n    d = int(derivative)\\n    if a == 1 and not (d or method):\\n        try:\\n            return ctx._zeta(s, **kwargs)\\n        except NotImplementedError:\\n            pass\\n    s = ctx.convert(s)\\n    prec = ctx.prec\\n    method = kwargs.get('method')\\n    verbose = kwargs.get('verbose')\\n    if (not s) and (not derivative):\\n        return ctx.mpf(0.5) - ctx._convert_param(a)[0]\\n    if a == 1 and method != 'euler-maclaurin':\\n        im = abs(ctx._im(s))\\n        re = abs(ctx._re(s))\\n        #if (im < prec or method == 'borwein') and not derivative:\\n        #    try:\\n        #        if verbose:\\n        #            print \\\"zeta: Attempting to use the Borwein algorithm\\\"\\n        #        return ctx._zeta(s, **kwargs)\\n        #    except NotImplementedError:\\n        #        if verbose:\\n        #            print \\\"zeta: Could not use the Borwein algorithm\\\"\\n        #        pass\\n        if abs(im) > 500*prec and 10*re < prec and derivative <= 4 or \\\\\\n            method == 'riemann-siegel':\\n            try:   #  py2.4 compatible try block\\n                try:\\n                    if verbose:\\n                        print(\\\"zeta: Attempting to use the Riemann-Siegel algorithm\\\")\\n                    return ctx.rs_zeta(s, derivative, **kwargs)\\n                except NotImplementedError:\\n                    if verbose:\\n                        print(\\\"zeta: Could not use the Riemann-Siegel algorithm\\\")\\n                    pass\\n            finally:\\n                ctx.prec = prec\\n    if s == 1:\\n        return ctx.inf\\n    abss = abs(s)\\n    if abss == ctx.inf:\\n        if ctx.re(s) == ctx.inf:\\n            if d == 0:\\n                return ctx.one\\n            return ctx.zero\\n        return s*0\\n    elif ctx.isnan(abss):\\n        return 1/s\\n    if ctx.re(s) > 2*ctx.prec and a == 1 and not derivative:\\n        return ctx.one + ctx.power(2, -s)\\n    return +ctx._hurwitz(s, a, d, **kwargs)\\n\\n@defun\\ndef _hurwitz(ctx, s, a=1, d=0, **kwargs):\\n    prec = ctx.prec\\n    verbose = kwargs.get('verbose')\\n    try:\\n        extraprec = 10\\n        ctx.prec += extraprec\\n        # We strongly want to special-case rational a\\n        a, atype = ctx._convert_param(a)\\n        if ctx.re(s) < 0:\\n            if verbose:\\n                print(\\\"zeta: Attempting reflection formula\\\")\\n            try:\\n                return _hurwitz_reflection(ctx, s, a, d, atype)\\n            except NotImplementedError:\\n                pass\\n            if verbose:\\n                print(\\\"zeta: Reflection formula failed\\\")\\n        if verbose:\\n            print(\\\"zeta: Using the Euler-Maclaurin algorithm\\\")\\n        while 1:\\n            ctx.prec = prec + extraprec\\n            T1, T2 = _hurwitz_em(ctx, s, a, d, prec+10, verbose)\\n            cancellation = ctx.mag(T1) - ctx.mag(T1+T2)\\n            if verbose:\\n                print(\\\"Term 1:\\\", T1)\\n                print(\\\"Term 2:\\\", T2)\\n                print(\\\"Cancellation:\\\", cancellation, \\\"bits\\\")\\n            if cancellation < extraprec:\\n                return T1 + T2\\n            else:\\n                extraprec = max(2*extraprec, min(cancellation + 5, 100*prec))\\n                if extraprec > kwargs.get('maxprec', 100*prec):\\n                    raise ctx.NoConvergence(\\\"zeta: too much cancellation\\\")\\n    finally:\\n        ctx.prec = prec\\n\\ndef _hurwitz_reflection(ctx, s, a, d, atype):\\n    # TODO: implement for derivatives\\n    if d != 0:\\n        raise NotImplementedError\\n    res = ctx.re(s)\\n    negs = -s\\n    # Integer reflection formula\\n    if ctx.isnpint(s):\\n        n = int(res)\\n        if n <= 0:\\n            return ctx.bernpoly(1-n, a) / (n-1)\\n    if not (atype == 'Q' or atype == 'Z'):\\n        raise NotImplementedError\\n    t = 1-s\\n    # We now require a to be standardized\\n    v = 0\\n    shift = 0\\n    b = a\\n    while ctx.re(b) > 1:\\n        b -= 1\\n        v -= b**negs\\n        shift -= 1\\n    while ctx.re(b) <= 0:\\n        v += b**negs\\n        b += 1\\n        shift += 1\\n    # Rational reflection formula\\n    try:\\n        p, q = a._mpq_\\n    except:\\n        assert a == int(a)\\n        p = int(a)\\n        q = 1\\n    p += shift*q\\n    assert 1 <= p <= q\\n    g = ctx.fsum(ctx.cospi(t/2-2*k*b)*ctx._hurwitz(t,(k,q)) \\\\\\n        for k in range(1,q+1))\\n    g *= 2*ctx.gamma(t)/(2*ctx.pi*q)**t\\n    v += g\\n    return v\\n\\ndef _hurwitz_em(ctx, s, a, d, prec, verbose):\\n    # May not be converted at this point\\n    a = ctx.convert(a)\\n    tol = -prec\\n    # Estimate number of terms for Euler-Maclaurin summation; could be improved\\n    M1 = 0\\n    M2 = prec // 3\\n    N = M2\\n    lsum = 0\\n    # This speeds up the recurrence for derivatives\\n    if ctx.isint(s):\\n        s = int(ctx._re(s))\\n    s1 = s-1\\n    while 1:\\n        # Truncated L-series\\n        l = ctx._zetasum(s, M1+a, M2-M1-1, [d])[0][0]\\n        #if d:\\n        #    l = ctx.fsum((-ctx.ln(n+a))**d * (n+a)**negs for n in range(M1,M2))\\n        #else:\\n        #    l = ctx.fsum((n+a)**negs for n in range(M1,M2))\\n        lsum += l\\n        M2a = M2+a\\n        logM2a = ctx.ln(M2a)\\n        logM2ad = logM2a**d\\n        logs = [logM2ad]\\n        logr = 1/logM2a\\n        rM2a = 1/M2a\\n        M2as = M2a**(-s)\\n        if d:\\n            tailsum = ctx.gammainc(d+1, s1*logM2a) / s1**(d+1)\\n        else:\\n            tailsum = 1/((s1)*(M2a)**s1)\\n        tailsum += 0.5 * logM2ad * M2as\\n        U = [1]\\n        r = M2as\\n        fact = 2\\n        for j in range(1, N+1):\\n            # TODO: the following could perhaps be tidied a bit\\n            j2 = 2*j\\n            if j == 1:\\n                upds = [1]\\n            else:\\n                upds = [j2-2, j2-1]\\n            for m in upds:\\n                D = min(m,d+1)\\n                if m <= d:\\n                    logs.append(logs[-1] * logr)\\n                Un = [0]*(D+1)\\n                for i in xrange(D): Un[i] = (1-m-s)*U[i]\\n                for i in xrange(1,D+1): Un[i] += (d-(i-1))*U[i-1]\\n                U = Un\\n                r *= rM2a\\n            t = ctx.fdot(U, logs) * r * ctx.bernoulli(j2)/(-fact)\\n            tailsum += t\\n            if ctx.mag(t) < tol:\\n                return lsum, (-1)**d * tailsum\\n            fact *= (j2+1)*(j2+2)\\n        if verbose:\\n            print(\\\"Sum range:\\\", M1, M2, \\\"term magnitude\\\", ctx.mag(t), \\\"tolerance\\\", tol)\\n        M1, M2 = M2, M2*2\\n        if ctx.re(s) < 0:\\n            N += N//2\\n\\n\\n\\n@defun\\ndef _zetasum(ctx, s, a, n, derivatives=[0], reflect=False):\\n    \\\"\\\"\\\"\\n    Returns [xd0,xd1,...,xdr], [yd0,yd1,...ydr] where\\n\\n    xdk = D^k     ( 1/a^s     +  1/(a+1)^s      +  ...  +  1/(a+n)^s     )\\n    ydk = D^k conj( 1/a^(1-s) +  1/(a+1)^(1-s)  +  ...  +  1/(a+n)^(1-s) )\\n\\n    D^k = kth derivative with respect to s, k ranges over the given list of\\n    derivatives (which should consist of either a single element\\n    or a range 0,1,...r). If reflect=False, the ydks are not computed.\\n    \\\"\\\"\\\"\\n    #print \\\"zetasum\\\", s, a, n\\n    # don't use the fixed-point code if there are large exponentials\\n    if abs(ctx.re(s)) < 0.5 * ctx.prec:\\n        try:\\n            return ctx._zetasum_fast(s, a, n, derivatives, reflect)\\n        except NotImplementedError:\\n            pass\\n    negs = ctx.fneg(s, exact=True)\\n    have_derivatives = derivatives != [0]\\n    have_one_derivative = len(derivatives) == 1\\n    if not reflect:\\n        if not have_derivatives:\\n            return [ctx.fsum((a+k)**negs for k in xrange(n+1))], []\\n        if have_one_derivative:\\n            d = derivatives[0]\\n            x = ctx.fsum(ctx.ln(a+k)**d * (a+k)**negs for k in xrange(n+1))\\n            return [(-1)**d * x], []\\n    maxd = max(derivatives)\\n    if not have_one_derivative:\\n        derivatives = range(maxd+1)\\n    xs = [ctx.zero for d in derivatives]\\n    if reflect:\\n        ys = [ctx.zero for d in derivatives]\\n    else:\\n        ys = []\\n    for k in xrange(n+1):\\n        w = a + k\\n        xterm = w ** negs\\n        if reflect:\\n            yterm = ctx.conj(ctx.one / (w * xterm))\\n        if have_derivatives:\\n            logw = -ctx.ln(w)\\n            if have_one_derivative:\\n                logw = logw ** maxd\\n                xs[0] += xterm * logw\\n                if reflect:\\n                    ys[0] += yterm * logw\\n            else:\\n                t = ctx.one\\n                for d in derivatives:\\n                    xs[d] += xterm * t\\n                    if reflect:\\n                        ys[d] += yterm * t\\n                    t *= logw\\n        else:\\n            xs[0] += xterm\\n            if reflect:\\n                ys[0] += yterm\\n    return xs, ys\\n\\n@defun\\ndef dirichlet(ctx, s, chi=[1], derivative=0):\\n    s = ctx.convert(s)\\n    q = len(chi)\\n    d = int(derivative)\\n    if d > 2:\\n        raise NotImplementedError(\\\"arbitrary order derivatives\\\")\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 10\\n        if s == 1:\\n            have_pole = True\\n            for x in chi:\\n                if x and x != 1:\\n                    have_pole = False\\n                    h = +ctx.eps\\n                    ctx.prec *= 2*(d+1)\\n                    s += h\\n            if have_pole:\\n                return +ctx.inf\\n        z = ctx.zero\\n        for p in range(1,q+1):\\n            if chi[p%q]:\\n                if d == 1:\\n                    z += chi[p%q] * (ctx.zeta(s, (p,q), 1) - \\\\\\n                        ctx.zeta(s, (p,q))*ctx.log(q))\\n                else:\\n                    z += chi[p%q] * ctx.zeta(s, (p,q))\\n        z /= q**s\\n    finally:\\n        ctx.prec = prec\\n    return +z\\n\\n\\ndef secondzeta_main_term(ctx, s, a, **kwargs):\\n    tol = ctx.eps\\n    f = lambda n: ctx.gammainc(0.5*s, a*gamm**2, regularized=True)*gamm**(-s)\\n    totsum = term = ctx.zero\\n    mg = ctx.inf\\n    n = 0\\n    while mg > tol:\\n        totsum += term\\n        n += 1\\n        gamm = ctx.im(ctx.zetazero_memoized(n))\\n        term = f(n)\\n        mg = abs(term)\\n    err = 0\\n    if kwargs.get(\\\"error\\\"):\\n        sg = ctx.re(s)\\n        err = 0.5*ctx.pi**(-1)*max(1,sg)*a**(sg-0.5)*ctx.log(gamm/(2*ctx.pi))*\\\\\\n             ctx.gammainc(-0.5, a*gamm**2)/abs(ctx.gamma(s/2))\\n        err = abs(err)\\n    return +totsum, err, n\\n\\ndef secondzeta_prime_term(ctx, s, a, **kwargs):\\n    tol = ctx.eps\\n    f = lambda n: ctx.gammainc(0.5*(1-s),0.25*ctx.log(n)**2 * a**(-1))*\\\\\\n        ((0.5*ctx.log(n))**(s-1))*ctx.mangoldt(n)/ctx.sqrt(n)/\\\\\\n        (2*ctx.gamma(0.5*s)*ctx.sqrt(ctx.pi))\\n    totsum = term = ctx.zero\\n    mg = ctx.inf\\n    n = 1\\n    while mg > tol or n < 9:\\n        totsum += term\\n        n += 1\\n        term = f(n)\\n        if term == 0:\\n            mg = ctx.inf\\n        else:\\n            mg = abs(term)\\n    if kwargs.get(\\\"error\\\"):\\n        err = mg\\n    return +totsum, err, n\\n\\ndef secondzeta_exp_term(ctx, s, a):\\n    if ctx.isint(s) and ctx.re(s) <= 0:\\n        m = int(round(ctx.re(s)))\\n        if not m & 1:\\n            return ctx.mpf('-0.25')**(-m//2)\\n    tol = ctx.eps\\n    f = lambda n: (0.25*a)**n/((n+0.5*s)*ctx.fac(n))\\n    totsum = ctx.zero\\n    term = f(0)\\n    mg = ctx.inf\\n    n = 0\\n    while mg > tol:\\n        totsum += term\\n        n += 1\\n        term = f(n)\\n        mg = abs(term)\\n    v = a**(0.5*s)*totsum/ctx.gamma(0.5*s)\\n    return v\\n\\ndef secondzeta_singular_term(ctx, s, a, **kwargs):\\n    factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s))\\n    extraprec = ctx.mag(factor)\\n    ctx.prec += extraprec\\n    factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s))\\n    tol = ctx.eps\\n    f = lambda n: ctx.bernpoly(n,0.75)*(4*ctx.sqrt(a))**n*\\\\\\n       ctx.gamma(0.5*n)/((s+n-1)*ctx.fac(n))\\n    totsum = ctx.zero\\n    mg1 = ctx.inf\\n    n = 1\\n    term = f(n)\\n    mg2 = abs(term)\\n    while mg2 > tol and mg2 <= mg1:\\n        totsum += term\\n        n += 1\\n        term = f(n)\\n        totsum += term\\n        n +=1\\n        term = f(n)\\n        mg1 = mg2\\n        mg2 = abs(term)\\n    totsum += term\\n    pole = -2*(s-1)**(-2)+(ctx.euler+ctx.log(16*ctx.pi**2*a))*(s-1)**(-1)\\n    st = factor*(pole+totsum)\\n    err = 0\\n    if kwargs.get(\\\"error\\\"):\\n        if not ((mg2 > tol) and (mg2 <= mg1)):\\n            if mg2 <= tol:\\n                err = ctx.mpf(10)**int(ctx.log(abs(factor*tol),10))\\n            if mg2 > mg1:\\n                err = ctx.mpf(10)**int(ctx.log(abs(factor*mg1),10))\\n        err = max(err, ctx.eps*1.)\\n    ctx.prec -= extraprec\\n    return +st, err\\n\\n@defun\\ndef secondzeta(ctx, s, a = 0.015, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the secondary zeta function `Z(s)`, defined for\\n    `\\\\mathrm{Re}(s)>1` by\\n\\n    .. math ::\\n\\n        Z(s) = \\\\sum_{n=1}^{\\\\infty} \\\\frac{1}{\\\\tau_n^s}\\n\\n    where `\\\\frac12+i\\\\tau_n` runs through the zeros of `\\\\zeta(s)` with\\n    imaginary part positive.\\n\\n    `Z(s)` extends to a meromorphic function on `\\\\mathbb{C}`  with a\\n    double pole at `s=1` and  simple poles at the points `-2n` for\\n    `n=0`,  1, 2, ...\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.pretty = True; mp.dps = 15\\n        >>> secondzeta(2)\\n        0.023104993115419\\n        >>> xi = lambda s: 0.5*s*(s-1)*pi**(-0.5*s)*gamma(0.5*s)*zeta(s)\\n        >>> Xi = lambda t: xi(0.5+t*j)\\n        >>> chop(-0.5*diff(Xi,0,n=2)/Xi(0))\\n        0.023104993115419\\n\\n    We may ask for an approximate error value::\\n\\n        >>> secondzeta(0.5+100j, error=True)\\n        ((-0.216272011276718 - 0.844952708937228j), 2.22044604925031e-16)\\n\\n    The function has poles at the negative odd integers,\\n    and dyadic rational values at the negative even integers::\\n\\n        >>> mp.dps = 30\\n        >>> secondzeta(-8)\\n        -0.67236328125\\n        >>> secondzeta(-7)\\n        +inf\\n\\n    **Implementation notes**\\n\\n    The function is computed as sum of four terms `Z(s)=A(s)-P(s)+E(s)-S(s)`\\n    respectively main, prime, exponential and singular terms.\\n    The main term `A(s)` is computed from the zeros of zeta.\\n    The prime term depends on the von Mangoldt function.\\n    The singular term is responsible for the poles of the function.\\n\\n    The four terms depends on a small parameter `a`. We may change the\\n    value of `a`. Theoretically this has no effect on the sum of the four\\n    terms, but in practice may be important.\\n\\n    A smaller value of the parameter `a` makes `A(s)` depend on\\n    a smaller number of zeros of zeta, but `P(s)`  uses more values of\\n    von Mangoldt function.\\n\\n    We may also add a verbose option to obtain data about the\\n    values of the four terms.\\n\\n        >>> mp.dps = 10\\n        >>> secondzeta(0.5 + 40j, error=True, verbose=True)\\n        main term = (-30190318549.138656312556 - 13964804384.624622876523j)\\n            computed using 19 zeros of zeta\\n        prime term = (132717176.89212754625045 + 188980555.17563978290601j)\\n            computed using 9 values of the von Mangoldt function\\n        exponential term = (542447428666.07179812536 + 362434922978.80192435203j)\\n        singular term = (512124392939.98154322355 + 348281138038.65531023921j)\\n        ((0.059471043 + 0.3463514534j), 1.455191523e-11)\\n\\n        >>> secondzeta(0.5 + 40j, a=0.04, error=True, verbose=True)\\n        main term = (-151962888.19606243907725 - 217930683.90210294051982j)\\n            computed using 9 zeros of zeta\\n        prime term = (2476659342.3038722372461 + 28711581821.921627163136j)\\n            computed using 37 values of the von Mangoldt function\\n        exponential term = (178506047114.7838188264 + 819674143244.45677330576j)\\n        singular term = (175877424884.22441310708 + 790744630738.28669174871j)\\n        ((0.059471043 + 0.3463514534j), 1.455191523e-11)\\n\\n    Notice the great cancellation between the four terms. Changing `a`, the\\n    four terms are very different numbers but the cancellation gives\\n    the good value of Z(s).\\n\\n    **References**\\n\\n    A. Voros, Zeta functions for the Riemann zeros, Ann. Institute Fourier,\\n    53, (2003) 665--699.\\n\\n    A. Voros, Zeta functions over Zeros of Zeta Functions, Lecture Notes\\n    of the Unione Matematica Italiana, Springer, 2009.\\n    \\\"\\\"\\\"\\n    s = ctx.convert(s)\\n    a = ctx.convert(a)\\n    tol = ctx.eps\\n    if ctx.isint(s) and ctx.re(s) <= 1:\\n        if abs(s-1) < tol*1000:\\n            return ctx.inf\\n        m = int(round(ctx.re(s)))\\n        if m & 1:\\n            return ctx.inf\\n        else:\\n            return ((-1)**(-m//2)*\\\\\\n                   ctx.fraction(8-ctx.eulernum(-m,exact=True),2**(-m+3)))\\n    prec = ctx.prec\\n    try:\\n        t3 = secondzeta_exp_term(ctx, s, a)\\n        extraprec = max(ctx.mag(t3),0)\\n        ctx.prec += extraprec + 3\\n        t1, r1, gt = secondzeta_main_term(ctx,s,a,error='True', verbose='True')\\n        t2, r2, pt = secondzeta_prime_term(ctx,s,a,error='True', verbose='True')\\n        t4, r4 = secondzeta_singular_term(ctx,s,a,error='True')\\n        t3 = secondzeta_exp_term(ctx, s, a)\\n        err = r1+r2+r4\\n        t = t1-t2+t3-t4\\n        if kwargs.get(\\\"verbose\\\"):\\n            print('main term =', t1)\\n            print('    computed using', gt, 'zeros of zeta')\\n            print('prime term =', t2)\\n            print('    computed using', pt, 'values of the von Mangoldt function')\\n            print('exponential term =', t3)\\n            print('singular term =', t4)\\n    finally:\\n        ctx.prec = prec\\n    if kwargs.get(\\\"error\\\"):\\n        w = max(ctx.mag(abs(t)),0)\\n        err = max(err*2**w, ctx.eps*1.*2**w)\\n        return +t, err\\n    return +t\\n\\n\\n@defun_wrapped\\ndef lerchphi(ctx, z, s, a):\\n    r\\\"\\\"\\\"\\n    Gives the Lerch transcendent, defined for `|z| < 1` and\\n    `\\\\Re{a} > 0` by\\n\\n    .. math ::\\n\\n        \\\\Phi(z,s,a) = \\\\sum_{k=0}^{\\\\infty} \\\\frac{z^k}{(a+k)^s}\\n\\n    and generally by the recurrence `\\\\Phi(z,s,a) = z \\\\Phi(z,s,a+1) + a^{-s}`\\n    along with the integral representation valid for `\\\\Re{a} > 0`\\n\\n    .. math ::\\n\\n        \\\\Phi(z,s,a) = \\\\frac{1}{2 a^s} +\\n                \\\\int_0^{\\\\infty} \\\\frac{z^t}{(a+t)^s} dt -\\n                2 \\\\int_0^{\\\\infty} \\\\frac{\\\\sin(t \\\\log z - s\\n                    \\\\operatorname{arctan}(t/a)}{(a^2 + t^2)^{s/2}\\n                    (e^{2 \\\\pi t}-1)} dt.\\n\\n    The Lerch transcendent generalizes the Hurwitz zeta function :func:`zeta`\\n    (`z = 1`) and the polylogarithm :func:`polylog` (`a = 1`).\\n\\n    **Examples**\\n\\n    Several evaluations in terms of simpler functions::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> lerchphi(-1,2,0.5); 4*catalan\\n        3.663862376708876060218414\\n        3.663862376708876060218414\\n        >>> diff(lerchphi, (-1,-2,1), (0,1,0)); 7*zeta(3)/(4*pi**2)\\n        0.2131391994087528954617607\\n        0.2131391994087528954617607\\n        >>> lerchphi(-4,1,1); log(5)/4\\n        0.4023594781085250936501898\\n        0.4023594781085250936501898\\n        >>> lerchphi(-3+2j,1,0.5); 2*atanh(sqrt(-3+2j))/sqrt(-3+2j)\\n        (1.142423447120257137774002 + 0.2118232380980201350495795j)\\n        (1.142423447120257137774002 + 0.2118232380980201350495795j)\\n\\n    Evaluation works for complex arguments and `|z| \\\\ge 1`::\\n\\n        >>> lerchphi(1+2j, 3-j, 4+2j)\\n        (0.002025009957009908600539469 + 0.003327897536813558807438089j)\\n        >>> lerchphi(-2,2,-2.5)\\n        -12.28676272353094275265944\\n        >>> lerchphi(10,10,10)\\n        (-4.462130727102185701817349e-11 - 1.575172198981096218823481e-12j)\\n        >>> lerchphi(10,10,-10.5)\\n        (112658784011940.5605789002 - 498113185.5756221777743631j)\\n\\n    Some degenerate cases::\\n\\n        >>> lerchphi(0,1,2)\\n        0.5\\n        >>> lerchphi(0,1,-2)\\n        -0.5\\n\\n    Reduction to simpler functions::\\n\\n        >>> lerchphi(1, 4.25+1j, 1)\\n        (1.044674457556746668033975 - 0.04674508654012658932271226j)\\n        >>> zeta(4.25+1j)\\n        (1.044674457556746668033975 - 0.04674508654012658932271226j)\\n        >>> lerchphi(1 - 0.5**10, 4.25+1j, 1)\\n        (1.044629338021507546737197 - 0.04667768813963388181708101j)\\n        >>> lerchphi(3, 4, 1)\\n        (1.249503297023366545192592 - 0.2314252413375664776474462j)\\n        >>> polylog(4, 3) / 3\\n        (1.249503297023366545192592 - 0.2314252413375664776474462j)\\n        >>> lerchphi(3, 4, 1 - 0.5**10)\\n        (1.253978063946663945672674 - 0.2316736622836535468765376j)\\n\\n    **References**\\n\\n    1. [DLMF]_ section 25.14\\n\\n    \\\"\\\"\\\"\\n    if z == 0:\\n        return a ** (-s)\\n    # Faster, but these cases are useful for testing right now\\n    if z == 1:\\n        return ctx.zeta(s, a)\\n    if a == 1:\\n        return ctx.polylog(s, z) / z\\n    if ctx.re(a) < 1:\\n        if ctx.isnpint(a):\\n            raise ValueError(\\\"Lerch transcendent complex infinity\\\")\\n        m = int(ctx.ceil(1-ctx.re(a)))\\n        v = ctx.zero\\n        zpow = ctx.one\\n        for n in xrange(m):\\n            v += zpow / (a+n)**s\\n            zpow *= z\\n        return zpow * ctx.lerchphi(z,s, a+m) + v\\n    g = ctx.ln(z)\\n    v = 1/(2*a**s) + ctx.gammainc(1-s, -a*g) * (-g)**(s-1) / z**a\\n    h = s / 2\\n    r = 2*ctx.pi\\n    f = lambda t: ctx.sin(s*ctx.atan(t/a)-t*g) / \\\\\\n        ((a**2+t**2)**h * ctx.expm1(r*t))\\n    v += 2*ctx.quad(f, [0, ctx.inf])\\n    if not ctx.im(z) and not ctx.im(s) and not ctx.im(a) and ctx.re(z) < 1:\\n        v = ctx.chop(v)\\n    return v\\n\\n\\nfrom ..libmp.backend import xrange\\n\\nclass SpecialFunctions(object):\\n    \\\"\\\"\\\"\\n    This class implements special functions using high-level code.\\n\\n    Elementary and some other functions (e.g. gamma function, basecase\\n    hypergeometric series) are assumed to be predefined by the context as\\n    \\\"builtins\\\" or \\\"low-level\\\" functions.\\n    \\\"\\\"\\\"\\n    defined_functions = {}\\n\\n    # The series for the Jacobi theta functions converge for |q| < 1;\\n    # in the current implementation they throw a ValueError for\\n    # abs(q) > THETA_Q_LIM\\n    THETA_Q_LIM = 1 - 10**-7\\n\\n    def __init__(self):\\n        cls = self.__class__\\n        for name in cls.defined_functions:\\n            f, wrap = cls.defined_functions[name]\\n            cls._wrap_specfun(name, f, wrap)\\n\\n        self.mpq_1 = self._mpq((1,1))\\n        self.mpq_0 = self._mpq((0,1))\\n        self.mpq_1_2 = self._mpq((1,2))\\n        self.mpq_3_2 = self._mpq((3,2))\\n        self.mpq_1_4 = self._mpq((1,4))\\n        self.mpq_1_16 = self._mpq((1,16))\\n        self.mpq_3_16 = self._mpq((3,16))\\n        self.mpq_5_2 = self._mpq((5,2))\\n        self.mpq_3_4 = self._mpq((3,4))\\n        self.mpq_7_4 = self._mpq((7,4))\\n        self.mpq_5_4 = self._mpq((5,4))\\n        self.mpq_1_3 = self._mpq((1,3))\\n        self.mpq_2_3 = self._mpq((2,3))\\n        self.mpq_4_3 = self._mpq((4,3))\\n        self.mpq_1_6 = self._mpq((1,6))\\n        self.mpq_5_6 = self._mpq((5,6))\\n        self.mpq_5_3 = self._mpq((5,3))\\n\\n        self._misc_const_cache = {}\\n\\n        self._aliases.update({\\n            'phase' : 'arg',\\n            'conjugate' : 'conj',\\n            'nthroot' : 'root',\\n            'polygamma' : 'psi',\\n            'hurwitz' : 'zeta',\\n            #'digamma' : 'psi0',\\n            #'trigamma' : 'psi1',\\n            #'tetragamma' : 'psi2',\\n            #'pentagamma' : 'psi3',\\n            'fibonacci' : 'fib',\\n            'factorial' : 'fac',\\n        })\\n\\n        self.zetazero_memoized = self.memoize(self.zetazero)\\n\\n    # Default -- do nothing\\n    @classmethod\\n    def _wrap_specfun(cls, name, f, wrap):\\n        setattr(cls, name, f)\\n\\n    # Optional fast versions of common functions in common cases.\\n    # If not overridden, default (generic hypergeometric series)\\n    # implementations will be used\\n    def _besselj(ctx, n, z): raise NotImplementedError\\n    def _erf(ctx, z): raise NotImplementedError\\n    def _erfc(ctx, z): raise NotImplementedError\\n    def _gamma_upper_int(ctx, z, a): raise NotImplementedError\\n    def _expint_int(ctx, n, z): raise NotImplementedError\\n    def _zeta(ctx, s): raise NotImplementedError\\n    def _zetasum_fast(ctx, s, a, n, derivatives, reflect): raise NotImplementedError\\n    def _ei(ctx, z): raise NotImplementedError\\n    def _e1(ctx, z): raise NotImplementedError\\n    def _ci(ctx, z): raise NotImplementedError\\n    def _si(ctx, z): raise NotImplementedError\\n    def _altzeta(ctx, s): raise NotImplementedError\\n\\ndef defun_wrapped(f):\\n    SpecialFunctions.defined_functions[f.__name__] = f, True\\n    return f\\n\\ndef defun(f):\\n    SpecialFunctions.defined_functions[f.__name__] = f, False\\n    return f\\n\\ndef defun_static(f):\\n    setattr(SpecialFunctions, f.__name__, f)\\n    return f\\n\\n@defun_wrapped\\ndef cot(ctx, z): return ctx.one / ctx.tan(z)\\n\\n@defun_wrapped\\ndef sec(ctx, z): return ctx.one / ctx.cos(z)\\n\\n@defun_wrapped\\ndef csc(ctx, z): return ctx.one / ctx.sin(z)\\n\\n@defun_wrapped\\ndef coth(ctx, z): return ctx.one / ctx.tanh(z)\\n\\n@defun_wrapped\\ndef sech(ctx, z): return ctx.one / ctx.cosh(z)\\n\\n@defun_wrapped\\ndef csch(ctx, z): return ctx.one / ctx.sinh(z)\\n\\n@defun_wrapped\\ndef acot(ctx, z):\\n    if not z:\\n        return ctx.pi * 0.5\\n    else:\\n        return ctx.atan(ctx.one / z)\\n\\n@defun_wrapped\\ndef asec(ctx, z): return ctx.acos(ctx.one / z)\\n\\n@defun_wrapped\\ndef acsc(ctx, z): return ctx.asin(ctx.one / z)\\n\\n@defun_wrapped\\ndef acoth(ctx, z):\\n    if not z:\\n        return ctx.pi * 0.5j\\n    else:\\n        return ctx.atanh(ctx.one / z)\\n\\n\\n@defun_wrapped\\ndef asech(ctx, z): return ctx.acosh(ctx.one / z)\\n\\n@defun_wrapped\\ndef acsch(ctx, z): return ctx.asinh(ctx.one / z)\\n\\n@defun\\ndef sign(ctx, x):\\n    x = ctx.convert(x)\\n    if not x or ctx.isnan(x):\\n        return x\\n    if ctx._is_real_type(x):\\n        if x > 0:\\n            return ctx.one\\n        else:\\n            return -ctx.one\\n    return x / abs(x)\\n\\n@defun\\ndef agm(ctx, a, b=1):\\n    if b == 1:\\n        return ctx.agm1(a)\\n    a = ctx.convert(a)\\n    b = ctx.convert(b)\\n    return ctx._agm(a, b)\\n\\n@defun_wrapped\\ndef sinc(ctx, x):\\n    if ctx.isinf(x):\\n        return 1/x\\n    if not x:\\n        return x+1\\n    return ctx.sin(x)/x\\n\\n@defun_wrapped\\ndef sincpi(ctx, x):\\n    if ctx.isinf(x):\\n        return 1/x\\n    if not x:\\n        return x+1\\n    return ctx.sinpi(x)/(ctx.pi*x)\\n\\n# TODO: tests; improve implementation\\n@defun_wrapped\\ndef expm1(ctx, x):\\n    if not x:\\n        return ctx.zero\\n    # exp(x) - 1 ~ x\\n    if ctx.mag(x) < -ctx.prec:\\n        return x + 0.5*x**2\\n    # TODO: accurately eval the smaller of the real/imag parts\\n    return ctx.sum_accurately(lambda: iter([ctx.exp(x),-1]),1)\\n\\n@defun_wrapped\\ndef log1p(ctx, x):\\n    if not x:\\n        return ctx.zero\\n    if ctx.mag(x) < -ctx.prec:\\n        return x - 0.5*x**2\\n    return ctx.log(ctx.fadd(1, x, prec=2*ctx.prec))\\n\\n@defun_wrapped\\ndef powm1(ctx, x, y):\\n    mag = ctx.mag\\n    one = ctx.one\\n    w = x**y - one\\n    M = mag(w)\\n    # Only moderate cancellation\\n    if M > -8:\\n        return w\\n    # Check for the only possible exact cases\\n    if not w:\\n        if (not y) or (x in (1, -1, 1j, -1j) and ctx.isint(y)):\\n            return w\\n    x1 = x - one\\n    magy = mag(y)\\n    lnx = ctx.ln(x)\\n    # Small y: x^y - 1 ~ log(x)*y + O(log(x)^2 * y^2)\\n    if magy + mag(lnx) < -ctx.prec:\\n        return lnx*y + (lnx*y)**2/2\\n    # TODO: accurately eval the smaller of the real/imag part\\n    return ctx.sum_accurately(lambda: iter([x**y, -1]), 1)\\n\\n@defun\\ndef _rootof1(ctx, k, n):\\n    k = int(k)\\n    n = int(n)\\n    k %= n\\n    if not k:\\n        return ctx.one\\n    elif 2*k == n:\\n        return -ctx.one\\n    elif 4*k == n:\\n        return ctx.j\\n    elif 4*k == 3*n:\\n        return -ctx.j\\n    return ctx.expjpi(2*ctx.mpf(k)/n)\\n\\n@defun\\ndef root(ctx, x, n, k=0):\\n    n = int(n)\\n    x = ctx.convert(x)\\n    if k:\\n        # Special case: there is an exact real root\\n        if (n & 1 and 2*k == n-1) and (not ctx.im(x)) and (ctx.re(x) < 0):\\n            return -ctx.root(-x, n)\\n        # Multiply by root of unity\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            v = ctx.root(x, n, 0) * ctx._rootof1(k, n)\\n        finally:\\n            ctx.prec = prec\\n        return +v\\n    return ctx._nthroot(x, n)\\n\\n@defun\\ndef unitroots(ctx, n, primitive=False):\\n    gcd = ctx._gcd\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 10\\n        if primitive:\\n            v = [ctx._rootof1(k,n) for k in range(n) if gcd(k,n) == 1]\\n        else:\\n            # TODO: this can be done *much* faster\\n            v = [ctx._rootof1(k,n) for k in range(n)]\\n    finally:\\n        ctx.prec = prec\\n    return [+x for x in v]\\n\\n@defun\\ndef arg(ctx, x):\\n    x = ctx.convert(x)\\n    re = ctx._re(x)\\n    im = ctx._im(x)\\n    return ctx.atan2(im, re)\\n\\n@defun\\ndef fabs(ctx, x):\\n    return abs(ctx.convert(x))\\n\\n@defun\\ndef re(ctx, x):\\n    x = ctx.convert(x)\\n    if hasattr(x, \\\"real\\\"):    # py2.5 doesn't have .real/.imag for all numbers\\n        return x.real\\n    return x\\n\\n@defun\\ndef im(ctx, x):\\n    x = ctx.convert(x)\\n    if hasattr(x, \\\"imag\\\"):    # py2.5 doesn't have .real/.imag for all numbers\\n        return x.imag\\n    return ctx.zero\\n\\n@defun\\ndef conj(ctx, x):\\n    x = ctx.convert(x)\\n    try:\\n        return x.conjugate()\\n    except AttributeError:\\n        return x\\n\\n@defun\\ndef polar(ctx, z):\\n    return (ctx.fabs(z), ctx.arg(z))\\n\\n@defun_wrapped\\ndef rect(ctx, r, phi):\\n    return r * ctx.mpc(*ctx.cos_sin(phi))\\n\\n@defun\\ndef log(ctx, x, b=None):\\n    if b is None:\\n        return ctx.ln(x)\\n    wp = ctx.prec + 20\\n    return ctx.ln(x, prec=wp) / ctx.ln(b, prec=wp)\\n\\n@defun\\ndef log10(ctx, x):\\n    return ctx.log(x, 10)\\n\\n@defun\\ndef fmod(ctx, x, y):\\n    return ctx.convert(x) % ctx.convert(y)\\n\\n@defun\\ndef degrees(ctx, x):\\n    return x / ctx.degree\\n\\n@defun\\ndef radians(ctx, x):\\n    return x * ctx.degree\\n\\ndef _lambertw_special(ctx, z, k):\\n    # W(0,0) = 0; all other branches are singular\\n    if not z:\\n        if not k:\\n            return z\\n        return ctx.ninf + z\\n    if z == ctx.inf:\\n        if k == 0:\\n            return z\\n        else:\\n            return z + 2*k*ctx.pi*ctx.j\\n    if z == ctx.ninf:\\n        return (-z) + (2*k+1)*ctx.pi*ctx.j\\n    # Some kind of nan or complex inf/nan?\\n    return ctx.ln(z)\\n\\nimport math\\nimport cmath\\n\\ndef _lambertw_approx_hybrid(z, k):\\n    imag_sign = 0\\n    if hasattr(z, \\\"imag\\\"):\\n        x = float(z.real)\\n        y = z.imag\\n        if y:\\n            imag_sign = (-1) ** (y < 0)\\n        y = float(y)\\n    else:\\n        x = float(z)\\n        y = 0.0\\n        imag_sign = 0\\n    # hack to work regardless of whether Python supports -0.0\\n    if not y:\\n        y = 0.0\\n    z = complex(x,y)\\n    if k == 0:\\n        if -4.0 < y < 4.0 and -1.0 < x < 2.5:\\n            if imag_sign:\\n                # Taylor series in upper/lower half-plane\\n                if y > 1.00: return (0.876+0.645j) + (0.118-0.174j)*(z-(0.75+2.5j))\\n                if y > 0.25: return (0.505+0.204j) + (0.375-0.132j)*(z-(0.75+0.5j))\\n                if y < -1.00: return (0.876-0.645j) + (0.118+0.174j)*(z-(0.75-2.5j))\\n                if y < -0.25: return (0.505-0.204j) + (0.375+0.132j)*(z-(0.75-0.5j))\\n            # Taylor series near -1\\n            if x < -0.5:\\n                if imag_sign >= 0:\\n                    return (-0.318+1.34j) + (-0.697-0.593j)*(z+1)\\n                else:\\n                    return (-0.318-1.34j) + (-0.697+0.593j)*(z+1)\\n            # return real type\\n            r = -0.367879441171442\\n            if (not imag_sign) and x > r:\\n                z = x\\n            # Singularity near -1/e\\n            if x < -0.2:\\n                return -1 + 2.33164398159712*(z-r)**0.5 - 1.81218788563936*(z-r)\\n            # Taylor series near 0\\n            if x < 0.5: return z\\n            # Simple linear approximation\\n            return 0.2 + 0.3*z\\n        if (not imag_sign) and x > 0.0:\\n            L1 = math.log(x); L2 = math.log(L1)\\n        else:\\n            L1 = cmath.log(z); L2 = cmath.log(L1)\\n    elif k == -1:\\n        # return real type\\n        r = -0.367879441171442\\n        if (not imag_sign) and r < x < 0.0:\\n            z = x\\n        if (imag_sign >= 0) and y < 0.1 and -0.6 < x < -0.2:\\n            return -1 - 2.33164398159712*(z-r)**0.5 - 1.81218788563936*(z-r)\\n        if (not imag_sign) and -0.2 <= x < 0.0:\\n            L1 = math.log(-x)\\n            return L1 - math.log(-L1)\\n        else:\\n            if imag_sign == -1 and (not y) and x < 0.0:\\n                L1 = cmath.log(z) - 3.1415926535897932j\\n            else:\\n                L1 = cmath.log(z) - 6.2831853071795865j\\n            L2 = cmath.log(L1)\\n    return L1 - L2 + L2/L1 + L2*(L2-2)/(2*L1**2)\\n\\ndef _lambertw_series(ctx, z, k, tol):\\n    \\\"\\\"\\\"\\n    Return rough approximation for W_k(z) from an asymptotic series,\\n    sufficiently accurate for the Halley iteration to converge to\\n    the correct value.\\n    \\\"\\\"\\\"\\n    magz = ctx.mag(z)\\n    if (-10 < magz < 900) and (-1000 < k < 1000):\\n        # Near the branch point at -1/e\\n        if magz < 1 and abs(z+0.36787944117144) < 0.05:\\n            if k == 0 or (k == -1 and ctx._im(z) >= 0) or \\\\\\n                         (k == 1  and ctx._im(z) < 0):\\n                delta = ctx.sum_accurately(lambda: [z, ctx.exp(-1)])\\n                cancellation = -ctx.mag(delta)\\n                ctx.prec += cancellation\\n                # Use series given in Corless et al.\\n                p = ctx.sqrt(2*(ctx.e*z+1))\\n                ctx.prec -= cancellation\\n                u = {0:ctx.mpf(-1), 1:ctx.mpf(1)}\\n                a = {0:ctx.mpf(2), 1:ctx.mpf(-1)}\\n                if k != 0:\\n                    p = -p\\n                s = ctx.zero\\n                # The series converges, so we could use it directly, but unless\\n                # *extremely* close, it is better to just use the first few\\n                # terms to get a good approximation for the iteration\\n                for l in xrange(max(2,cancellation)):\\n                    if l not in u:\\n                        a[l] = ctx.fsum(u[j]*u[l+1-j] for j in xrange(2,l))\\n                        u[l] = (l-1)*(u[l-2]/2+a[l-2]/4)/(l+1)-a[l]/2-u[l-1]/(l+1)\\n                    term = u[l] * p**l\\n                    s += term\\n                    if ctx.mag(term) < -tol:\\n                        return s, True\\n                    l += 1\\n                ctx.prec += cancellation//2\\n                return s, False\\n        if k == 0 or k == -1:\\n            return _lambertw_approx_hybrid(z, k), False\\n    if k == 0:\\n        if magz < -1:\\n            return z*(1-z), False\\n        L1 = ctx.ln(z)\\n        L2 = ctx.ln(L1)\\n    elif k == -1 and (not ctx._im(z)) and (-0.36787944117144 < ctx._re(z) < 0):\\n        L1 = ctx.ln(-z)\\n        return L1 - ctx.ln(-L1), False\\n    else:\\n        # This holds both as z -> 0 and z -> inf.\\n        # Relative error is O(1/log(z)).\\n        L1 = ctx.ln(z) + 2j*ctx.pi*k\\n        L2 = ctx.ln(L1)\\n    return L1 - L2 + L2/L1 + L2*(L2-2)/(2*L1**2), False\\n\\n@defun\\ndef lambertw(ctx, z, k=0):\\n    z = ctx.convert(z)\\n    k = int(k)\\n    if not ctx.isnormal(z):\\n        return _lambertw_special(ctx, z, k)\\n    prec = ctx.prec\\n    ctx.prec += 20 + ctx.mag(k or 1)\\n    wp = ctx.prec\\n    tol = wp - 5\\n    w, done = _lambertw_series(ctx, z, k, tol)\\n    if not done:\\n        # Use Halley iteration to solve w*exp(w) = z\\n        two = ctx.mpf(2)\\n        for i in xrange(100):\\n            ew = ctx.exp(w)\\n            wew = w*ew\\n            wewz = wew-z\\n            wn = w - wewz/(wew+ew-(w+two)*wewz/(two*w+two))\\n            if ctx.mag(wn-w) <= ctx.mag(wn) - tol:\\n                w = wn\\n                break\\n            else:\\n                w = wn\\n        if i == 100:\\n            ctx.warn(\\\"Lambert W iteration failed to converge for z = %s\\\" % z)\\n    ctx.prec = prec\\n    return +w\\n\\n@defun_wrapped\\ndef bell(ctx, n, x=1):\\n    x = ctx.convert(x)\\n    if not n:\\n        if ctx.isnan(x):\\n            return x\\n        return type(x)(1)\\n    if ctx.isinf(x) or ctx.isinf(n) or ctx.isnan(x) or ctx.isnan(n):\\n        return x**n\\n    if n == 1: return x\\n    if n == 2: return x*(x+1)\\n    if x == 0: return ctx.sincpi(n)\\n    return _polyexp(ctx, n, x, True) / ctx.exp(x)\\n\\ndef _polyexp(ctx, n, x, extra=False):\\n    def _terms():\\n        if extra:\\n            yield ctx.sincpi(n)\\n        t = x\\n        k = 1\\n        while 1:\\n            yield k**n * t\\n            k += 1\\n            t = t*x/k\\n    return ctx.sum_accurately(_terms, check_step=4)\\n\\n@defun_wrapped\\ndef polyexp(ctx, s, z):\\n    if ctx.isinf(z) or ctx.isinf(s) or ctx.isnan(z) or ctx.isnan(s):\\n        return z**s\\n    if z == 0: return z*s\\n    if s == 0: return ctx.expm1(z)\\n    if s == 1: return ctx.exp(z)*z\\n    if s == 2: return ctx.exp(z)*z*(z+1)\\n    return _polyexp(ctx, s, z)\\n\\n@defun_wrapped\\ndef cyclotomic(ctx, n, z):\\n    n = int(n)\\n    if n < 0:\\n        raise ValueError(\\\"n cannot be negative\\\")\\n    p = ctx.one\\n    if n == 0:\\n        return p\\n    if n == 1:\\n        return z - p\\n    if n == 2:\\n        return z + p\\n    # Use divisor product representation. Unfortunately, this sometimes\\n    # includes singularities for roots of unity, which we have to cancel out.\\n    # Matching zeros/poles pairwise, we have (1-z^a)/(1-z^b) ~ a/b + O(z-1).\\n    a_prod = 1\\n    b_prod = 1\\n    num_zeros = 0\\n    num_poles = 0\\n    for d in range(1,n+1):\\n        if not n % d:\\n            w = ctx.moebius(n//d)\\n            # Use powm1 because it is important that we get 0 only\\n            # if it really is exactly 0\\n            b = -ctx.powm1(z, d)\\n            if b:\\n                p *= b**w\\n            else:\\n                if w == 1:\\n                    a_prod *= d\\n                    num_zeros += 1\\n                elif w == -1:\\n                    b_prod *= d\\n                    num_poles += 1\\n    #print n, num_zeros, num_poles\\n    if num_zeros:\\n        if num_zeros > num_poles:\\n            p *= 0\\n        else:\\n            p *= a_prod\\n            p /= b_prod\\n    return p\\n\\n@defun\\ndef mangoldt(ctx, n):\\n    r\\\"\\\"\\\"\\n    Evaluates the von Mangoldt function `\\\\Lambda(n) = \\\\log p`\\n    if `n = p^k` a power of a prime, and `\\\\Lambda(n) = 0` otherwise.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> [mangoldt(n) for n in range(-2,3)]\\n        [0.0, 0.0, 0.0, 0.0, 0.6931471805599453094172321]\\n        >>> mangoldt(6)\\n        0.0\\n        >>> mangoldt(7)\\n        1.945910149055313305105353\\n        >>> mangoldt(8)\\n        0.6931471805599453094172321\\n        >>> fsum(mangoldt(n) for n in range(101))\\n        94.04531122935739224600493\\n        >>> fsum(mangoldt(n) for n in range(10001))\\n        10013.39669326311478372032\\n\\n    \\\"\\\"\\\"\\n    n = int(n)\\n    if n < 2:\\n        return ctx.zero\\n    if n % 2 == 0:\\n        # Must be a power of two\\n        if n & (n-1) == 0:\\n            return +ctx.ln2\\n        else:\\n            return ctx.zero\\n    # TODO: the following could be generalized into a perfect\\n    # power testing function\\n    # ---\\n    # Look for a small factor\\n    for p in (3,5,7,11,13,17,19,23,29,31):\\n        if not n % p:\\n            q, r = n // p, 0\\n            while q > 1:\\n                q, r = divmod(q, p)\\n                if r:\\n                    return ctx.zero\\n            return ctx.ln(p)\\n    if ctx.isprime(n):\\n        return ctx.ln(n)\\n    # Obviously, we could use arbitrary-precision arithmetic for this...\\n    if n > 10**30:\\n        raise NotImplementedError\\n    k = 2\\n    while 1:\\n        p = int(n**(1./k) + 0.5)\\n        if p < 2:\\n            return ctx.zero\\n        if p ** k == n:\\n            if ctx.isprime(p):\\n                return ctx.ln(p)\\n        k += 1\\n\\n@defun\\ndef stirling1(ctx, n, k, exact=False):\\n    v = ctx._stirling1(int(n), int(k))\\n    if exact:\\n        return int(v)\\n    else:\\n        return ctx.mpf(v)\\n\\n@defun\\ndef stirling2(ctx, n, k, exact=False):\\n    v = ctx._stirling2(int(n), int(k))\\n    if exact:\\n        return int(v)\\n    else:\\n        return ctx.mpf(v)\\n\\n\\nfrom ..libmp.backend import xrange\\nfrom .functions import defun, defun_wrapped\\n\\n@defun\\ndef gammaprod(ctx, a, b, _infsign=False):\\n    a = [ctx.convert(x) for x in a]\\n    b = [ctx.convert(x) for x in b]\\n    poles_num = []\\n    poles_den = []\\n    regular_num = []\\n    regular_den = []\\n    for x in a: [regular_num, poles_num][ctx.isnpint(x)].append(x)\\n    for x in b: [regular_den, poles_den][ctx.isnpint(x)].append(x)\\n    # One more pole in numerator or denominator gives 0 or inf\\n    if len(poles_num) < len(poles_den): return ctx.zero\\n    if len(poles_num) > len(poles_den):\\n        # Get correct sign of infinity for x+h, h -> 0 from above\\n        # XXX: hack, this should be done properly\\n        if _infsign:\\n            a = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_num]\\n            b = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_den]\\n            return ctx.sign(ctx.gammaprod(a+regular_num,b+regular_den)) * ctx.inf\\n        else:\\n            return ctx.inf\\n    # All poles cancel\\n    # lim G(i)/G(j) = (-1)**(i+j) * gamma(1-j) / gamma(1-i)\\n    p = ctx.one\\n    orig = ctx.prec\\n    try:\\n        ctx.prec = orig + 15\\n        while poles_num:\\n            i = poles_num.pop()\\n            j = poles_den.pop()\\n            p *= (-1)**(i+j) * ctx.gamma(1-j) / ctx.gamma(1-i)\\n        for x in regular_num: p *= ctx.gamma(x)\\n        for x in regular_den: p /= ctx.gamma(x)\\n    finally:\\n        ctx.prec = orig\\n    return +p\\n\\n@defun\\ndef beta(ctx, x, y):\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    if ctx.isinf(y):\\n        x, y = y, x\\n    if ctx.isinf(x):\\n        if x == ctx.inf and not ctx._im(y):\\n            if y == ctx.ninf:\\n                return ctx.nan\\n            if y > 0:\\n                return ctx.zero\\n            if ctx.isint(y):\\n                return ctx.nan\\n            if y < 0:\\n                return ctx.sign(ctx.gamma(y)) * ctx.inf\\n        return ctx.nan\\n    xy = ctx.fadd(x, y, prec=2*ctx.prec)\\n    return ctx.gammaprod([x, y], [xy])\\n\\n@defun\\ndef binomial(ctx, n, k):\\n    n1 = ctx.fadd(n, 1, prec=2*ctx.prec)\\n    k1 = ctx.fadd(k, 1, prec=2*ctx.prec)\\n    nk1 = ctx.fsub(n1, k, prec=2*ctx.prec)\\n    return ctx.gammaprod([n1], [k1, nk1])\\n\\n@defun\\ndef rf(ctx, x, n):\\n    xn = ctx.fadd(x, n, prec=2*ctx.prec)\\n    return ctx.gammaprod([xn], [x])\\n\\n@defun\\ndef ff(ctx, x, n):\\n    x1 = ctx.fadd(x, 1, prec=2*ctx.prec)\\n    xn1 = ctx.fadd(ctx.fsub(x, n, prec=2*ctx.prec), 1, prec=2*ctx.prec)\\n    return ctx.gammaprod([x1], [xn1])\\n\\n@defun_wrapped\\ndef fac2(ctx, x):\\n    if ctx.isinf(x):\\n        if x == ctx.inf:\\n            return x\\n        return ctx.nan\\n    return 2**(x/2)*(ctx.pi/2)**((ctx.cospi(x)-1)/4)*ctx.gamma(x/2+1)\\n\\n@defun_wrapped\\ndef barnesg(ctx, z):\\n    if ctx.isinf(z):\\n        if z == ctx.inf:\\n            return z\\n        return ctx.nan\\n    if ctx.isnan(z):\\n        return z\\n    if (not ctx._im(z)) and ctx._re(z) <= 0 and ctx.isint(ctx._re(z)):\\n        return z*0\\n    # Account for size (would not be needed if computing log(G))\\n    if abs(z) > 5:\\n        ctx.dps += 2*ctx.log(abs(z),2)\\n    # Reflection formula\\n    if ctx.re(z) < -ctx.dps:\\n        w = 1-z\\n        pi2 = 2*ctx.pi\\n        u = ctx.expjpi(2*w)\\n        v = ctx.j*ctx.pi/12 - ctx.j*ctx.pi*w**2/2 + w*ctx.ln(1-u) - \\\\\\n            ctx.j*ctx.polylog(2, u)/pi2\\n        v = ctx.barnesg(2-z)*ctx.exp(v)/pi2**w\\n        if ctx._is_real_type(z):\\n            v = ctx._re(v)\\n        return v\\n    # Estimate terms for asymptotic expansion\\n    # TODO: fixme, obviously\\n    N = ctx.dps // 2 + 5\\n    G = 1\\n    while abs(z) < N or ctx.re(z) < 1:\\n        G /= ctx.gamma(z)\\n        z += 1\\n    z -= 1\\n    s = ctx.mpf(1)/12\\n    s -= ctx.log(ctx.glaisher)\\n    s += z*ctx.log(2*ctx.pi)/2\\n    s += (z**2/2-ctx.mpf(1)/12)*ctx.log(z)\\n    s -= 3*z**2/4\\n    z2k = z2 = z**2\\n    for k in xrange(1, N+1):\\n        t = ctx.bernoulli(2*k+2) / (4*k*(k+1)*z2k)\\n        if abs(t) < ctx.eps:\\n            #print k, N      # check how many terms were needed\\n            break\\n        z2k *= z2\\n        s += t\\n    #if k == N:\\n    #    print \\\"warning: series for barnesg failed to converge\\\", ctx.dps\\n    return G*ctx.exp(s)\\n\\n@defun\\ndef superfac(ctx, z):\\n    return ctx.barnesg(z+2)\\n\\n@defun_wrapped\\ndef hyperfac(ctx, z):\\n    # XXX: estimate needed extra bits accurately\\n    if z == ctx.inf:\\n        return z\\n    if abs(z) > 5:\\n        extra = 4*int(ctx.log(abs(z),2))\\n    else:\\n        extra = 0\\n    ctx.prec += extra\\n    if not ctx._im(z) and ctx._re(z) < 0 and ctx.isint(ctx._re(z)):\\n        n = int(ctx.re(z))\\n        h = ctx.hyperfac(-n-1)\\n        if ((n+1)//2) & 1:\\n            h = -h\\n        if ctx._is_complex_type(z):\\n            return h + 0j\\n        return h\\n    zp1 = z+1\\n    # Wrong branch cut\\n    #v = ctx.gamma(zp1)**z\\n    #ctx.prec -= extra\\n    #return v / ctx.barnesg(zp1)\\n    v = ctx.exp(z*ctx.loggamma(zp1))\\n    ctx.prec -= extra\\n    return v / ctx.barnesg(zp1)\\n\\n'''\\n@defun\\ndef psi0(ctx, z):\\n    \\\"\\\"\\\"Shortcut for psi(0,z) (the digamma function)\\\"\\\"\\\"\\n    return ctx.psi(0, z)\\n\\n@defun\\ndef psi1(ctx, z):\\n    \\\"\\\"\\\"Shortcut for psi(1,z) (the trigamma function)\\\"\\\"\\\"\\n    return ctx.psi(1, z)\\n\\n@defun\\ndef psi2(ctx, z):\\n    \\\"\\\"\\\"Shortcut for psi(2,z) (the tetragamma function)\\\"\\\"\\\"\\n    return ctx.psi(2, z)\\n\\n@defun\\ndef psi3(ctx, z):\\n    \\\"\\\"\\\"Shortcut for psi(3,z) (the pentagamma function)\\\"\\\"\\\"\\n    return ctx.psi(3, z)\\n'''\\n\\n\\nfrom .functions import defun, defun_wrapped\\n\\n@defun\\ndef j0(ctx, x):\\n    \\\"\\\"\\\"Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.\\\"\\\"\\\"\\n    return ctx.besselj(0, x)\\n\\n@defun\\ndef j1(ctx, x):\\n    \\\"\\\"\\\"Computes the Bessel function `J_1(x)`.  See :func:`~mpmath.besselj`.\\\"\\\"\\\"\\n    return ctx.besselj(1, x)\\n\\n@defun\\ndef besselj(ctx, n, z, derivative=0, **kwargs):\\n    if type(n) is int:\\n        n_isint = True\\n    else:\\n        n = ctx.convert(n)\\n        n_isint = ctx.isint(n)\\n        if n_isint:\\n            n = int(ctx._re(n))\\n    if n_isint and n < 0:\\n        return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs)\\n    z = ctx.convert(z)\\n    M = ctx.mag(z)\\n    if derivative:\\n        d = ctx.convert(derivative)\\n        # TODO: the integer special-casing shouldn't be necessary.\\n        # However, the hypergeometric series gets inaccurate for large d\\n        # because of inaccurate pole cancellation at a pole far from\\n        # zero (needs to be fixed in hypercomb or hypsum)\\n        if ctx.isint(d) and d >= 0:\\n            d = int(d)\\n            orig = ctx.prec\\n            try:\\n                ctx.prec += 15\\n                v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z)\\n                    for k in range(d+1))\\n            finally:\\n                ctx.prec = orig\\n            v *= ctx.mpf(2)**(-d)\\n        else:\\n            def h(n,d):\\n                r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True)\\n                B = [0.5*(n-d+1), 0.5*(n-d+2)]\\n                T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)]\\n                return T\\n            v = ctx.hypercomb(h, [n,d], **kwargs)\\n    else:\\n        # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation\\n        if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20:\\n            try:\\n                return ctx._besselj(n, z)\\n            except NotImplementedError:\\n                pass\\n        if not z:\\n            if not n:\\n                v = ctx.one + n+z\\n            elif ctx.re(n) > 0:\\n                v = n*z\\n            else:\\n                v = ctx.inf + z + n\\n        else:\\n            #v = 0\\n            orig = ctx.prec\\n            try:\\n                # XXX: workaround for accuracy in low level hypergeometric series\\n                # when alternating, large arguments\\n                ctx.prec += min(3*abs(M), ctx.prec)\\n                w = ctx.fmul(z, 0.5, exact=True)\\n                def h(n):\\n                    r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True)\\n                    return [([w], [n], [], [n+1], [], [n+1], r)]\\n                v = ctx.hypercomb(h, [n], **kwargs)\\n            finally:\\n                ctx.prec = orig\\n        v = +v\\n    return v\\n\\n@defun\\ndef besseli(ctx, n, z, derivative=0, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    if not z:\\n        if derivative:\\n            raise ValueError\\n        if not n:\\n            # I(0,0) = 1\\n            return 1+n+z\\n        if ctx.isint(n):\\n            return 0*(n+z)\\n        r = ctx.re(n)\\n        if r == 0:\\n            return ctx.nan*(n+z)\\n        elif r > 0:\\n            return 0*(n+z)\\n        else:\\n            return ctx.inf+(n+z)\\n    M = ctx.mag(z)\\n    if derivative:\\n        d = ctx.convert(derivative)\\n        def h(n,d):\\n            r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True)\\n            B = [0.5*(n-d+1), 0.5*(n-d+2), n+1]\\n            T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)]\\n            return T\\n        v = ctx.hypercomb(h, [n,d], **kwargs)\\n    else:\\n        def h(n):\\n            w = ctx.fmul(z, 0.5, exact=True)\\n            r = ctx.fmul(w, w, prec=max(0,ctx.prec+M))\\n            return [([w], [n], [], [n+1], [], [n+1], r)]\\n        v = ctx.hypercomb(h, [n], **kwargs)\\n    return v\\n\\n@defun_wrapped\\ndef bessely(ctx, n, z, derivative=0, **kwargs):\\n    if not z:\\n        if derivative:\\n            # Not implemented\\n            raise ValueError\\n        if not n:\\n            # ~ log(z/2)\\n            return -ctx.inf + (n+z)\\n        if ctx.im(n):\\n            return ctx.nan * (n+z)\\n        r = ctx.re(n)\\n        q = n+0.5\\n        if ctx.isint(q):\\n            if n > 0:\\n                return -ctx.inf + (n+z)\\n            else:\\n                return 0 * (n+z)\\n        if r < 0 and int(ctx.floor(q)) % 2:\\n            return ctx.inf + (n+z)\\n        else:\\n            return ctx.ninf + (n+z)\\n    # XXX: use hypercomb\\n    ctx.prec += 10\\n    m, d = ctx.nint_distance(n)\\n    if d < -ctx.prec:\\n        h = +ctx.eps\\n        ctx.prec *= 2\\n        n += h\\n    elif d < 0:\\n        ctx.prec -= d\\n    # TODO: avoid cancellation for imaginary arguments\\n    cos, sin = ctx.cospi_sinpi(n)\\n    return (ctx.besselj(n,z,derivative,**kwargs)*cos - \\\\\\n        ctx.besselj(-n,z,derivative,**kwargs))/sin\\n\\n@defun_wrapped\\ndef besselk(ctx, n, z, **kwargs):\\n    if not z:\\n        return ctx.inf\\n    M = ctx.mag(z)\\n    if M < 1:\\n        # Represent as limit definition\\n        def h(n):\\n            r = (z/2)**2\\n            T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r\\n            T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r\\n            return T1, T2\\n    # We could use the limit definition always, but it leads\\n    # to very bad cancellation (of exponentially large terms)\\n    # for large real z\\n    # Instead represent in terms of 2F0\\n    else:\\n        ctx.prec += M\\n        def h(n):\\n            return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \\\\\\n                [n+0.5, 0.5-n], [], -1/(2*z))]\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun_wrapped\\ndef hankel1(ctx,n,x,**kwargs):\\n    return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs)\\n\\n@defun_wrapped\\ndef hankel2(ctx,n,x,**kwargs):\\n    return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs)\\n\\n@defun_wrapped\\ndef whitm(ctx,k,m,z,**kwargs):\\n    if z == 0:\\n        # M(k,m,z) = 0^(1/2+m)\\n        if ctx.re(m) > -0.5:\\n            return z\\n        elif ctx.re(m) < -0.5:\\n            return ctx.inf + z\\n        else:\\n            return ctx.nan * z\\n    x = ctx.fmul(-0.5, z, exact=True)\\n    y = 0.5+m\\n    return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs)\\n\\n@defun_wrapped\\ndef whitw(ctx,k,m,z,**kwargs):\\n    if z == 0:\\n        g = abs(ctx.re(m))\\n        if g < 0.5:\\n            return z\\n        elif g > 0.5:\\n            return ctx.inf + z\\n        else:\\n            return ctx.nan * z\\n    x = ctx.fmul(-0.5, z, exact=True)\\n    y = 0.5+m\\n    return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs)\\n\\n@defun\\ndef hyperu(ctx, a, b, z, **kwargs):\\n    a, atype = ctx._convert_param(a)\\n    b, btype = ctx._convert_param(b)\\n    z = ctx.convert(z)\\n    if not z:\\n        if ctx.re(b) <= 1:\\n            return ctx.gammaprod([1-b],[a-b+1])\\n        else:\\n            return ctx.inf + z\\n    bb = 1+a-b\\n    bb, bbtype = ctx._convert_param(bb)\\n    try:\\n        orig = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec)\\n            return v / z**a\\n        finally:\\n            ctx.prec = orig\\n    except ctx.NoConvergence:\\n        pass\\n    def h(a,b):\\n        w = ctx.sinpi(b)\\n        T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z)\\n        T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z)\\n        return T1, T2\\n    return ctx.hypercomb(h, [a,b], **kwargs)\\n\\n@defun\\ndef struveh(ctx,n,z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/\\n    def h(n):\\n        return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)]\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun\\ndef struvel(ctx,n,z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/\\n    def h(n):\\n        return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)]\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\ndef _anger(ctx,which,v,z,**kwargs):\\n    v = ctx._convert_param(v)[0]\\n    z = ctx.convert(z)\\n    def h(v):\\n        b = ctx.mpq_1_2\\n        u = v*b\\n        m = b*3\\n        a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u\\n        c, s = ctx.cospi_sinpi(u)\\n        if which == 0:\\n            A, B = [b*z, s], [c]\\n        if which == 1:\\n            A, B = [b*z, -c], [s]\\n        w = ctx.square_exp_arg(z, mult=-0.25)\\n        T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w\\n        T2 = B, [1], [], [b1,b2], [1], [b1,b2], w\\n        return T1, T2\\n    return ctx.hypercomb(h, [v], **kwargs)\\n\\n@defun\\ndef angerj(ctx, v, z, **kwargs):\\n    return _anger(ctx, 0, v, z, **kwargs)\\n\\n@defun\\ndef webere(ctx, v, z, **kwargs):\\n    return _anger(ctx, 1, v, z, **kwargs)\\n\\n@defun\\ndef lommels1(ctx, u, v, z, **kwargs):\\n    u = ctx._convert_param(u)[0]\\n    v = ctx._convert_param(v)[0]\\n    z = ctx.convert(z)\\n    def h(u,v):\\n        b = ctx.mpq_1_2\\n        w = ctx.square_exp_arg(z, mult=-0.25)\\n        return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \\\\\\n            [b*(u-v+3),b*(u+v+3)], w),\\n    return ctx.hypercomb(h, [u,v], **kwargs)\\n\\n@defun\\ndef lommels2(ctx, u, v, z, **kwargs):\\n    u = ctx._convert_param(u)[0]\\n    v = ctx._convert_param(v)[0]\\n    z = ctx.convert(z)\\n    # Asymptotic expansion (GR p. 947) -- need to be careful\\n    # not to use for small arguments\\n    # def h(u,v):\\n    #    b = ctx.mpq_1_2\\n    #    w = -(z/2)**(-2)\\n    #    return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w),\\n    def h(u,v):\\n        b = ctx.mpq_1_2\\n        w = ctx.square_exp_arg(z, mult=-0.25)\\n        T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w\\n        T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w\\n        T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w\\n        #c1 = ctx.cospi((u-v)*b)\\n        #c2 = ctx.cospi((u+v)*b)\\n        #s = ctx.sinpi(v)\\n        #r1 = (u-v+1)*b\\n        #r2 = (u+v+1)*b\\n        #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w\\n        #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w\\n        #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w\\n        #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w\\n        return T1, T2, T3\\n    return ctx.hypercomb(h, [u,v], **kwargs)\\n\\n@defun\\ndef ber(ctx, n, z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/\\n    def h(n):\\n        r = -(z/4)**4\\n        cos, sin = ctx.cospi_sinpi(-0.75*n)\\n        T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r\\n        T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r\\n        return T1, T2\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun\\ndef bei(ctx, n, z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/\\n    def h(n):\\n        r = -(z/4)**4\\n        cos, sin = ctx.cospi_sinpi(0.75*n)\\n        T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r\\n        T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r\\n        return T1, T2\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun\\ndef ker(ctx, n, z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/\\n    def h(n):\\n        r = -(z/4)**4\\n        cos1, sin1 = ctx.cospi_sinpi(0.25*n)\\n        cos2, sin2 = ctx.cospi_sinpi(0.75*n)\\n        T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r\\n        T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r\\n        T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r\\n        T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r\\n        return T1, T2, T3, T4\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun\\ndef kei(ctx, n, z, **kwargs):\\n    n = ctx.convert(n)\\n    z = ctx.convert(z)\\n    # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/\\n    def h(n):\\n        r = -(z/4)**4\\n        cos1, sin1 = ctx.cospi_sinpi(0.75*n)\\n        cos2, sin2 = ctx.cospi_sinpi(0.25*n)\\n        T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r\\n        T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r\\n        T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r\\n        T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r\\n        return T1, T2, T3, T4\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n# TODO: do this more generically?\\ndef c_memo(f):\\n    name = f.__name__\\n    def f_wrapped(ctx):\\n        cache = ctx._misc_const_cache\\n        prec = ctx.prec\\n        p,v = cache.get(name, (-1,0))\\n        if p >= prec:\\n            return +v\\n        else:\\n            cache[name] = (prec, f(ctx))\\n            return cache[name][1]\\n    return f_wrapped\\n\\n@c_memo\\ndef _airyai_C1(ctx):\\n    return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3))\\n\\n@c_memo\\ndef _airyai_C2(ctx):\\n    return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3))\\n\\n@c_memo\\ndef _airybi_C1(ctx):\\n    return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3))\\n\\n@c_memo\\ndef _airybi_C2(ctx):\\n    return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3)\\n\\ndef _airybi_n2_inf(ctx):\\n    prec = ctx.prec\\n    try:\\n        v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\n# Derivatives at z = 0\\n# TODO: could be expressed more elegantly using triple factorials\\ndef _airyderiv_0(ctx, z, n, ntype, which):\\n    if ntype == 'Z':\\n        if n < 0:\\n            return z\\n        r = ctx.mpq_1_3\\n        prec = ctx.prec\\n        try:\\n            ctx.prec += 10\\n            v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi\\n            if which == 0:\\n                v *= ctx.sinpi(2*(n+1)*r)\\n                v /= ctx.power(3,'2/3')\\n            else:\\n                v *= abs(ctx.sinpi(2*(n+1)*r))\\n                v /= ctx.power(3,'1/6')\\n        finally:\\n            ctx.prec = prec\\n        return +v + z\\n    else:\\n        # singular (does the limit exist?)\\n        raise NotImplementedError\\n\\n@defun\\ndef airyai(ctx, z, derivative=0, **kwargs):\\n    z = ctx.convert(z)\\n    if derivative:\\n        n, ntype = ctx._convert_param(derivative)\\n    else:\\n        n = 0\\n    # Values at infinities\\n    if not ctx.isnormal(z) and z:\\n        if n and ntype == 'Z':\\n            if n == -1:\\n                if z == ctx.inf:\\n                    return ctx.mpf(1)/3 + 1/z\\n                if z == ctx.ninf:\\n                    return ctx.mpf(-2)/3 + 1/z\\n            if n < -1:\\n                if z == ctx.inf:\\n                    return z\\n                if z == ctx.ninf:\\n                    return (-1)**n * (-z)\\n        if (not n) and z == ctx.inf or z == ctx.ninf:\\n            return 1/z\\n        # TODO: limits\\n        raise ValueError(\\\"essential singularity of Ai(z)\\\")\\n    # Account for exponential scaling\\n    if z:\\n        extraprec = max(0, int(1.5*ctx.mag(z)))\\n    else:\\n        extraprec = 0\\n    if n:\\n        if n == 1:\\n            def h():\\n                # http://functions.wolfram.com/03.07.06.0005.01\\n                if ctx._re(z) > 4:\\n                    ctx.prec += extraprec\\n                    w = z**1.5; r = -0.75/w; u = -2*w/3\\n                    ctx.prec -= extraprec\\n                    C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4)\\n                    return ([C],[1],[],[],[(-1,6),(7,6)],[],r),\\n                # http://functions.wolfram.com/03.07.26.0001.01\\n                else:\\n                    ctx.prec += extraprec\\n                    w = z**3 / 9\\n                    ctx.prec -= extraprec\\n                    C1 = _airyai_C1(ctx) * 0.5\\n                    C2 = _airyai_C2(ctx)\\n                    T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w\\n                    T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w\\n                    return T1, T2\\n            return ctx.hypercomb(h, [], **kwargs)\\n        else:\\n            if z == 0:\\n                return _airyderiv_0(ctx, z, n, ntype, 0)\\n            # http://functions.wolfram.com/03.05.20.0004.01\\n            def h(n):\\n                ctx.prec += extraprec\\n                w = z**3/9\\n                ctx.prec -= extraprec\\n                q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3\\n                a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13\\n                T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \\\\\\n                    [a1,a2], [b1,b2,b3], w\\n                a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13\\n                T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \\\\\\n                    [a1,a2], [b1,b2,b3], w\\n                return T1, T2\\n            v = ctx.hypercomb(h, [n], **kwargs)\\n            if ctx._is_real_type(z) and ctx.isint(n):\\n                v = ctx._re(v)\\n            return v\\n    else:\\n        def h():\\n            if ctx._re(z) > 4:\\n                # We could use 1F1, but it results in huge cancellation;\\n                # the following expansion is better.\\n                # TODO: asymptotic series for derivatives\\n                ctx.prec += extraprec\\n                w = z**1.5; r = -0.75/w; u = -2*w/3\\n                ctx.prec -= extraprec\\n                C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4))\\n                return ([C],[1],[],[],[(1,6),(5,6)],[],r),\\n            else:\\n                ctx.prec += extraprec\\n                w = z**3 / 9\\n                ctx.prec -= extraprec\\n                C1 = _airyai_C1(ctx)\\n                C2 = _airyai_C2(ctx)\\n                T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w\\n                T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w\\n                return T1, T2\\n        return ctx.hypercomb(h, [], **kwargs)\\n\\n@defun\\ndef airybi(ctx, z, derivative=0, **kwargs):\\n    z = ctx.convert(z)\\n    if derivative:\\n        n, ntype = ctx._convert_param(derivative)\\n    else:\\n        n = 0\\n    # Values at infinities\\n    if not ctx.isnormal(z) and z:\\n        if n and ntype == 'Z':\\n            if z == ctx.inf:\\n                return z\\n            if z == ctx.ninf:\\n                if n == -1:\\n                    return 1/z\\n                if n == -2:\\n                    return _airybi_n2_inf(ctx)\\n                if n < -2:\\n                    return (-1)**n * (-z)\\n        if not n:\\n            if z == ctx.inf:\\n                return z\\n            if z == ctx.ninf:\\n                return 1/z\\n        # TODO: limits\\n        raise ValueError(\\\"essential singularity of Bi(z)\\\")\\n    if z:\\n        extraprec = max(0, int(1.5*ctx.mag(z)))\\n    else:\\n        extraprec = 0\\n    if n:\\n        if n == 1:\\n            # http://functions.wolfram.com/03.08.26.0001.01\\n            def h():\\n                ctx.prec += extraprec\\n                w = z**3 / 9\\n                ctx.prec -= extraprec\\n                C1 = _airybi_C1(ctx)*0.5\\n                C2 = _airybi_C2(ctx)\\n                T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w\\n                T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w\\n                return T1, T2\\n            return ctx.hypercomb(h, [], **kwargs)\\n        else:\\n            if z == 0:\\n                return _airyderiv_0(ctx, z, n, ntype, 1)\\n            def h(n):\\n                ctx.prec += extraprec\\n                w = z**3/9\\n                ctx.prec -= extraprec\\n                q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3\\n                q16 = ctx.mpq_1_6\\n                q56 = ctx.mpq_5_6\\n                a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13\\n                T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \\\\\\n                    [a1,a2], [b1,b2,b3], w\\n                a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13\\n                T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \\\\\\n                    [a1,a2], [b1,b2,b3], w\\n                return T1, T2\\n            v = ctx.hypercomb(h, [n], **kwargs)\\n            if ctx._is_real_type(z) and ctx.isint(n):\\n                v = ctx._re(v)\\n            return v\\n    else:\\n        def h():\\n            ctx.prec += extraprec\\n            w = z**3 / 9\\n            ctx.prec -= extraprec\\n            C1 = _airybi_C1(ctx)\\n            C2 = _airybi_C2(ctx)\\n            T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w\\n            T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w\\n            return T1, T2\\n        return ctx.hypercomb(h, [], **kwargs)\\n\\ndef _airy_zero(ctx, which, k, derivative, complex=False):\\n    # Asymptotic formulas are given in DLMF section 9.9\\n    def U(t): return t**(2/3.)*(1-7/(t**2*48))\\n    def T(t): return t**(2/3.)*(1+5/(t**2*48))\\n    k = int(k)\\n    if k < 1:\\n        raise ValueError(\\\"k cannot be less than 1\\\")\\n    if not derivative in (0,1):\\n        raise ValueError(\\\"Derivative should lie between 0 and 1\\\")\\n    if which == 0:\\n        if derivative:\\n            return ctx.findroot(lambda z: ctx.airyai(z,1),\\n                -U(3*ctx.pi*(4*k-3)/8))\\n        return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8))\\n    if which == 1 and complex == False:\\n        if derivative:\\n            return ctx.findroot(lambda z: ctx.airybi(z,1),\\n                -U(3*ctx.pi*(4*k-1)/8))\\n        return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8))\\n    if which == 1 and complex == True:\\n        if derivative:\\n            t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2\\n            s = ctx.expjpi(ctx.mpf(1)/3) * T(t)\\n            return ctx.findroot(lambda z: ctx.airybi(z,1), s)\\n        t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2\\n        s = ctx.expjpi(ctx.mpf(1)/3) * U(t)\\n        return ctx.findroot(ctx.airybi, s)\\n\\n@defun\\ndef airyaizero(ctx, k, derivative=0):\\n    return _airy_zero(ctx, 0, k, derivative, False)\\n\\n@defun\\ndef airybizero(ctx, k, derivative=0, complex=False):\\n    return _airy_zero(ctx, 1, k, derivative, complex)\\n\\ndef _scorer(ctx, z, which, kwargs):\\n    z = ctx.convert(z)\\n    if ctx.isinf(z):\\n        if z == ctx.inf:\\n            if which == 0: return 1/z\\n            if which == 1: return z\\n        if z == ctx.ninf:\\n            return 1/z\\n        raise ValueError(\\\"essential singularity\\\")\\n    if z:\\n        extraprec = max(0, int(1.5*ctx.mag(z)))\\n    else:\\n        extraprec = 0\\n    if kwargs.get('derivative'):\\n        raise NotImplementedError\\n    # Direct asymptotic expansions, to avoid\\n    # exponentially large cancellation\\n    try:\\n        if ctx.mag(z) > 3:\\n            if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999:\\n                def h():\\n                    return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),)\\n                return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True)\\n            if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999:\\n                def h():\\n                    return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),)\\n                return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True)\\n    except ctx.NoConvergence:\\n        pass\\n    def h():\\n        A = ctx.airybi(z, **kwargs)/3\\n        B = -2*ctx.pi\\n        if which == 1:\\n            A *= 2\\n            B *= -1\\n        ctx.prec += extraprec\\n        w = z**3/9\\n        ctx.prec -= extraprec\\n        T1 = [A], [1], [], [], [], [], 0\\n        T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w\\n        return T1, T2\\n    return ctx.hypercomb(h, [], **kwargs)\\n\\n@defun\\ndef scorergi(ctx, z, **kwargs):\\n    return _scorer(ctx, z, 0, kwargs)\\n\\n@defun\\ndef scorerhi(ctx, z, **kwargs):\\n    return _scorer(ctx, z, 1, kwargs)\\n\\n@defun_wrapped\\ndef coulombc(ctx, l, eta, _cache={}):\\n    if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec:\\n        return +_cache[l,eta][1]\\n    G3 = ctx.loggamma(2*l+2)\\n    G1 = ctx.loggamma(1+l+ctx.j*eta)\\n    G2 = ctx.loggamma(1+l-ctx.j*eta)\\n    v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3)\\n    if not (ctx.im(l) or ctx.im(eta)):\\n        v = ctx.re(v)\\n    _cache[l,eta] = (ctx.prec, v)\\n    return v\\n\\n@defun_wrapped\\ndef coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs):\\n    # Regular Coulomb wave function\\n    # Note: w can be either 1 or -1; the other may be better in some cases\\n    # TODO: check that chop=True chops when and only when it should\\n    #ctx.prec += 10\\n    def h(l, eta):\\n        try:\\n            jw = ctx.j*w\\n            jwz = ctx.fmul(jw, z, exact=True)\\n            jwz2 = ctx.fmul(jwz, -2, exact=True)\\n            C = ctx.coulombc(l, eta)\\n            T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \\\\\\n                [2*l+2], jwz2\\n        except ValueError:\\n            T1 = [0], [-1], [], [], [], [], 0\\n        return (T1,)\\n    v = ctx.hypercomb(h, [l,eta], **kwargs)\\n    if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \\\\\\n        (ctx.re(z) >= 0):\\n        v = ctx.re(v)\\n    return v\\n\\n@defun_wrapped\\ndef _coulomb_chi(ctx, l, eta, _cache={}):\\n    if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec:\\n        return _cache[l,eta][1]\\n    def terms():\\n        l2 = -l-1\\n        jeta = ctx.j*eta\\n        return [ctx.loggamma(1+l+jeta) * (-0.5j),\\n            ctx.loggamma(1+l-jeta) * (0.5j),\\n            ctx.loggamma(1+l2+jeta) * (0.5j),\\n            ctx.loggamma(1+l2-jeta) * (-0.5j),\\n            -(l+0.5)*ctx.pi]\\n    v = ctx.sum_accurately(terms, 1)\\n    _cache[l,eta] = (ctx.prec, v)\\n    return v\\n\\n@defun_wrapped\\ndef coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs):\\n    # Irregular Coulomb wave function\\n    # Note: w can be either 1 or -1; the other may be better in some cases\\n    # TODO: check that chop=True chops when and only when it should\\n    if not ctx._im(l):\\n        l = ctx._re(l)  # XXX: for isint\\n    def h(l, eta):\\n        # Force perturbation for integers and half-integers\\n        if ctx.isint(l*2):\\n            T1 = [0], [-1], [], [], [], [], 0\\n            return (T1,)\\n        l2 = -l-1\\n        try:\\n            chi = ctx._coulomb_chi(l, eta)\\n            jw = ctx.j*w\\n            s = ctx.sin(chi); c = ctx.cos(chi)\\n            C1 = ctx.coulombc(l,eta)\\n            C2 = ctx.coulombc(l2,eta)\\n            u = ctx.exp(jw*z)\\n            x = -2*jw*z\\n            T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \\\\\\n                [1+l+jw*eta], [2*l+2], x\\n            T2 = [-s, C2, z, u],   [-1, 1, l2+1, 1],    [], [], \\\\\\n                [1+l2+jw*eta], [2*l2+2], x\\n            return T1, T2\\n        except ValueError:\\n            T1 = [0], [-1], [], [], [], [], 0\\n            return (T1,)\\n    v = ctx.hypercomb(h, [l,eta], **kwargs)\\n    if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \\\\\\n        (ctx._re(z) >= 0):\\n        v = ctx._re(v)\\n    return v\\n\\ndef mcmahon(ctx,kind,prime,v,m):\\n    \\\"\\\"\\\"\\n    Computes an estimate for the location of the Bessel function zero\\n    j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic\\n    expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)).\\n\\n    Returns (r,err) where r is the estimated location of the root\\n    and err is a positive number estimating the error of the\\n    asymptotic expansion.\\n    \\\"\\\"\\\"\\n    u = 4*v**2\\n    if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4\\n    if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4\\n    if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4\\n    if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4\\n    if not prime:\\n        s1 = b\\n        s2 = -(u-1)/(8*b)\\n        s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3)\\n        s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5)\\n        s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7)\\n    if prime:\\n        s1 = b\\n        s2 = -(u+3)/(8*b)\\n        s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3)\\n        s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5)\\n        s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7)\\n    terms = [s1,s2,s3,s4,s5]\\n    s = s1\\n    err = 0.0\\n    for i in range(1,len(terms)):\\n        if abs(terms[i]) < abs(terms[i-1]):\\n            s += terms[i]\\n        else:\\n            err = abs(terms[i])\\n    if i == len(terms)-1:\\n        err = abs(terms[-1])\\n    return s, err\\n\\ndef generalized_bisection(ctx,f,a,b,n):\\n    \\\"\\\"\\\"\\n    Given f known to have exactly n simple roots within [a,b],\\n    return a list of n intervals isolating the roots\\n    and having opposite signs at the endpoints.\\n\\n    TODO: this can be optimized, e.g. by reusing evaluation points.\\n    \\\"\\\"\\\"\\n    if n < 1:\\n        raise ValueError(\\\"n cannot be less than 1\\\")\\n    N = n+1\\n    points = []\\n    signs = []\\n    while 1:\\n        points = ctx.linspace(a,b,N)\\n        signs = [ctx.sign(f(x)) for x in points]\\n        ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \\\\\\n            if signs[i]*signs[i+1] == -1]\\n        if len(ok_intervals) == n:\\n            return ok_intervals\\n        N = N*2\\n\\ndef find_in_interval(ctx, f, ab):\\n    return ctx.findroot(f, ab, solver='illinois', verify=False)\\n\\ndef bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}):\\n    prec = ctx.prec\\n    workprec = max(prec, ctx.mag(v), ctx.mag(m))+10\\n    try:\\n        ctx.prec = workprec\\n        v = ctx.mpf(v)\\n        m = int(m)\\n        prime = int(prime)\\n        if v < 0:\\n            raise ValueError(\\\"v cannot be negative\\\")\\n        if m < 1:\\n            raise ValueError(\\\"m cannot be less than 1\\\")\\n        if not prime in (0,1):\\n            raise ValueError(\\\"prime should lie between 0 and 1\\\")\\n        if kind == 1:\\n            if prime: f = lambda x: ctx.besselj(v,x,derivative=1)\\n            else:     f = lambda x: ctx.besselj(v,x)\\n        if kind == 2:\\n            if prime: f = lambda x: ctx.bessely(v,x,derivative=1)\\n            else:     f = lambda x: ctx.bessely(v,x)\\n        # The first root of J' is very close to 0 for small\\n        # orders, and this needs to be special-cased\\n        if kind == 1 and prime and m == 1:\\n            if v == 0:\\n                return ctx.zero\\n            if v <= 1:\\n                # TODO: use v <= j'_{v,1} < y_{v,1}?\\n                r = 2*ctx.sqrt(v*(1+v)/(v+2))\\n                return find_in_interval(ctx, f, (r/10, 2*r))\\n        if (kind,prime,v,m) in _interval_cache:\\n            return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m])\\n        r, err = mcmahon(ctx, kind, prime, v, m)\\n        if err < isoltol:\\n            return find_in_interval(ctx, f, (r-isoltol, r+isoltol))\\n        # An x such that 0 < x < r_{v,1}\\n        if kind == 1 and not prime: low = 2.4\\n        if kind == 1 and prime: low = 1.8\\n        if kind == 2 and not prime: low = 0.8\\n        if kind == 2 and prime: low = 2.0\\n        n = m+1\\n        while 1:\\n            r1, err = mcmahon(ctx, kind, prime, v, n)\\n            if err < isoltol:\\n                r2, err2 = mcmahon(ctx, kind, prime, v, n+1)\\n                intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n)\\n                for k, ab in enumerate(intervals):\\n                    _interval_cache[kind,prime,v,k+1] = ab\\n                return find_in_interval(ctx, f, intervals[m-1])\\n            else:\\n                n = n*2\\n    finally:\\n        ctx.prec = prec\\n\\n@defun\\ndef besseljzero(ctx, v, m, derivative=0):\\n    r\\\"\\\"\\\"\\n    For a real order `\\\\nu \\\\ge 0` and a positive integer `m`, returns\\n    `j_{\\\\nu,m}`, the `m`-th positive zero of the Bessel function of the\\n    first kind `J_{\\\\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively,\\n    with *derivative=1*, gives the first nonnegative simple zero\\n    `j'_{\\\\nu,m}` of `J'_{\\\\nu}(z)`.\\n\\n    The indexing convention is that used by Abramowitz & Stegun\\n    and the DLMF. Note the special case `j'_{0,1} = 0`, while all other\\n    zeros are positive. In effect, only simple zeros are counted\\n    (all zeros of Bessel functions are simple except possibly `z = 0`)\\n    and `j_{\\\\nu,m}` becomes a monotonic function of both `\\\\nu`\\n    and `m`.\\n\\n    The zeros are interlaced according to the inequalities\\n\\n    .. math ::\\n\\n        j'_{\\\\nu,k} < j_{\\\\nu,k} < j'_{\\\\nu,k+1}\\n\\n        j_{\\\\nu,1} < j_{\\\\nu+1,2} < j_{\\\\nu,2} < j_{\\\\nu+1,2} < j_{\\\\nu,3} < \\\\cdots\\n\\n    **Examples**\\n\\n    Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3)\\n        2.404825557695772768621632\\n        5.520078110286310649596604\\n        8.653727912911012216954199\\n        >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3)\\n        3.831705970207512315614436\\n        7.01558666981561875353705\\n        10.17346813506272207718571\\n        >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3)\\n        5.135622301840682556301402\\n        8.417244140399864857783614\\n        11.61984117214905942709415\\n\\n    Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`::\\n\\n        0.0\\n        3.831705970207512315614436\\n        7.01558666981561875353705\\n        >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1)\\n        1.84118378134065930264363\\n        5.331442773525032636884016\\n        8.536316366346285834358961\\n        >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1)\\n        3.054236928227140322755932\\n        6.706133194158459146634394\\n        9.969467823087595793179143\\n\\n    Zeros with large index::\\n\\n        >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000)\\n        313.3742660775278447196902\\n        3140.807295225078628895545\\n        31415.14114171350798533666\\n        >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000)\\n        321.1893195676003157339222\\n        3148.657306813047523500494\\n        31422.9947255486291798943\\n        >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1)\\n        311.8018681873704508125112\\n        3139.236339643802482833973\\n        31413.57032947022399485808\\n\\n    Zeros of functions with large order::\\n\\n        >>> besseljzero(50,1)\\n        57.11689916011917411936228\\n        >>> besseljzero(50,2)\\n        62.80769876483536093435393\\n        >>> besseljzero(50,100)\\n        388.6936600656058834640981\\n        >>> besseljzero(50,1,1)\\n        52.99764038731665010944037\\n        >>> besseljzero(50,2,1)\\n        60.02631933279942589882363\\n        >>> besseljzero(50,100,1)\\n        387.1083151608726181086283\\n\\n    Zeros of functions with fractional order::\\n\\n        >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4)\\n        3.141592653589793238462643\\n        4.493409457909064175307881\\n        15.15657692957458622921634\\n\\n    Both `J_{\\\\nu}(z)` and `J'_{\\\\nu}(z)` can be expressed as infinite\\n    products over their zeros::\\n\\n        >>> v,z = 2, mpf(1)\\n        >>> (z/2)**v/gamma(v+1) * \\\\\\n        ...     nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf])\\n        ...\\n        0.1149034849319004804696469\\n        >>> besselj(v,z)\\n        0.1149034849319004804696469\\n        >>> (z/2)**(v-1)/2/gamma(v) * \\\\\\n        ...     nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf])\\n        ...\\n        0.2102436158811325550203884\\n        >>> besselj(v,z,1)\\n        0.2102436158811325550203884\\n\\n    \\\"\\\"\\\"\\n    return +bessel_zero(ctx, 1, derivative, v, m)\\n\\n@defun\\ndef besselyzero(ctx, v, m, derivative=0):\\n    r\\\"\\\"\\\"\\n    For a real order `\\\\nu \\\\ge 0` and a positive integer `m`, returns\\n    `y_{\\\\nu,m}`, the `m`-th positive zero of the Bessel function of the\\n    second kind `Y_{\\\\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively,\\n    with *derivative=1*, gives the first positive zero `y'_{\\\\nu,m}` of\\n    `Y'_{\\\\nu}(z)`.\\n\\n    The zeros are interlaced according to the inequalities\\n\\n    .. math ::\\n\\n        y_{\\\\nu,k} < y'_{\\\\nu,k} < y_{\\\\nu,k+1}\\n\\n        y_{\\\\nu,1} < y_{\\\\nu+1,2} < y_{\\\\nu,2} < y_{\\\\nu+1,2} < y_{\\\\nu,3} < \\\\cdots\\n\\n    **Examples**\\n\\n    Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3)\\n        0.8935769662791675215848871\\n        3.957678419314857868375677\\n        7.086051060301772697623625\\n        >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3)\\n        2.197141326031017035149034\\n        5.429681040794135132772005\\n        8.596005868331168926429606\\n        >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3)\\n        3.384241767149593472701426\\n        6.793807513268267538291167\\n        10.02347797936003797850539\\n\\n    Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`::\\n\\n        >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1)\\n        2.197141326031017035149034\\n        5.429681040794135132772005\\n        8.596005868331168926429606\\n        >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1)\\n        3.683022856585177699898967\\n        6.941499953654175655751944\\n        10.12340465543661307978775\\n        >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1)\\n        5.002582931446063945200176\\n        8.350724701413079526349714\\n        11.57419546521764654624265\\n\\n    Zeros with large index::\\n\\n        >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000)\\n        311.8034717601871549333419\\n        3139.236498918198006794026\\n        31413.57034538691205229188\\n        >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000)\\n        319.6183338562782156235062\\n        3147.086508524556404473186\\n        31421.42392920214673402828\\n        >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1)\\n        313.3726705426359345050449\\n        3140.807136030340213610065\\n        31415.14112579761578220175\\n\\n    Zeros of functions with large order::\\n\\n        >>> besselyzero(50,1)\\n        53.50285882040036394680237\\n        >>> besselyzero(50,2)\\n        60.11244442774058114686022\\n        >>> besselyzero(50,100)\\n        387.1096509824943957706835\\n        >>> besselyzero(50,1,1)\\n        56.96290427516751320063605\\n        >>> besselyzero(50,2,1)\\n        62.74888166945933944036623\\n        >>> besselyzero(50,100,1)\\n        388.6923300548309258355475\\n\\n    Zeros of functions with fractional order::\\n\\n        >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4)\\n        1.570796326794896619231322\\n        2.798386045783887136720249\\n        13.56721208770735123376018\\n\\n    \\\"\\\"\\\"\\n    return +bessel_zero(ctx, 2, derivative, v, m)\\n\\n\\nfrom .functions import defun, defun_wrapped\\n\\ndef _hermite_param(ctx, n, z, parabolic_cylinder):\\n    \\\"\\\"\\\"\\n    Combined calculation of the Hermite polynomial H_n(z) (and its\\n    generalization to complex n) and the parabolic cylinder\\n    function D.\\n    \\\"\\\"\\\"\\n    n, ntyp = ctx._convert_param(n)\\n    z = ctx.convert(z)\\n    q = -ctx.mpq_1_2\\n    # For re(z) > 0, 2F0 -- http://functions.wolfram.com/\\n    #     HypergeometricFunctions/HermiteHGeneral/06/02/0009/\\n    # Otherwise, there is a reflection formula\\n    # 2F0 + http://functions.wolfram.com/HypergeometricFunctions/\\n    #           HermiteHGeneral/16/01/01/0006/\\n    #\\n    # TODO:\\n    # An alternative would be to use\\n    # http://functions.wolfram.com/HypergeometricFunctions/\\n    #     HermiteHGeneral/06/02/0006/\\n    #\\n    # Also, the 1F1 expansion\\n    # http://functions.wolfram.com/HypergeometricFunctions/\\n    #     HermiteHGeneral/26/01/02/0001/\\n    # should probably be used for tiny z\\n    if not z:\\n        T1 = [2, ctx.pi], [n, 0.5], [], [q*(n-1)], [], [], 0\\n        if parabolic_cylinder:\\n            T1[1][0] += q*n\\n        return T1,\\n    can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or \\\\\\n        (ctx.re(z) == 0 and ctx.im(z) > 0)\\n    expprec = ctx.prec*4 + 20\\n    if parabolic_cylinder:\\n        u = ctx.fmul(ctx.fmul(z,z,prec=expprec), -0.25, exact=True)\\n        w = ctx.fmul(z, ctx.sqrt(0.5,prec=expprec), prec=expprec)\\n    else:\\n        w = z\\n    w2 = ctx.fmul(w, w, prec=expprec)\\n    rw2 = ctx.fdiv(1, w2, prec=expprec)\\n    nrw2 = ctx.fneg(rw2, exact=True)\\n    nw = ctx.fneg(w, exact=True)\\n    if can_use_2f0:\\n        T1 = [2, w], [n, n], [], [], [q*n, q*(n-1)], [], nrw2\\n        terms = [T1]\\n    else:\\n        T1 = [2, nw], [n, n], [], [], [q*n, q*(n-1)], [], nrw2\\n        T2 = [2, ctx.pi, nw], [n+2, 0.5, 1], [], [q*n], [q*(n-1)], [1-q], w2\\n        terms = [T1,T2]\\n    # Multiply by prefactor for D_n\\n    if parabolic_cylinder:\\n        expu = ctx.exp(u)\\n        for i in range(len(terms)):\\n            terms[i][1][0] += q*n\\n            terms[i][0].append(expu)\\n            terms[i][1].append(1)\\n    return tuple(terms)\\n\\n@defun\\ndef hermite(ctx, n, z, **kwargs):\\n    return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 0), [], **kwargs)\\n\\n@defun\\ndef pcfd(ctx, n, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Gives the parabolic cylinder function in Whittaker's notation\\n    `D_n(z) = U(-n-1/2, z)` (see :func:`~mpmath.pcfu`).\\n    It solves the differential equation\\n\\n    .. math ::\\n\\n        y'' + \\\\left(n + \\\\frac{1}{2} - \\\\frac{1}{4} z^2\\\\right) y = 0.\\n\\n    and can be represented in terms of Hermite polynomials\\n    (see :func:`~mpmath.hermite`) as\\n\\n    .. math ::\\n\\n        D_n(z) = 2^{-n/2} e^{-z^2/4} H_n\\\\left(\\\\frac{z}{\\\\sqrt{2}}\\\\right).\\n\\n    **Plots**\\n\\n    .. literalinclude :: /plots/pcfd.py\\n    .. image :: /plots/pcfd.png\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> pcfd(0,0); pcfd(1,0); pcfd(2,0); pcfd(3,0)\\n        1.0\\n        0.0\\n        -1.0\\n        0.0\\n        >>> pcfd(4,0); pcfd(-3,0)\\n        3.0\\n        0.6266570686577501256039413\\n        >>> pcfd('1/2', 2+3j)\\n        (-5.363331161232920734849056 - 3.858877821790010714163487j)\\n        >>> pcfd(2, -10)\\n        1.374906442631438038871515e-9\\n\\n    Verifying the differential equation::\\n\\n        >>> n = mpf(2.5)\\n        >>> y = lambda z: pcfd(n,z)\\n        >>> z = 1.75\\n        >>> chop(diff(y,z,2) + (n+0.5-0.25*z**2)*y(z))\\n        0.0\\n\\n    Rational Taylor series expansion when `n` is an integer::\\n\\n        >>> taylor(lambda z: pcfd(5,z), 0, 7)\\n        [0.0, 15.0, 0.0, -13.75, 0.0, 3.96875, 0.0, -0.6015625]\\n\\n    \\\"\\\"\\\"\\n    return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 1), [], **kwargs)\\n\\n@defun\\ndef pcfu(ctx, a, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Gives the parabolic cylinder function `U(a,z)`, which may be\\n    defined for `\\\\Re(z) > 0` in terms of the confluent\\n    U-function (see :func:`~mpmath.hyperu`) by\\n\\n    .. math ::\\n\\n        U(a,z) = 2^{-\\\\frac{1}{4}-\\\\frac{a}{2}} e^{-\\\\frac{1}{4} z^2}\\n            U\\\\left(\\\\frac{a}{2}+\\\\frac{1}{4},\\n            \\\\frac{1}{2}, \\\\frac{1}{2}z^2\\\\right)\\n\\n    or, for arbitrary `z`,\\n\\n    .. math ::\\n\\n        e^{-\\\\frac{1}{4}z^2} U(a,z) =\\n            U(a,0) \\\\,_1F_1\\\\left(-\\\\tfrac{a}{2}+\\\\tfrac{1}{4};\\n            \\\\tfrac{1}{2}; -\\\\tfrac{1}{2}z^2\\\\right) +\\n            U'(a,0) z \\\\,_1F_1\\\\left(-\\\\tfrac{a}{2}+\\\\tfrac{3}{4};\\n            \\\\tfrac{3}{2}; -\\\\tfrac{1}{2}z^2\\\\right).\\n\\n    **Examples**\\n\\n    Connection to other functions::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> z = mpf(3)\\n        >>> pcfu(0.5,z)\\n        0.03210358129311151450551963\\n        >>> sqrt(pi/2)*exp(z**2/4)*erfc(z/sqrt(2))\\n        0.03210358129311151450551963\\n        >>> pcfu(0.5,-z)\\n        23.75012332835297233711255\\n        >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2))\\n        23.75012332835297233711255\\n        >>> pcfu(0.5,-z)\\n        23.75012332835297233711255\\n        >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2))\\n        23.75012332835297233711255\\n\\n    \\\"\\\"\\\"\\n    n, _ = ctx._convert_param(a)\\n    return ctx.pcfd(-n-ctx.mpq_1_2, z)\\n\\n@defun\\ndef pcfv(ctx, a, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Gives the parabolic cylinder function `V(a,z)`, which can be\\n    represented in terms of :func:`~mpmath.pcfu` as\\n\\n    .. math ::\\n\\n        V(a,z) = \\\\frac{\\\\Gamma(a+\\\\tfrac{1}{2}) (U(a,-z)-\\\\sin(\\\\pi a) U(a,z)}{\\\\pi}.\\n\\n    **Examples**\\n\\n    Wronskian relation between `U` and `V`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> a, z = 2, 3\\n        >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)\\n        0.7978845608028653558798921\\n        >>> sqrt(2/pi)\\n        0.7978845608028653558798921\\n        >>> a, z = 2.5, 3\\n        >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)\\n        0.7978845608028653558798921\\n        >>> a, z = 0.25, -1\\n        >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)\\n        0.7978845608028653558798921\\n        >>> a, z = 2+1j, 2+3j\\n        >>> chop(pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z))\\n        0.7978845608028653558798921\\n\\n    \\\"\\\"\\\"\\n    n, ntype = ctx._convert_param(a)\\n    z = ctx.convert(z)\\n    q = ctx.mpq_1_2\\n    r = ctx.mpq_1_4\\n    if ntype == 'Q' and ctx.isint(n*2):\\n        # Faster for half-integers\\n        def h():\\n            jz = ctx.fmul(z, -1j, exact=True)\\n            T1terms = _hermite_param(ctx, -n-q, z, 1)\\n            T2terms = _hermite_param(ctx, n-q, jz, 1)\\n            for T in T1terms:\\n                T[0].append(1j)\\n                T[1].append(1)\\n                T[3].append(q-n)\\n            u = ctx.expjpi((q*n-r)) * ctx.sqrt(2/ctx.pi)\\n            for T in T2terms:\\n                T[0].append(u)\\n                T[1].append(1)\\n            return T1terms + T2terms\\n        v = ctx.hypercomb(h, [], **kwargs)\\n        if ctx._is_real_type(n) and ctx._is_real_type(z):\\n            v = ctx._re(v)\\n        return v\\n    else:\\n        def h(n):\\n            w = ctx.square_exp_arg(z, -0.25)\\n            u = ctx.square_exp_arg(z, 0.5)\\n            e = ctx.exp(w)\\n            l = [ctx.pi, q, ctx.exp(w)]\\n            Y1 = l, [-q, n*q+r, 1], [r-q*n], [], [q*n+r], [q], u\\n            Y2 = l + [z], [-q, n*q-r, 1, 1], [1-r-q*n], [], [q*n+1-r], [1+q], u\\n            c, s = ctx.cospi_sinpi(r+q*n)\\n            Y1[0].append(s)\\n            Y2[0].append(c)\\n            for Y in (Y1, Y2):\\n                Y[1].append(1)\\n                Y[3].append(q-n)\\n            return Y1, Y2\\n        return ctx.hypercomb(h, [n], **kwargs)\\n\\n\\n@defun\\ndef pcfw(ctx, a, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Gives the parabolic cylinder function `W(a,z)` defined in (DLMF 12.14).\\n\\n    **Examples**\\n\\n    Value at the origin::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> a = mpf(0.25)\\n        >>> pcfw(a,0)\\n        0.9722833245718180765617104\\n        >>> power(2,-0.75)*sqrt(abs(gamma(0.25+0.5j*a)/gamma(0.75+0.5j*a)))\\n        0.9722833245718180765617104\\n        >>> diff(pcfw,(a,0),(0,1))\\n        -0.5142533944210078966003624\\n        >>> -power(2,-0.25)*sqrt(abs(gamma(0.75+0.5j*a)/gamma(0.25+0.5j*a)))\\n        -0.5142533944210078966003624\\n\\n    \\\"\\\"\\\"\\n    n, _ = ctx._convert_param(a)\\n    z = ctx.convert(z)\\n    def terms():\\n        phi2 = ctx.arg(ctx.gamma(0.5 + ctx.j*n))\\n        phi2 = (ctx.loggamma(0.5+ctx.j*n) - ctx.loggamma(0.5-ctx.j*n))/2j\\n        rho = ctx.pi/8 + 0.5*phi2\\n        # XXX: cancellation computing k\\n        k = ctx.sqrt(1 + ctx.exp(2*ctx.pi*n)) - ctx.exp(ctx.pi*n)\\n        C = ctx.sqrt(k/2) * ctx.exp(0.25*ctx.pi*n)\\n        yield C * ctx.expj(rho) * ctx.pcfu(ctx.j*n, z*ctx.expjpi(-0.25))\\n        yield C * ctx.expj(-rho) * ctx.pcfu(-ctx.j*n, z*ctx.expjpi(0.25))\\n    v = ctx.sum_accurately(terms)\\n    if ctx._is_real_type(n) and ctx._is_real_type(z):\\n        v = ctx._re(v)\\n    return v\\n\\n\\\"\\\"\\\"\\nEven/odd PCFs. Useful?\\n\\n@defun\\ndef pcfy1(ctx, a, z, **kwargs):\\n    a, _ = ctx._convert_param(n)\\n    z = ctx.convert(z)\\n    def h():\\n        w = ctx.square_exp_arg(z)\\n        w1 = ctx.fmul(w, -0.25, exact=True)\\n        w2 = ctx.fmul(w, 0.5, exact=True)\\n        e = ctx.exp(w1)\\n        return [e], [1], [], [], [ctx.mpq_1_2*a+ctx.mpq_1_4], [ctx.mpq_1_2], w2\\n    return ctx.hypercomb(h, [], **kwargs)\\n\\n@defun\\ndef pcfy2(ctx, a, z, **kwargs):\\n    a, _ = ctx._convert_param(n)\\n    z = ctx.convert(z)\\n    def h():\\n        w = ctx.square_exp_arg(z)\\n        w1 = ctx.fmul(w, -0.25, exact=True)\\n        w2 = ctx.fmul(w, 0.5, exact=True)\\n        e = ctx.exp(w1)\\n        return [e, z], [1, 1], [], [], [ctx.mpq_1_2*a+ctx.mpq_3_4], \\\\\\n            [ctx.mpq_3_2], w2\\n    return ctx.hypercomb(h, [], **kwargs)\\n\\\"\\\"\\\"\\n\\n@defun_wrapped\\ndef gegenbauer(ctx, n, a, z, **kwargs):\\n    # Special cases: a+0.5, a*2 poles\\n    if ctx.isnpint(a):\\n        return 0*(z+n)\\n    if ctx.isnpint(a+0.5):\\n        # TODO: something else is required here\\n        # E.g.: gegenbauer(-2, -0.5, 3) == -12\\n        if ctx.isnpint(n+1):\\n            raise NotImplementedError(\\\"Gegenbauer function with two limits\\\")\\n        def h(a):\\n            a2 = 2*a\\n            T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z)\\n            return [T]\\n        return ctx.hypercomb(h, [a], **kwargs)\\n    def h(n):\\n        a2 = 2*a\\n        T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z)\\n        return [T]\\n    return ctx.hypercomb(h, [n], **kwargs)\\n\\n@defun_wrapped\\ndef jacobi(ctx, n, a, b, x, **kwargs):\\n    if not ctx.isnpint(a):\\n        def h(n):\\n            return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),)\\n        return ctx.hypercomb(h, [n], **kwargs)\\n    if not ctx.isint(b):\\n        def h(n, a):\\n            return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),)\\n        return ctx.hypercomb(h, [n, a], **kwargs)\\n    # XXX: determine appropriate limit\\n    return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs)\\n\\n@defun_wrapped\\ndef laguerre(ctx, n, a, z, **kwargs):\\n    # XXX: limits, poles\\n    #if ctx.isnpint(n):\\n    #    return 0*(a+z)\\n    def h(a):\\n        return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),)\\n    return ctx.hypercomb(h, [a], **kwargs)\\n\\n@defun_wrapped\\ndef legendre(ctx, n, x, **kwargs):\\n    if ctx.isint(n):\\n        n = int(n)\\n        # Accuracy near zeros\\n        if (n + (n < 0)) & 1:\\n            if not x:\\n                return x\\n            mag = ctx.mag(x)\\n            if mag < -2*ctx.prec-10:\\n                return x\\n            if mag < -5:\\n                ctx.prec += -mag\\n    return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs)\\n\\n@defun\\ndef legenp(ctx, n, m, z, type=2, **kwargs):\\n    # Legendre function, 1st kind\\n    n = ctx.convert(n)\\n    m = ctx.convert(m)\\n    # Faster\\n    if not m:\\n        return ctx.legendre(n, z, **kwargs)\\n    # TODO: correct evaluation at singularities\\n    if type == 2:\\n        def h(n,m):\\n            g = m*0.5\\n            T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z)\\n            return (T,)\\n        return ctx.hypercomb(h, [n,m], **kwargs)\\n    if type == 3:\\n        def h(n,m):\\n            g = m*0.5\\n            T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z)\\n            return (T,)\\n        return ctx.hypercomb(h, [n,m], **kwargs)\\n    raise ValueError(\\\"requires type=2 or type=3\\\")\\n\\n@defun\\ndef legenq(ctx, n, m, z, type=2, **kwargs):\\n    # Legendre function, 2nd kind\\n    n = ctx.convert(n)\\n    m = ctx.convert(m)\\n    z = ctx.convert(z)\\n    if z in (1, -1):\\n        #if ctx.isint(m):\\n        #    return ctx.nan\\n        #return ctx.inf  # unsigned\\n        return ctx.nan\\n    if type == 2:\\n        def h(n, m):\\n            cos, sin = ctx.cospi_sinpi(m)\\n            s = 2 * sin / ctx.pi\\n            c = cos\\n            a = 1+z\\n            b = 1-z\\n            u = m/2\\n            w = (1-z)/2\\n            T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \\\\\\n                [-n, n+1], [1-m], w\\n            T2 = [-s, a, b], [-1, -u, u], [n+m+1], [n-m+1, m+1], \\\\\\n                [-n, n+1], [m+1], w\\n            return T1, T2\\n        return ctx.hypercomb(h, [n, m], **kwargs)\\n    if type == 3:\\n        # The following is faster when there only is a single series\\n        # Note: not valid for -1 < z < 0 (?)\\n        if abs(z) > 1:\\n            def h(n, m):\\n                T1 = [ctx.expjpi(m), 2, ctx.pi, z, z-1, z+1], \\\\\\n                     [1, -n-1, 0.5, -n-m-1, 0.5*m, 0.5*m], \\\\\\n                     [n+m+1], [n+1.5], \\\\\\n                     [0.5*(2+n+m), 0.5*(1+n+m)], [n+1.5], z**(-2)\\n                return [T1]\\n            return ctx.hypercomb(h, [n, m], **kwargs)\\n        else:\\n            # not valid for 1 < z < inf ?\\n            def h(n, m):\\n                s = 2 * ctx.sinpi(m) / ctx.pi\\n                c = ctx.expjpi(m)\\n                a = 1+z\\n                b = z-1\\n                u = m/2\\n                w = (1-z)/2\\n                T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \\\\\\n                    [-n, n+1], [1-m], w\\n                T2 = [-s, c, a, b], [-1, 1, -u, u], [n+m+1], [n-m+1, m+1], \\\\\\n                    [-n, n+1], [m+1], w\\n                return T1, T2\\n            return ctx.hypercomb(h, [n, m], **kwargs)\\n    raise ValueError(\\\"requires type=2 or type=3\\\")\\n\\n@defun_wrapped\\ndef chebyt(ctx, n, x, **kwargs):\\n    if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1:\\n        return x * 0\\n    return ctx.hyp2f1(-n,n,(1,2),(1-x)/2, **kwargs)\\n\\n@defun_wrapped\\ndef chebyu(ctx, n, x, **kwargs):\\n    if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1:\\n        return x * 0\\n    return (n+1) * ctx.hyp2f1(-n, n+2, (3,2), (1-x)/2, **kwargs)\\n\\n@defun\\ndef spherharm(ctx, l, m, theta, phi, **kwargs):\\n    l = ctx.convert(l)\\n    m = ctx.convert(m)\\n    theta = ctx.convert(theta)\\n    phi = ctx.convert(phi)\\n    l_isint = ctx.isint(l)\\n    l_natural = l_isint and l >= 0\\n    m_isint = ctx.isint(m)\\n    if l_isint and l < 0 and m_isint:\\n        return ctx.spherharm(-(l+1), m, theta, phi, **kwargs)\\n    if theta == 0 and m_isint and m < 0:\\n        return ctx.zero * 1j\\n    if l_natural and m_isint:\\n        if abs(m) > l:\\n            return ctx.zero * 1j\\n        # http://functions.wolfram.com/Polynomials/\\n        #     SphericalHarmonicY/26/01/02/0004/\\n        def h(l,m):\\n            absm = abs(m)\\n            C = [-1, ctx.expj(m*phi),\\n                 (2*l+1)*ctx.fac(l+absm)/ctx.pi/ctx.fac(l-absm),\\n                 ctx.sin(theta)**2,\\n                 ctx.fac(absm), 2]\\n            P = [0.5*m*(ctx.sign(m)+1), 1, 0.5, 0.5*absm, -1, -absm-1]\\n            return ((C, P, [], [], [absm-l, l+absm+1], [absm+1],\\n                ctx.sin(0.5*theta)**2),)\\n    else:\\n        # http://functions.wolfram.com/HypergeometricFunctions/\\n        #     SphericalHarmonicYGeneral/26/01/02/0001/\\n        def h(l,m):\\n            if ctx.isnpint(l-m+1) or ctx.isnpint(l+m+1) or ctx.isnpint(1-m):\\n                return (([0], [-1], [], [], [], [], 0),)\\n            cos, sin = ctx.cos_sin(0.5*theta)\\n            C = [0.5*ctx.expj(m*phi), (2*l+1)/ctx.pi,\\n                 ctx.gamma(l-m+1), ctx.gamma(l+m+1),\\n                 cos**2, sin**2]\\n            P = [1, 0.5, 0.5, -0.5, 0.5*m, -0.5*m]\\n            return ((C, P, [], [1-m], [-l,l+1], [1-m], sin**2),)\\n    return ctx.hypercomb(h, [l,m], **kwargs)\\n\\n\\nfrom .functions import defun, defun_wrapped\\n\\n@defun\\ndef qp(ctx, a, q=None, n=None, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the q-Pochhammer symbol (or q-rising factorial)\\n\\n    .. math ::\\n\\n        (a; q)_n = \\\\prod_{k=0}^{n-1} (1-a q^k)\\n\\n    where `n = \\\\infty` is permitted if `|q| < 1`. Called with two arguments,\\n    ``qp(a,q)`` computes `(a;q)_{\\\\infty}`; with a single argument, ``qp(q)``\\n    computes `(q;q)_{\\\\infty}`. The special case\\n\\n    .. math ::\\n\\n        \\\\phi(q) = (q; q)_{\\\\infty} = \\\\prod_{k=1}^{\\\\infty} (1-q^k) =\\n            \\\\sum_{k=-\\\\infty}^{\\\\infty} (-1)^k q^{(3k^2-k)/2}\\n\\n    is also known as the Euler function, or (up to a factor `q^{-1/24}`)\\n    the Dedekind eta function.\\n\\n    **Examples**\\n\\n    If `n` is a positive integer, the function amounts to a finite product::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qp(2,3,5)\\n        -725305.0\\n        >>> fprod(1-2*3**k for k in range(5))\\n        -725305.0\\n        >>> qp(2,3,0)\\n        1.0\\n\\n    Complex arguments are allowed::\\n\\n        >>> qp(2-1j, 0.75j)\\n        (0.4628842231660149089976379 + 4.481821753552703090628793j)\\n\\n    The regular Pochhammer symbol `(a)_n` is obtained in the\\n    following limit as `q \\\\to 1`::\\n\\n        >>> a, n = 4, 7\\n        >>> limit(lambda q: qp(q**a,q,n) / (1-q)**n, 1)\\n        604800.0\\n        >>> rf(a,n)\\n        604800.0\\n\\n    The Taylor series of the reciprocal Euler function gives\\n    the partition function `P(n)`, i.e. the number of ways of writing\\n    `n` as a sum of positive integers::\\n\\n        >>> taylor(lambda q: 1/qp(q), 0, 10)\\n        [1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 11.0, 15.0, 22.0, 30.0, 42.0]\\n\\n    Special values include::\\n\\n        >>> qp(0)\\n        1.0\\n        >>> findroot(diffun(qp), -0.4)   # location of maximum\\n        -0.4112484791779547734440257\\n        >>> qp(_)\\n        1.228348867038575112586878\\n\\n    The q-Pochhammer symbol is related to the Jacobi theta functions.\\n    For example, the following identity holds::\\n\\n        >>> q = mpf(0.5)    # arbitrary\\n        >>> qp(q)\\n        0.2887880950866024212788997\\n        >>> root(3,-2)*root(q,-24)*jtheta(2,pi/6,root(q,6))\\n        0.2887880950866024212788997\\n\\n    \\\"\\\"\\\"\\n    a = ctx.convert(a)\\n    if n is None:\\n        n = ctx.inf\\n    else:\\n        n = ctx.convert(n)\\n    if n < 0:\\n        raise ValueError(\\\"n cannot be negative\\\")\\n    if q is None:\\n        q = a\\n    else:\\n        q = ctx.convert(q)\\n    if n == 0:\\n        return ctx.one + 0*(a+q)\\n    infinite = (n == ctx.inf)\\n    same = (a == q)\\n    if infinite:\\n        if abs(q) >= 1:\\n            if same and (q == -1 or q == 1):\\n                return ctx.zero * q\\n            raise ValueError(\\\"q-function only defined for |q| < 1\\\")\\n        elif q == 0:\\n            return ctx.one - a\\n    maxterms = kwargs.get('maxterms', 50*ctx.prec)\\n    if infinite and same:\\n        # Euler's pentagonal theorem\\n        def terms():\\n            t = 1\\n            yield t\\n            k = 1\\n            x1 = q\\n            x2 = q**2\\n            while 1:\\n                yield (-1)**k * x1\\n                yield (-1)**k * x2\\n                x1 *= q**(3*k+1)\\n                x2 *= q**(3*k+2)\\n                k += 1\\n                if k > maxterms:\\n                    raise ctx.NoConvergence\\n        return ctx.sum_accurately(terms)\\n    # return ctx.nprod(lambda k: 1-a*q**k, [0,n-1])\\n    def factors():\\n        k = 0\\n        r = ctx.one\\n        while 1:\\n            yield 1 - a*r\\n            r *= q\\n            k += 1\\n            if k >= n:\\n                return\\n            if k > maxterms:\\n                raise ctx.NoConvergence\\n    return ctx.mul_accurately(factors)\\n\\n@defun_wrapped\\ndef qgamma(ctx, z, q, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the q-gamma function\\n\\n    .. math ::\\n\\n        \\\\Gamma_q(z) = \\\\frac{(q; q)_{\\\\infty}}{(q^z; q)_{\\\\infty}} (1-q)^{1-z}.\\n\\n\\n    **Examples**\\n\\n    Evaluation for real and complex arguments::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qgamma(4,0.75)\\n        4.046875\\n        >>> qgamma(6,6)\\n        121226245.0\\n        >>> qgamma(3+4j, 0.5j)\\n        (0.1663082382255199834630088 + 0.01952474576025952984418217j)\\n\\n    The q-gamma function satisfies a functional equation similar\\n    to that of the ordinary gamma function::\\n\\n        >>> q = mpf(0.25)\\n        >>> z = mpf(2.5)\\n        >>> qgamma(z+1,q)\\n        1.428277424823760954685912\\n        >>> (1-q**z)/(1-q)*qgamma(z,q)\\n        1.428277424823760954685912\\n\\n    \\\"\\\"\\\"\\n    if abs(q) > 1:\\n        return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5)\\n    return ctx.qp(q, q, None, **kwargs) / \\\\\\n        ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z)\\n\\n@defun_wrapped\\ndef qfac(ctx, z, q, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the q-factorial,\\n\\n    .. math ::\\n\\n        [n]_q! = (1+q)(1+q+q^2)\\\\cdots(1+q+\\\\cdots+q^{n-1})\\n\\n    or more generally\\n\\n    .. math ::\\n\\n        [z]_q! = \\\\frac{(q;q)_z}{(1-q)^z}.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qfac(0,0)\\n        1.0\\n        >>> qfac(4,3)\\n        2080.0\\n        >>> qfac(5,6)\\n        121226245.0\\n        >>> qfac(1+1j, 2+1j)\\n        (0.4370556551322672478613695 + 0.2609739839216039203708921j)\\n\\n    \\\"\\\"\\\"\\n    if ctx.isint(z) and ctx._re(z) > 0:\\n        n = int(ctx._re(z))\\n        return ctx.qp(q, q, n, **kwargs) / (1-q)**n\\n    return ctx.qgamma(z+1, q, **kwargs)\\n\\n@defun\\ndef qhyper(ctx, a_s, b_s, q, z, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the basic hypergeometric series or hypergeometric q-series\\n\\n    .. math ::\\n\\n        \\\\,_r\\\\phi_s \\\\left[\\\\begin{matrix}\\n            a_1 & a_2 & \\\\ldots & a_r \\\\\\\\\\n            b_1 & b_2 & \\\\ldots & b_s\\n        \\\\end{matrix} ; q,z \\\\right] =\\n        \\\\sum_{n=0}^\\\\infty\\n        \\\\frac{(a_1;q)_n, \\\\ldots, (a_r;q)_n}\\n             {(b_1;q)_n, \\\\ldots, (b_s;q)_n}\\n        \\\\left((-1)^n q^{n\\\\choose 2}\\\\right)^{1+s-r}\\n        \\\\frac{z^n}{(q;q)_n}\\n\\n    where `(a;q)_n` denotes the q-Pochhammer symbol (see :func:`~mpmath.qp`).\\n\\n    **Examples**\\n\\n    Evaluation works for real and complex arguments::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qhyper([0.5], [2.25], 0.25, 4)\\n        -0.1975849091263356009534385\\n        >>> qhyper([0.5], [2.25], 0.25-0.25j, 4)\\n        (2.806330244925716649839237 + 3.568997623337943121769938j)\\n        >>> qhyper([1+j], [2,3+0.5j], 0.25, 3+4j)\\n        (9.112885171773400017270226 - 1.272756997166375050700388j)\\n\\n    Comparing with a summation of the defining series, using\\n    :func:`~mpmath.nsum`::\\n\\n        >>> b, q, z = 3, 0.25, 0.5\\n        >>> qhyper([], [b], q, z)\\n        0.6221136748254495583228324\\n        >>> nsum(lambda n: z**n / qp(q,q,n)/qp(b,q,n) * q**(n*(n-1)), [0,inf])\\n        0.6221136748254495583228324\\n\\n    \\\"\\\"\\\"\\n    #a_s = [ctx._convert_param(a)[0] for a in a_s]\\n    #b_s = [ctx._convert_param(b)[0] for b in b_s]\\n    #q = ctx._convert_param(q)[0]\\n    a_s = [ctx.convert(a) for a in a_s]\\n    b_s = [ctx.convert(b) for b in b_s]\\n    q = ctx.convert(q)\\n    z = ctx.convert(z)\\n    r = len(a_s)\\n    s = len(b_s)\\n    d = 1+s-r\\n    maxterms = kwargs.get('maxterms', 50*ctx.prec)\\n    def terms():\\n        t = ctx.one\\n        yield t\\n        qk = 1\\n        k = 0\\n        x = 1\\n        while 1:\\n            for a in a_s:\\n                p = 1 - a*qk\\n                t *= p\\n            for b in b_s:\\n                p = 1 - b*qk\\n                if not p:\\n                    raise ValueError\\n                t /= p\\n            t *= z\\n            x *= (-1)**d * qk ** d\\n            qk *= q\\n            t /= (1 - qk)\\n            k += 1\\n            yield t * x\\n            if k > maxterms:\\n                raise ctx.NoConvergence\\n    return ctx.sum_accurately(terms)\\n\\n\\nfrom .functions import defun, defun_wrapped\\n\\n@defun\\ndef _jacobi_theta2(ctx, z, q):\\n    extra1 = 10\\n    extra2 = 20\\n    # the loops below break when the fixed precision quantities\\n    # a and b go to zero;\\n    # right shifting small negative numbers by wp one obtains -1, not zero,\\n    # so the condition a**2 + b**2 > MIN is used to break the loops.\\n    MIN = 2\\n    if z == ctx.zero:\\n        if (not ctx._im(q)):\\n            wp = ctx.prec + extra1\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            x2 = (x*x) >> wp\\n            a = b = x2\\n            s = x2\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                s += a\\n            s = (1 << (wp+1)) + (s << 1)\\n            s = ctx.ldexp(s, -wp)\\n        else:\\n            wp = ctx.prec + extra1\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp-1)\\n            are = bre = x2re\\n            aim = bim = x2im\\n            sre = (1<<wp) + are\\n            sim = aim\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                sre += are\\n                sim += aim\\n            sre = (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n    else:\\n        if (not ctx._im(q)) and (not ctx._im(z)):\\n            wp = ctx.prec + extra1\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            x2 = (x*x) >> wp\\n            a = b = x2\\n            c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp)\\n            cn = c1 = ctx.to_fixed(c1, wp)\\n            sn = s1 = ctx.to_fixed(s1, wp)\\n            c2 = (c1*c1 - s1*s1) >> wp\\n            s2 = (c1 * s1) >> (wp - 1)\\n            cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n            s = c1 + ((a * cn) >> wp)\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n                s += (a * cn) >> wp\\n            s = (s << 1)\\n            s = ctx.ldexp(s, -wp)\\n            s *= ctx.nthroot(q, 4)\\n            return s\\n        # case z real, q complex\\n        elif not ctx._im(z):\\n            wp = ctx.prec + extra2\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp - 1)\\n            are = bre = x2re\\n            aim = bim = x2im\\n            c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp)\\n            cn = c1 = ctx.to_fixed(c1, wp)\\n            sn = s1 = ctx.to_fixed(s1, wp)\\n            c2 = (c1*c1 - s1*s1) >> wp\\n            s2 = (c1 * s1) >> (wp - 1)\\n            cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n            sre = c1 + ((are * cn) >> wp)\\n            sim = ((aim * cn) >> wp)\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n                sre += ((are * cn) >> wp)\\n                sim += ((aim * cn) >> wp)\\n            sre = (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n        #case z complex, q real\\n        elif not ctx._im(q):\\n            wp = ctx.prec + extra2\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            x2 = (x*x) >> wp\\n            a = b = x2\\n            prec0 = ctx.prec\\n            ctx.prec = wp\\n            c1, s1 = ctx.cos_sin(z)\\n            ctx.prec = prec0\\n            cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n            cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n            snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n            snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n            #c2 = (c1*c1 - s1*s1) >> wp\\n            c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp\\n            c2im = (c1re*c1im - s1re*s1im) >> (wp - 1)\\n            #s2 = (c1 * s1) >> (wp - 1)\\n            s2re = (c1re*s1re - c1im*s1im) >> (wp - 1)\\n            s2im = (c1re*s1im + c1im*s1re) >> (wp - 1)\\n            #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n            t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n            t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n            t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n            t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            sre = c1re + ((a * cnre) >> wp)\\n            sim = c1im + ((a * cnim) >> wp)\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n                t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n                t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n                t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n                cnre = t1\\n                cnim = t2\\n                snre = t3\\n                snim = t4\\n                sre += ((a * cnre) >> wp)\\n                sim += ((a * cnim) >> wp)\\n            sre = (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n        # case z and q complex\\n        else:\\n            wp = ctx.prec + extra2\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp - 1)\\n            are = bre = x2re\\n            aim = bim = x2im\\n            prec0 = ctx.prec\\n            ctx.prec = wp\\n            # cos(z), sin(z) with z complex\\n            c1, s1 = ctx.cos_sin(z)\\n            ctx.prec = prec0\\n            cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n            cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n            snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n            snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n            c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp\\n            c2im = (c1re*c1im - s1re*s1im) >> (wp - 1)\\n            s2re = (c1re*s1re - c1im*s1im) >> (wp - 1)\\n            s2im = (c1re*s1im + c1im*s1re) >> (wp - 1)\\n            t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n            t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n            t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n            t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            n = 1\\n            termre = c1re\\n            termim = c1im\\n            sre = c1re + ((are * cnre - aim * cnim) >> wp)\\n            sim = c1im + ((are * cnim + aim * cnre) >> wp)\\n            n = 3\\n            termre = ((are * cnre - aim * cnim) >> wp)\\n            termim = ((are * cnim + aim * cnre) >> wp)\\n            sre = c1re + ((are * cnre - aim * cnim) >> wp)\\n            sim = c1im + ((are * cnim + aim * cnre) >> wp)\\n            n = 5\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n                t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n                t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n                t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n                t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n                cnre = t1\\n                cnim = t2\\n                snre = t3\\n                snim = t4\\n                termre = ((are * cnre - aim * cnim) >> wp)\\n                termim = ((aim * cnre + are * cnim) >> wp)\\n                sre += ((are * cnre - aim * cnim) >> wp)\\n                sim += ((aim * cnre + are * cnim) >> wp)\\n                n += 2\\n            sre = (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n    s *= ctx.nthroot(q, 4)\\n    return s\\n\\n@defun\\ndef _djacobi_theta2(ctx, z, q, nd):\\n    MIN = 2\\n    extra1 = 10\\n    extra2 = 20\\n    if (not ctx._im(q)) and (not ctx._im(z)):\\n        wp = ctx.prec + extra1\\n        x = ctx.to_fixed(ctx._re(q), wp)\\n        x2 = (x*x) >> wp\\n        a = b = x2\\n        c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp)\\n        cn = c1 = ctx.to_fixed(c1, wp)\\n        sn = s1 = ctx.to_fixed(s1, wp)\\n        c2 = (c1*c1 - s1*s1) >> wp\\n        s2 = (c1 * s1) >> (wp - 1)\\n        cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n        if (nd&1):\\n            s = s1 + ((a * sn * 3**nd) >> wp)\\n        else:\\n            s = c1 + ((a * cn * 3**nd) >> wp)\\n        n = 2\\n        while abs(a) > MIN:\\n            b = (b*x2) >> wp\\n            a = (a*b) >> wp\\n            cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n            if nd&1:\\n                s += (a * sn * (2*n+1)**nd) >> wp\\n            else:\\n                s += (a * cn * (2*n+1)**nd) >> wp\\n            n += 1\\n        s = -(s << 1)\\n        s = ctx.ldexp(s, -wp)\\n        # case z real, q complex\\n    elif not ctx._im(z):\\n        wp = ctx.prec + extra2\\n        xre = ctx.to_fixed(ctx._re(q), wp)\\n        xim = ctx.to_fixed(ctx._im(q), wp)\\n        x2re = (xre*xre - xim*xim) >> wp\\n        x2im = (xre*xim) >> (wp - 1)\\n        are = bre = x2re\\n        aim = bim = x2im\\n        c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp)\\n        cn = c1 = ctx.to_fixed(c1, wp)\\n        sn = s1 = ctx.to_fixed(s1, wp)\\n        c2 = (c1*c1 - s1*s1) >> wp\\n        s2 = (c1 * s1) >> (wp - 1)\\n        cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n        if (nd&1):\\n            sre = s1 + ((are * sn * 3**nd) >> wp)\\n            sim = ((aim * sn * 3**nd) >> wp)\\n        else:\\n            sre = c1 + ((are * cn * 3**nd) >> wp)\\n            sim = ((aim * cn * 3**nd) >> wp)\\n        n = 5\\n        while are**2 + aim**2 > MIN:\\n            bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                       (bre * x2im + bim * x2re) >> wp\\n            are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                       (are * bim + aim * bre) >> wp\\n            cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n\\n            if (nd&1):\\n                sre += ((are * sn * n**nd) >> wp)\\n                sim += ((aim * sn * n**nd) >> wp)\\n            else:\\n                sre += ((are * cn * n**nd) >> wp)\\n                sim += ((aim * cn * n**nd) >> wp)\\n            n += 2\\n        sre = -(sre << 1)\\n        sim = -(sim << 1)\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    #case z complex, q real\\n    elif not ctx._im(q):\\n        wp = ctx.prec + extra2\\n        x = ctx.to_fixed(ctx._re(q), wp)\\n        x2 = (x*x) >> wp\\n        a = b = x2\\n        prec0 = ctx.prec\\n        ctx.prec = wp\\n        c1, s1 = ctx.cos_sin(z)\\n        ctx.prec = prec0\\n        cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n        cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n        snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n        snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n        #c2 = (c1*c1 - s1*s1) >> wp\\n        c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp\\n        c2im = (c1re*c1im - s1re*s1im) >> (wp - 1)\\n        #s2 = (c1 * s1) >> (wp - 1)\\n        s2re = (c1re*s1re - c1im*s1im) >> (wp - 1)\\n        s2im = (c1re*s1im + c1im*s1re) >> (wp - 1)\\n        #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp\\n        t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n        t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n        t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n        t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n        cnre = t1\\n        cnim = t2\\n        snre = t3\\n        snim = t4\\n        if (nd&1):\\n            sre = s1re + ((a * snre * 3**nd) >> wp)\\n            sim = s1im + ((a * snim * 3**nd) >> wp)\\n        else:\\n            sre = c1re + ((a * cnre * 3**nd) >> wp)\\n            sim = c1im + ((a * cnim * 3**nd) >> wp)\\n        n = 5\\n        while abs(a) > MIN:\\n            b = (b*x2) >> wp\\n            a = (a*b) >> wp\\n            t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n            t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n            t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n            t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            if (nd&1):\\n                sre += ((a * snre * n**nd) >> wp)\\n                sim += ((a * snim * n**nd) >> wp)\\n            else:\\n                sre += ((a * cnre * n**nd) >> wp)\\n                sim += ((a * cnim * n**nd) >> wp)\\n            n += 2\\n        sre = -(sre << 1)\\n        sim = -(sim << 1)\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    # case z and q complex\\n    else:\\n        wp = ctx.prec + extra2\\n        xre = ctx.to_fixed(ctx._re(q), wp)\\n        xim = ctx.to_fixed(ctx._im(q), wp)\\n        x2re = (xre*xre - xim*xim) >> wp\\n        x2im = (xre*xim) >> (wp - 1)\\n        are = bre = x2re\\n        aim = bim = x2im\\n        prec0 = ctx.prec\\n        ctx.prec = wp\\n        # cos(2*z), sin(2*z) with z complex\\n        c1, s1 = ctx.cos_sin(z)\\n        ctx.prec = prec0\\n        cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n        cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n        snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n        snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n        c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp\\n        c2im = (c1re*c1im - s1re*s1im) >> (wp - 1)\\n        s2re = (c1re*s1re - c1im*s1im) >> (wp - 1)\\n        s2im = (c1re*s1im + c1im*s1re) >> (wp - 1)\\n        t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n        t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n        t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n        t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n        cnre = t1\\n        cnim = t2\\n        snre = t3\\n        snim = t4\\n        if (nd&1):\\n            sre = s1re + (((are * snre - aim * snim) * 3**nd) >> wp)\\n            sim = s1im + (((are * snim + aim * snre)* 3**nd) >> wp)\\n        else:\\n            sre = c1re + (((are * cnre - aim * cnim) * 3**nd) >> wp)\\n            sim = c1im + (((are * cnim + aim * cnre)* 3**nd) >> wp)\\n        n = 5\\n        while are**2 + aim**2 > MIN:\\n            bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                       (bre * x2im + bim * x2re) >> wp\\n            are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                       (are * bim + aim * bre) >> wp\\n            #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n            t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp\\n            t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp\\n            t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp\\n            t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            if (nd&1):\\n                sre += (((are * snre - aim * snim) * n**nd) >> wp)\\n                sim += (((aim * snre + are * snim) * n**nd) >> wp)\\n            else:\\n                sre += (((are * cnre - aim * cnim) * n**nd) >> wp)\\n                sim += (((aim * cnre + are * cnim) * n**nd) >> wp)\\n            n += 2\\n        sre = -(sre << 1)\\n        sim = -(sim << 1)\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    s *= ctx.nthroot(q, 4)\\n    if (nd&1):\\n        return (-1)**(nd//2) * s\\n    else:\\n        return (-1)**(1 + nd//2) * s\\n\\n@defun\\ndef _jacobi_theta3(ctx, z, q):\\n    extra1 = 10\\n    extra2 = 20\\n    MIN = 2\\n    if z == ctx.zero:\\n        if not ctx._im(q):\\n            wp = ctx.prec + extra1\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            s = x\\n            a = b = x\\n            x2 = (x*x) >> wp\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                s += a\\n            s = (1 << wp) + (s << 1)\\n            s = ctx.ldexp(s, -wp)\\n            return s\\n        else:\\n            wp = ctx.prec + extra1\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp - 1)\\n            sre = are = bre = xre\\n            sim = aim = bim = xim\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                sre += are\\n                sim += aim\\n            sre = (1 << wp) + (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n            return s\\n    else:\\n        if (not ctx._im(q)) and (not ctx._im(z)):\\n            s = 0\\n            wp = ctx.prec + extra1\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            a = b = x\\n            x2 = (x*x) >> wp\\n            c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp)\\n            c1 = ctx.to_fixed(c1, wp)\\n            s1 = ctx.to_fixed(s1, wp)\\n            cn = c1\\n            sn = s1\\n            s += (a * cn) >> wp\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n                s += (a * cn) >> wp\\n            s = (1 << wp) + (s << 1)\\n            s = ctx.ldexp(s, -wp)\\n            return s\\n        # case z real, q complex\\n        elif not ctx._im(z):\\n            wp = ctx.prec + extra2\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp - 1)\\n            are = bre = xre\\n            aim = bim = xim\\n            c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp)\\n            c1 = ctx.to_fixed(c1, wp)\\n            s1 = ctx.to_fixed(s1, wp)\\n            cn = c1\\n            sn = s1\\n            sre = (are * cn) >> wp\\n            sim = (aim * cn) >> wp\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n                sre += (are * cn) >> wp\\n                sim += (aim * cn) >> wp\\n            sre = (1 << wp) + (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n            return s\\n        #case z complex, q real\\n        elif not ctx._im(q):\\n            wp = ctx.prec + extra2\\n            x = ctx.to_fixed(ctx._re(q), wp)\\n            a = b = x\\n            x2 = (x*x) >> wp\\n            prec0 = ctx.prec\\n            ctx.prec = wp\\n            c1, s1 = ctx.cos_sin(2*z)\\n            ctx.prec = prec0\\n            cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n            cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n            snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n            snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n            sre = (a * cnre) >> wp\\n            sim = (a * cnim) >> wp\\n            while abs(a) > MIN:\\n                b = (b*x2) >> wp\\n                a = (a*b) >> wp\\n                t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp\\n                t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp\\n                t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp\\n                t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp\\n                cnre = t1\\n                cnim = t2\\n                snre = t3\\n                snim = t4\\n                sre += (a * cnre) >> wp\\n                sim += (a * cnim) >> wp\\n            sre = (1 << wp) + (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n            return s\\n        # case z and q complex\\n        else:\\n            wp = ctx.prec + extra2\\n            xre = ctx.to_fixed(ctx._re(q), wp)\\n            xim = ctx.to_fixed(ctx._im(q), wp)\\n            x2re = (xre*xre - xim*xim) >> wp\\n            x2im = (xre*xim) >> (wp - 1)\\n            are = bre = xre\\n            aim = bim = xim\\n            prec0 = ctx.prec\\n            ctx.prec = wp\\n            # cos(2*z), sin(2*z) with z complex\\n            c1, s1 = ctx.cos_sin(2*z)\\n            ctx.prec = prec0\\n            cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n            cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n            snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n            snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n            sre = (are * cnre - aim * cnim) >> wp\\n            sim = (aim * cnre + are * cnim) >> wp\\n            while are**2 + aim**2 > MIN:\\n                bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                           (bre * x2im + bim * x2re) >> wp\\n                are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                           (are * bim + aim * bre) >> wp\\n                t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp\\n                t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp\\n                t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp\\n                t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp\\n                cnre = t1\\n                cnim = t2\\n                snre = t3\\n                snim = t4\\n                sre += (are * cnre - aim * cnim) >> wp\\n                sim += (aim * cnre + are * cnim) >> wp\\n            sre = (1 << wp) + (sre << 1)\\n            sim = (sim << 1)\\n            sre = ctx.ldexp(sre, -wp)\\n            sim = ctx.ldexp(sim, -wp)\\n            s = ctx.mpc(sre, sim)\\n            return s\\n\\n@defun\\ndef _djacobi_theta3(ctx, z, q, nd):\\n    \\\"\\\"\\\"nd=1,2,3 order of the derivative with respect to z\\\"\\\"\\\"\\n    MIN = 2\\n    extra1 = 10\\n    extra2 = 20\\n    if (not ctx._im(q)) and (not ctx._im(z)):\\n        s = 0\\n        wp = ctx.prec + extra1\\n        x = ctx.to_fixed(ctx._re(q), wp)\\n        a = b = x\\n        x2 = (x*x) >> wp\\n        c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp)\\n        c1 = ctx.to_fixed(c1, wp)\\n        s1 = ctx.to_fixed(s1, wp)\\n        cn = c1\\n        sn = s1\\n        if (nd&1):\\n            s += (a * sn) >> wp\\n        else:\\n            s += (a * cn) >> wp\\n        n = 2\\n        while abs(a) > MIN:\\n            b = (b*x2) >> wp\\n            a = (a*b) >> wp\\n            cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n            if nd&1:\\n                s += (a * sn * n**nd) >> wp\\n            else:\\n                s += (a * cn * n**nd) >> wp\\n            n += 1\\n        s = -(s << (nd+1))\\n        s = ctx.ldexp(s, -wp)\\n    # case z real, q complex\\n    elif not ctx._im(z):\\n        wp = ctx.prec + extra2\\n        xre = ctx.to_fixed(ctx._re(q), wp)\\n        xim = ctx.to_fixed(ctx._im(q), wp)\\n        x2re = (xre*xre - xim*xim) >> wp\\n        x2im = (xre*xim) >> (wp - 1)\\n        are = bre = xre\\n        aim = bim = xim\\n        c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp)\\n        c1 = ctx.to_fixed(c1, wp)\\n        s1 = ctx.to_fixed(s1, wp)\\n        cn = c1\\n        sn = s1\\n        if (nd&1):\\n            sre = (are * sn) >> wp\\n            sim = (aim * sn) >> wp\\n        else:\\n            sre = (are * cn) >> wp\\n            sim = (aim * cn) >> wp\\n        n = 2\\n        while are**2 + aim**2 > MIN:\\n            bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                       (bre * x2im + bim * x2re) >> wp\\n            are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                       (are * bim + aim * bre) >> wp\\n            cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp\\n            if nd&1:\\n                sre += (are * sn * n**nd) >> wp\\n                sim += (aim * sn * n**nd) >> wp\\n            else:\\n                sre += (are * cn * n**nd) >> wp\\n                sim += (aim * cn * n**nd) >> wp\\n            n += 1\\n        sre = -(sre << (nd+1))\\n        sim = -(sim << (nd+1))\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    #case z complex, q real\\n    elif not ctx._im(q):\\n        wp = ctx.prec + extra2\\n        x = ctx.to_fixed(ctx._re(q), wp)\\n        a = b = x\\n        x2 = (x*x) >> wp\\n        prec0 = ctx.prec\\n        ctx.prec = wp\\n        c1, s1 = ctx.cos_sin(2*z)\\n        ctx.prec = prec0\\n        cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n        cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n        snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n        snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n        if (nd&1):\\n            sre = (a * snre) >> wp\\n            sim = (a * snim) >> wp\\n        else:\\n            sre = (a * cnre) >> wp\\n            sim = (a * cnim) >> wp\\n        n = 2\\n        while abs(a) > MIN:\\n            b = (b*x2) >> wp\\n            a = (a*b) >> wp\\n            t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp\\n            t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp\\n            t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp\\n            t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            if (nd&1):\\n                sre += (a * snre * n**nd) >> wp\\n                sim += (a * snim * n**nd) >> wp\\n            else:\\n                sre += (a * cnre * n**nd) >> wp\\n                sim += (a * cnim * n**nd) >> wp\\n            n += 1\\n        sre = -(sre << (nd+1))\\n        sim = -(sim << (nd+1))\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    # case z and q complex\\n    else:\\n        wp = ctx.prec + extra2\\n        xre = ctx.to_fixed(ctx._re(q), wp)\\n        xim = ctx.to_fixed(ctx._im(q), wp)\\n        x2re = (xre*xre - xim*xim) >> wp\\n        x2im = (xre*xim) >> (wp - 1)\\n        are = bre = xre\\n        aim = bim = xim\\n        prec0 = ctx.prec\\n        ctx.prec = wp\\n        # cos(2*z), sin(2*z) with z complex\\n        c1, s1 = ctx.cos_sin(2*z)\\n        ctx.prec = prec0\\n        cnre = c1re = ctx.to_fixed(ctx._re(c1), wp)\\n        cnim = c1im = ctx.to_fixed(ctx._im(c1), wp)\\n        snre = s1re = ctx.to_fixed(ctx._re(s1), wp)\\n        snim = s1im = ctx.to_fixed(ctx._im(s1), wp)\\n        if (nd&1):\\n            sre = (are * snre - aim * snim) >> wp\\n            sim = (aim * snre + are * snim) >> wp\\n        else:\\n            sre = (are * cnre - aim * cnim) >> wp\\n            sim = (aim * cnre + are * cnim) >> wp\\n        n = 2\\n        while are**2 + aim**2 > MIN:\\n            bre, bim = (bre * x2re - bim * x2im) >> wp, \\\\\\n                       (bre * x2im + bim * x2re) >> wp\\n            are, aim = (are * bre - aim * bim) >> wp,   \\\\\\n                       (are * bim + aim * bre) >> wp\\n            t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp\\n            t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp\\n            t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp\\n            t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp\\n            cnre = t1\\n            cnim = t2\\n            snre = t3\\n            snim = t4\\n            if(nd&1):\\n                sre += ((are * snre - aim * snim) * n**nd) >> wp\\n                sim += ((aim * snre + are * snim) * n**nd) >> wp\\n            else:\\n                sre += ((are * cnre - aim * cnim) * n**nd) >> wp\\n                sim += ((aim * cnre + are * cnim) * n**nd) >> wp\\n            n += 1\\n        sre = -(sre << (nd+1))\\n        sim = -(sim << (nd+1))\\n        sre = ctx.ldexp(sre, -wp)\\n        sim = ctx.ldexp(sim, -wp)\\n        s = ctx.mpc(sre, sim)\\n    if (nd&1):\\n        return (-1)**(nd//2) * s\\n    else:\\n        return (-1)**(1 + nd//2) * s\\n\\n@defun\\ndef _jacobi_theta2a(ctx, z, q):\\n    \\\"\\\"\\\"\\n    case ctx._im(z) != 0\\n    theta(2, z, q) =\\n    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=-inf, inf)\\n    max term for minimum (2*n+1)*log(q).real - 2* ctx._im(z)\\n    n0 = int(ctx._im(z)/log(q).real - 1/2)\\n    theta(2, z, q) =\\n    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=n0, inf) +\\n    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n, n0-1, -inf)\\n    \\\"\\\"\\\"\\n    n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2)\\n    e2 = ctx.expj(2*z)\\n    e = e0 = ctx.expj((2*n+1)*z)\\n    a = q**(n*n + n)\\n    # leading term\\n    term = a * e\\n    s = term\\n    eps1 = ctx.eps*abs(term)\\n    while 1:\\n        n += 1\\n        e = e * e2\\n        term = q**(n*n + n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    e = e0\\n    e2 = ctx.expj(-2*z)\\n    n = n0\\n    while 1:\\n        n -= 1\\n        e = e * e2\\n        term = q**(n*n + n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    s = s * ctx.nthroot(q, 4)\\n    return s\\n\\n@defun\\ndef _jacobi_theta3a(ctx, z, q):\\n    \\\"\\\"\\\"\\n    case ctx._im(z) != 0\\n    theta3(z, q) = Sum(q**(n*n) * exp(j*2*n*z), n, -inf, inf)\\n    max term for n*abs(log(q).real) + ctx._im(z) ~= 0\\n    n0 = int(- ctx._im(z)/abs(log(q).real))\\n    \\\"\\\"\\\"\\n    n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q))))\\n    e2 = ctx.expj(2*z)\\n    e = e0 = ctx.expj(2*n*z)\\n    s = term = q**(n*n) * e\\n    eps1 = ctx.eps*abs(term)\\n    while 1:\\n        n += 1\\n        e = e * e2\\n        term = q**(n*n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    e = e0\\n    e2 = ctx.expj(-2*z)\\n    n = n0\\n    while 1:\\n        n -= 1\\n        e = e * e2\\n        term = q**(n*n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    return s\\n\\n@defun\\ndef _djacobi_theta2a(ctx, z, q, nd):\\n    \\\"\\\"\\\"\\n    case ctx._im(z) != 0\\n    dtheta(2, z, q, nd) =\\n    j* q**1/4 * Sum(q**(n*n + n) * (2*n+1)*exp(j*(2*n + 1)*z), n=-inf, inf)\\n    max term for (2*n0+1)*log(q).real - 2* ctx._im(z) ~= 0\\n    n0 = int(ctx._im(z)/log(q).real - 1/2)\\n    \\\"\\\"\\\"\\n    n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2)\\n    e2 = ctx.expj(2*z)\\n    e = e0 = ctx.expj((2*n + 1)*z)\\n    a = q**(n*n + n)\\n    # leading term\\n    term = (2*n+1)**nd * a * e\\n    s = term\\n    eps1 = ctx.eps*abs(term)\\n    while 1:\\n        n += 1\\n        e = e * e2\\n        term = (2*n+1)**nd * q**(n*n + n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    e = e0\\n    e2 = ctx.expj(-2*z)\\n    n = n0\\n    while 1:\\n        n -= 1\\n        e = e * e2\\n        term = (2*n+1)**nd * q**(n*n + n) * e\\n        if abs(term) < eps1:\\n            break\\n        s += term\\n    return ctx.j**nd * s * ctx.nthroot(q, 4)\\n\\n@defun\\ndef _djacobi_theta3a(ctx, z, q, nd):\\n    \\\"\\\"\\\"\\n    case ctx._im(z) != 0\\n    djtheta3(z, q, nd) = (2*j)**nd *\\n      Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf)\\n    max term for minimum n*abs(log(q).real) + ctx._im(z)\\n    \\\"\\\"\\\"\\n    n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q))))\\n    e2 = ctx.expj(2*z)\\n    e = e0 = ctx.expj(2*n*z)\\n    a = q**(n*n) * e\\n    s = term = n**nd * a\\n    if n != 0:\\n        eps1 = ctx.eps*abs(term)\\n    else:\\n        eps1 = ctx.eps*abs(a)\\n    while 1:\\n        n += 1\\n        e = e * e2\\n        a = q**(n*n) * e\\n        term = n**nd * a\\n        if n != 0:\\n            aterm = abs(term)\\n        else:\\n            aterm = abs(a)\\n        if aterm < eps1:\\n            break\\n        s += term\\n    e = e0\\n    e2 = ctx.expj(-2*z)\\n    n = n0\\n    while 1:\\n        n -= 1\\n        e = e * e2\\n        a = q**(n*n) * e\\n        term = n**nd * a\\n        if n != 0:\\n            aterm = abs(term)\\n        else:\\n            aterm = abs(a)\\n        if aterm < eps1:\\n            break\\n        s += term\\n    return (2*ctx.j)**nd * s\\n\\n@defun\\ndef jtheta(ctx, n, z, q, derivative=0):\\n    if derivative:\\n        return ctx._djtheta(n, z, q, derivative)\\n\\n    z = ctx.convert(z)\\n    q = ctx.convert(q)\\n\\n    # Implementation note\\n    # If ctx._im(z) is close to zero, _jacobi_theta2 and _jacobi_theta3\\n    # are used,\\n    # which compute the series starting from n=0 using fixed precision\\n    # numbers;\\n    # otherwise  _jacobi_theta2a and _jacobi_theta3a are used, which compute\\n    # the series starting from n=n0, which is the largest term.\\n\\n    # TODO: write _jacobi_theta2a and _jacobi_theta3a using fixed-point\\n\\n    if abs(q) > ctx.THETA_Q_LIM:\\n        raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM)\\n\\n    extra = 10\\n    if z:\\n        M = ctx.mag(z)\\n        if M > 5 or (n == 1 and M < -5):\\n            extra += 2*abs(M)\\n    cz = 0.5\\n    extra2 = 50\\n    prec0 = ctx.prec\\n    try:\\n        ctx.prec += extra\\n        if n == 1:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._jacobi_theta2(z - ctx.pi/2, q)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._jacobi_theta2a(z - ctx.pi/2, q)\\n            else:\\n                res = ctx._jacobi_theta2(z - ctx.pi/2, q)\\n        elif n == 2:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._jacobi_theta2(z, q)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._jacobi_theta2a(z, q)\\n            else:\\n                res = ctx._jacobi_theta2(z, q)\\n        elif n == 3:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._jacobi_theta3(z, q)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._jacobi_theta3a(z, q)\\n            else:\\n                res = ctx._jacobi_theta3(z, q)\\n        elif n == 4:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._jacobi_theta3(z, -q)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._jacobi_theta3a(z, -q)\\n            else:\\n                res = ctx._jacobi_theta3(z, -q)\\n        else:\\n            raise ValueError\\n    finally:\\n        ctx.prec = prec0\\n    return res\\n\\n@defun\\ndef _djtheta(ctx, n, z, q, derivative=1):\\n    z = ctx.convert(z)\\n    q = ctx.convert(q)\\n    nd = int(derivative)\\n\\n    if abs(q) > ctx.THETA_Q_LIM:\\n        raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM)\\n    extra = 10 + ctx.prec * nd // 10\\n    if z:\\n        M = ctx.mag(z)\\n        if M > 5 or (n != 1 and M < -5):\\n            extra += 2*abs(M)\\n    cz = 0.5\\n    extra2 = 50\\n    prec0 = ctx.prec\\n    try:\\n        ctx.prec += extra\\n        if n == 1:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._djacobi_theta2a(z - ctx.pi/2, q, nd)\\n            else:\\n                res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd)\\n        elif n == 2:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._djacobi_theta2(z, q, nd)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._djacobi_theta2a(z, q, nd)\\n            else:\\n                res = ctx._djacobi_theta2(z, q, nd)\\n        elif n == 3:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._djacobi_theta3(z, q, nd)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._djacobi_theta3a(z, q, nd)\\n            else:\\n                res = ctx._djacobi_theta3(z, q, nd)\\n        elif n == 4:\\n            if ctx._im(z):\\n                if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))):\\n                    ctx.dps += extra2\\n                    res = ctx._djacobi_theta3(z, -q, nd)\\n                else:\\n                    ctx.dps += 10\\n                    res = ctx._djacobi_theta3a(z, -q, nd)\\n            else:\\n                res = ctx._djacobi_theta3(z, -q, nd)\\n        else:\\n            raise ValueError\\n    finally:\\n        ctx.prec = prec0\\n    return +res\\n\\n\\nfrom . import functions\\n# Hack to update methods\\nfrom . import factorials\\nfrom . import hypergeometric\\nfrom . import expintegrals\\nfrom . import bessel\\nfrom . import orthogonal\\nfrom . import theta\\nfrom . import elliptic\\nfrom . import signals\\nfrom . import zeta\\nfrom . import rszeta\\nfrom . import zetazeros\\nfrom . import qfunctions\\n\\n\\n\\\"\\\"\\\"\\n---------------------------------------------------------------------\\n.. sectionauthor:: Juan Arias de Reyna <arias@us.es>\\n\\nThis module implements zeta-related functions using the Riemann-Siegel\\nexpansion: zeta_offline(s,k=0)\\n\\n* coef(J, eps): Need in the computation of Rzeta(s,k)\\n\\n* Rzeta_simul(s, der=0) computes Rzeta^(k)(s) and Rzeta^(k)(1-s) simultaneously\\n  for  0 <= k <= der. Used by zeta_offline and z_offline\\n\\n* Rzeta_set(s, derivatives) computes Rzeta^(k)(s) for given derivatives, used by\\n  z_half(t,k) and zeta_half\\n\\n* z_offline(w,k): Z(w) and its derivatives of order k <= 4\\n* z_half(t,k): Z(t) (Riemann Siegel function) and its derivatives of order k <= 4\\n* zeta_offline(s): zeta(s) and its derivatives of order k<= 4\\n* zeta_half(1/2+it,k):  zeta(s)  and its derivatives of order k<= 4\\n\\n* rs_zeta(s,k=0) Computes zeta^(k)(s)   Unifies zeta_half and zeta_offline\\n* rs_z(w,k=0)    Computes Z^(k)(w)      Unifies z_offline and z_half\\n----------------------------------------------------------------------\\n\\nThis program uses Riemann-Siegel expansion even to compute\\nzeta(s) on points s = sigma + i t  with sigma arbitrary not\\nnecessarily equal to 1/2.\\n\\nIt is founded on a new deduction of the formula, with rigorous\\nand sharp bounds for the  terms and rest of this expansion.\\n\\nMore information on the papers:\\n\\n J. Arias de Reyna, High Precision Computation of Riemann's\\n Zeta Function by the Riemann-Siegel Formula I, II\\n\\n We refer to them as I, II.\\n\\n In them we shall find detailed explanation of all the\\n procedure.\\n\\nThe program uses Riemann-Siegel expansion.\\nThis  is useful when t is big, ( say  t > 10000 ).\\nThe precision is limited, roughly it can compute zeta(sigma+it)\\nwith an error less than exp(-c t) for some constant c depending\\non sigma.  The program gives an error when the Riemann-Siegel\\nformula can not compute to the wanted precision.\\n\\n\\\"\\\"\\\"\\n\\nimport math\\n\\nclass RSCache(object):\\n    def __init__(ctx):\\n        ctx._rs_cache = [0, 10, {}, {}]\\n\\nfrom .functions import defun\\n\\n#-------------------------------------------------------------------------------#\\n#                                                                               #\\n#                       coef(ctx, J, eps, _cache=[0, 10, {} ] )                 #\\n#                                                                               #\\n#-------------------------------------------------------------------------------#\\n\\n#  This function computes the coefficients c[n] defined on (I, equation (47))\\n#  but see also  (II, section 3.14).\\n#\\n#  Since these coefficients are very difficult to compute we save the values\\n#  in a cache. So if we compute several values of the functions Rzeta(s) for\\n#  near values of s, we do not recompute these coefficients.\\n#\\n#  c[n] are the Taylor coefficients of the function:\\n#\\n#  F(z):= (exp(pi*j*(z*z/2+3/8))-j* sqrt(2) cos(pi*z/2))/(2*cos(pi *z))\\n#\\n#\\n\\ndef _coef(ctx, J, eps):\\n    r\\\"\\\"\\\"\\n    Computes the coefficients  `c_n`  for `0\\\\le n\\\\le 2J` with error less than eps\\n\\n    **Definition**\\n\\n    The coefficients c_n are defined by\\n\\n    .. math ::\\n\\n        \\\\begin{equation}\\n        F(z)=\\\\frac{e^{\\\\pi i\\n        \\\\bigl(\\\\frac{z^2}{2}+\\\\frac38\\\\bigr)}-i\\\\sqrt{2}\\\\cos\\\\frac{\\\\pi}{2}z}{2\\\\cos\\\\pi\\n        z}=\\\\sum_{n=0}^\\\\infty c_{2n} z^{2n}\\n        \\\\end{equation}\\n\\n    they are computed applying the relation\\n\\n    .. math ::\\n\\n        \\\\begin{multline}\\n        c_{2n}=-\\\\frac{i}{\\\\sqrt{2}}\\\\Bigl(\\\\frac{\\\\pi}{2}\\\\Bigr)^{2n}\\n        \\\\sum_{k=0}^n\\\\frac{(-1)^k}{(2k)!}\\n        2^{2n-2k}\\\\frac{(-1)^{n-k}E_{2n-2k}}{(2n-2k)!}+\\\\\\\\\\n        +e^{3\\\\pi i/8}\\\\sum_{j=0}^n(-1)^j\\\\frac{\\n        E_{2j}}{(2j)!}\\\\frac{i^{n-j}\\\\pi^{n+j}}{(n-j)!2^{n-j+1}}.\\n        \\\\end{multline}\\n    \\\"\\\"\\\"\\n\\n    newJ = J+2        # compute more coefficients that are needed\\n    neweps6 = eps/2.  # compute with a slight more precision that are needed\\n\\n    #  PREPARATION FOR THE COMPUTATION OF V(N) AND W(N)\\n    #    See II Section 3.16\\n    #\\n    #  Computing the exponent wpvw of the error II equation (81)\\n    wpvw = max(ctx.mag(10*(newJ+3)), 4*newJ+5-ctx.mag(neweps6))\\n\\n    #  Preparation of Euler numbers (we need until the 2*RS_NEWJ)\\n    E = ctx._eulernum(2*newJ)\\n\\n    #  Now we have in the cache all the needed Euler numbers.\\n    #\\n    #  Computing the powers of pi\\n    #\\n    # We need to compute the powers pi**n for 1<= n <= 2*J\\n    # with relative error less than 2**(-wpvw)\\n    # it is easy to show that this is obtained\\n    # taking wppi as the least d with\\n    # 2**d>40*J and 2**d> 4.24 *newJ + 2**wpvw\\n    # In II Section 3.9 we need also that\\n    #  wppi > wptcoef[0], and that the powers\\n    # here computed  0<= k <= 2*newJ are more\\n    # than those needed there that are 2*L-2.\\n    # so we need  J >= L this will be checked\\n    # before computing tcoef[]\\n    wppi = max(ctx.mag(40*newJ), ctx.mag(newJ)+3 +wpvw)\\n    ctx.prec = wppi\\n    pipower = {}\\n    pipower[0] = ctx.one\\n    pipower[1] = ctx.pi\\n    for n in range(2,2*newJ+1):\\n        pipower[n] = pipower[n-1]*ctx.pi\\n\\n    # COMPUTING THE COEFFICIENTS v(n) AND w(n)\\n    #  see II equation (61) and equations (81) and (82)\\n    ctx.prec = wpvw+2\\n    v={}\\n    w={}\\n    for n in range(0,newJ+1):\\n        va = (-1)**n * ctx._eulernum(2*n)\\n        va = ctx.mpf(va)/ctx.fac(2*n)\\n        v[n]=va*pipower[2*n]\\n    for n in range(0,2*newJ+1):\\n        wa = ctx.one/ctx.fac(n)\\n        wa=wa/(2**n)\\n        w[n]=wa*pipower[n]\\n\\n    # COMPUTATION OF THE CONVOLUTIONS RS_P1 AND RS_P2\\n    #  See II Section 3.16\\n    ctx.prec = 15\\n    wpp1a = 9 - ctx.mag(neweps6)\\n    P1 = {}\\n    for n in range(0,newJ+1):\\n        ctx.prec = 15\\n        wpp1 = max(ctx.mag(10*(n+4)),4*n+wpp1a)\\n        ctx.prec = wpp1\\n        sump = 0\\n        for k in range(0,n+1):\\n            sump += ((-1)**k) * v[k]*w[2*n-2*k]\\n        P1[n]=((-1)**(n+1))*ctx.j*sump\\n    P2={}\\n    for n in range(0,newJ+1):\\n        ctx.prec = 15\\n        wpp2 = max(ctx.mag(10*(n+4)),4*n+wpp1a)\\n        ctx.prec = wpp2\\n        sump = 0\\n        for k in range(0,n+1):\\n            sump += (ctx.j**(n-k)) * v[k]*w[n-k]\\n        P2[n]=sump\\n    # COMPUTING THE COEFFICIENTS c[2n]\\n    # See II Section 3.14\\n    ctx.prec = 15\\n    wpc0 = 5 - ctx.mag(neweps6)\\n    wpc = max(6,4*newJ+wpc0)\\n    ctx.prec = wpc\\n    mu = ctx.sqrt(ctx.mpf('2'))/2\\n    nu = ctx.expjpi(3./8)/2\\n    c={}\\n    for n in range(0,newJ):\\n        ctx.prec = 15\\n        wpc = max(6,4*n+wpc0)\\n        ctx.prec = wpc\\n        c[2*n] = mu*P1[n]+nu*P2[n]\\n    for n in range(1,2*newJ,2):\\n        c[n] = 0\\n    return [newJ, neweps6, c, pipower]\\n\\ndef coef(ctx, J, eps):\\n    _cache = ctx._rs_cache\\n    if J <= _cache[0] and eps >= _cache[1]:\\n        return _cache[2], _cache[3]\\n    orig = ctx._mp.prec\\n    try:\\n        data = _coef(ctx._mp, J, eps)\\n    finally:\\n        ctx._mp.prec = orig\\n    if ctx is not ctx._mp:\\n        data[2] = dict((k,ctx.convert(v)) for (k,v) in data[2].items())\\n        data[3] = dict((k,ctx.convert(v)) for (k,v) in data[3].items())\\n    ctx._rs_cache[:] = data\\n    return ctx._rs_cache[2], ctx._rs_cache[3]\\n\\n#-------------------------------------------------------------------------------#\\n#                                                                               #\\n#                          Rzeta_simul(s,k=0)                                   #\\n#                                                                               #\\n#-------------------------------------------------------------------------------#\\n#  This function return a list with the values:\\n#  Rzeta(sigma+it), conj(Rzeta(1-sigma+it)),Rzeta'(sigma+it), conj(Rzeta'(1-sigma+it)),\\n#  .... , Rzeta^{(k)}(sigma+it), conj(Rzeta^{(k)}(1-sigma+it))\\n#\\n#  Useful to compute  the function zeta(s) and Z(w)  or its derivatives.\\n#\\n\\ndef aux_M_Fp(ctx, xA, xeps4, a, xB1, xL):\\n    # COMPUTING M  NUMBER OF DERIVATIVES Fp[m] TO COMPUTE\\n    #  See II Section 3.11  equations (47) and (48)\\n    aux1 = 126.0657606*xA/xeps4   # 126.06.. = 316/sqrt(2*pi)\\n    aux1 = ctx.ln(aux1)\\n    aux2 = (2*ctx.ln(ctx.pi)+ctx.ln(xB1)+ctx.ln(a))/3 -ctx.ln(2*ctx.pi)/2\\n    m = 3*xL-3\\n    aux3= (ctx.loggamma(m+1)-ctx.loggamma(m/3.0+2))/2 -ctx.loggamma((m+1)/2.)\\n    while((aux1 < m*aux2+ aux3)and (m>1)):\\n        m = m - 1\\n        aux3 = (ctx.loggamma(m+1)-ctx.loggamma(m/3.0+2))/2 -ctx.loggamma((m+1)/2.)\\n    xM = m\\n    return xM\\n\\ndef aux_J_needed(ctx, xA, xeps4, a, xB1, xM):\\n    #  DETERMINATION OF  J  THE NUMBER OF TERMS NEEDED\\n    #            IN THE TAYLOR SERIES OF F.\\n    #  See II Section 3.11 equation (49))\\n    #  Only determine one\\n    h1 = xeps4/(632*xA)\\n    h2 = xB1*a * 126.31337419529260248  # = pi^2*e^2*sqrt(3)\\n    h2 = h1 * ctx.power((h2/xM**2),(xM-1)/3) / xM\\n    h3 = min(h1,h2)\\n    return h3\\n\\ndef Rzeta_simul(ctx, s, der=0):\\n    # First we take the value of ctx.prec\\n    wpinitial = ctx.prec\\n\\n    # INITIALIZATION\\n    # Take the real and imaginary part of s\\n    t = ctx._im(s)\\n    xsigma = ctx._re(s)\\n    ysigma = 1 - xsigma\\n\\n    # Now compute several parameter that appear on the program\\n    ctx.prec = 15\\n    a = ctx.sqrt(t/(2*ctx.pi))\\n    xasigma = a ** xsigma\\n    yasigma = a ** ysigma\\n\\n    # We need a simple bound A1 < asigma  (see II Section 3.1 and 3.3)\\n    xA1=ctx.power(2, ctx.mag(xasigma)-1)\\n    yA1=ctx.power(2, ctx.mag(yasigma)-1)\\n\\n    # We compute various epsilon's  (see II end of Section 3.1)\\n    eps = ctx.power(2, -wpinitial)\\n    eps1 = eps/6.\\n    xeps2 = eps * xA1/3.\\n    yeps2 = eps * yA1/3.\\n\\n    #  COMPUTING SOME COEFFICIENTS THAT DEPENDS\\n    #                ON  sigma\\n    #  constant b and c  (see I  Theorem 2 formula (26) )\\n    #  coefficients A and B1  (see I Section 6.1 equation (50))\\n    #\\n    # here we not need high precision\\n    ctx.prec = 15\\n    if xsigma > 0:\\n        xb = 2.\\n        xc = math.pow(9,xsigma)/4.44288\\n        # 4.44288 =(math.sqrt(2)*math.pi)\\n        xA = math.pow(9,xsigma)\\n        xB1 = 1\\n    else:\\n        xb = 2.25158  #  math.sqrt( (3-2* math.log(2))*math.pi )\\n        xc = math.pow(2,-xsigma)/4.44288\\n        xA = math.pow(2,-xsigma)\\n        xB1 = 1.10789   #  = 2*sqrt(1-log(2))\\n\\n    if(ysigma > 0):\\n        yb = 2.\\n        yc = math.pow(9,ysigma)/4.44288\\n        # 4.44288 =(math.sqrt(2)*math.pi)\\n        yA = math.pow(9,ysigma)\\n        yB1 = 1\\n    else:\\n        yb = 2.25158  #  math.sqrt( (3-2* math.log(2))*math.pi )\\n        yc = math.pow(2,-ysigma)/4.44288\\n        yA = math.pow(2,-ysigma)\\n        yB1 = 1.10789   #  = 2*sqrt(1-log(2))\\n\\n    #  COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL\\n    #                         CORRECTION\\n    #  See II Section 3.2\\n    ctx.prec = 15\\n    xL = 1\\n    while 3*xc*ctx.gamma(xL*0.5) * ctx.power(xb*a,-xL) >= xeps2:\\n        xL = xL+1\\n    xL = max(2,xL)\\n    yL = 1\\n    while 3*yc*ctx.gamma(yL*0.5) * ctx.power(yb*a,-yL) >= yeps2:\\n        yL = yL+1\\n    yL = max(2,yL)\\n\\n    #  The number L has to satify some conditions.\\n    #  If not RS can not compute Rzeta(s) with the prescribed precision\\n    #  (see II, Section 3.2 condition (20)  ) and\\n    #  (II, Section 3.3 condition (22) ). Also we have added\\n    #  an additional technical  condition in Section 3.17 Proposition 17\\n    if ((3*xL >= 2*a*a/25.) or (3*xL+2+xsigma<0) or (abs(xsigma) > a/2.) or \\\\\\n        (3*yL >= 2*a*a/25.) or (3*yL+2+ysigma<0) or (abs(ysigma) > a/2.)):\\n        ctx.prec = wpinitial\\n        raise NotImplementedError(\\\"Riemann-Siegel can not compute with such precision\\\")\\n\\n    #  We take the maximum of the two values\\n    L = max(xL, yL)\\n\\n    #  INITIALIZATION (CONTINUATION)\\n    #\\n    # eps3 is the constant defined on (II, Section 3.5 equation (27) )\\n    # each term of the RS correction must be computed with error <= eps3\\n    xeps3 =  xeps2/(4*xL)\\n    yeps3 =  yeps2/(4*yL)\\n\\n    # eps4 is defined on (II Section 3.6  equation (30) )\\n    # each component of the formula (II Section 3.6 equation (29) )\\n    # must be computed with error <= eps4\\n    xeps4 = xeps3/(3*xL)\\n    yeps4 = yeps3/(3*yL)\\n\\n    # COMPUTING M NUMBER OF DERIVATIVES Fp[m] TO COMPUTE\\n    xM = aux_M_Fp(ctx, xA, xeps4, a, xB1, xL)\\n    yM = aux_M_Fp(ctx, yA, yeps4, a, yB1, yL)\\n    M = max(xM, yM)\\n\\n    # COMPUTING NUMBER OF TERMS J NEEDED\\n    h3 = aux_J_needed(ctx, xA, xeps4, a, xB1, xM)\\n    h4 = aux_J_needed(ctx, yA, yeps4, a, yB1, yM)\\n    h3 = min(h3,h4)\\n    J = 12\\n    jvalue = (2*ctx.pi)**J / ctx.gamma(J+1)\\n    while jvalue > h3:\\n        J = J+1\\n        jvalue = (2*ctx.pi)*jvalue/J\\n\\n    # COMPUTING eps5[m] for 1 <= m <= 21\\n    #  See II Section 10 equation (43)\\n    #  We choose the minimum of the two possibilities\\n    eps5={}\\n    xforeps5 = math.pi*math.pi*xB1*a\\n    yforeps5 = math.pi*math.pi*yB1*a\\n    for m in range(0,22):\\n        xaux1 = math.pow(xforeps5, m/3)/(316.*xA)\\n        yaux1 = math.pow(yforeps5, m/3)/(316.*yA)\\n        aux1 = min(xaux1, yaux1)\\n        aux2 = ctx.gamma(m+1)/ctx.gamma(m/3.0+0.5)\\n        aux2 = math.sqrt(aux2)\\n        eps5[m] = (aux1*aux2*min(xeps4,yeps4))\\n\\n    # COMPUTING wpfp\\n    #  See II Section 3.13 equation (59)\\n    twenty = min(3*L-3, 21)+1\\n    aux = 6812*J\\n    wpfp = ctx.mag(44*J)\\n    for m in range(0,twenty):\\n        wpfp = max(wpfp, ctx.mag(aux*ctx.gamma(m+1)/eps5[m]))\\n\\n    # COMPUTING N AND p\\n    #  See II Section\\n    ctx.prec = wpfp + ctx.mag(t)+20\\n    a = ctx.sqrt(t/(2*ctx.pi))\\n    N = ctx.floor(a)\\n    p = 1-2*(a-N)\\n\\n    # now we get a rounded version of p\\n    # to the precision wpfp\\n    # this possibly is not necessary\\n    num=ctx.floor(p*(ctx.mpf('2')**wpfp))\\n    difference = p * (ctx.mpf('2')**wpfp)-num\\n    if (difference < 0.5):\\n        num = num\\n    else:\\n        num = num+1\\n    p = ctx.convert(num * (ctx.mpf('2')**(-wpfp)))\\n\\n    # COMPUTING THE COEFFICIENTS c[n] = cc[n]\\n    # We shall use the notation cc[n], since there is\\n    # a constant that is called c\\n    # See II Section 3.14\\n    # We compute the coefficients and also save then in a\\n    # cache.  The bulk of the computation is passed to\\n    # the function  coef()\\n    #\\n    #  eps6 is defined in II Section 3.13  equation (58)\\n    eps6 = ctx.power(ctx.convert(2*ctx.pi), J)/(ctx.gamma(J+1)*3*J)\\n\\n    #  Now we compute the coefficients\\n    cc = {}\\n    cont = {}\\n    cont, pipowers = coef(ctx, J, eps6)\\n    cc=cont.copy()   # we need a copy since we have to change his values.\\n    Fp={}            # this is the adequate locus of this\\n    for n in range(M, 3*L-2):\\n        Fp[n] = 0\\n    Fp={}\\n    ctx.prec = wpfp\\n    for m in range(0,M+1):\\n        sumP = 0\\n        for k in range(2*J-m-1,-1,-1):\\n            sumP = (sumP * p)+ cc[k]\\n        Fp[m] = sumP\\n        # preparation of the new coefficients\\n        for k in range(0,2*J-m-1):\\n            cc[k] = (k+1)* cc[k+1]\\n\\n    # COMPUTING THE NUMBERS  xd[u,n,k], yd[u,n,k]\\n    #  See II Section 3.17\\n    #\\n    #  First we compute the working precisions xwpd[k]\\n    #   Se II equation (92)\\n    xwpd={}\\n    d1 = max(6,ctx.mag(40*L*L))\\n    xd2 = 13+ctx.mag((1+abs(xsigma))*xA)-ctx.mag(xeps4)-1\\n    xconst = ctx.ln(8/(ctx.pi*ctx.pi*a*a*xB1*xB1)) /2\\n    for n in range(0,L):\\n        xd3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*xconst)+xd2\\n        xwpd[n]=max(xd3,d1)\\n\\n    # procedure of II Section 3.17\\n    ctx.prec = xwpd[1]+10\\n    xpsigma = 1-(2*xsigma)\\n    xd = {}\\n    xd[0,0,-2]=0; xd[0,0,-1]=0; xd[0,0,0]=1; xd[0,0,1]=0\\n    xd[0,-1,-2]=0; xd[0,-1,-1]=0; xd[0,-1,0]=1; xd[0,-1,1]=0\\n    for n in range(1,L):\\n        ctx.prec = xwpd[n]+10\\n        for k in range(0,3*n//2+1):\\n            m = 3*n-2*k\\n            if(m!=0):\\n                m1 = ctx.one/m\\n                c1= m1/4\\n                c2=(xpsigma*m1)/2\\n                c3=-(m+1)\\n                xd[0,n,k]=c3*xd[0,n-1,k-2]+c1*xd[0,n-1,k]+c2*xd[0,n-1,k-1]\\n            else:\\n                xd[0,n,k]=0\\n                for r in range(0,k):\\n                    add=xd[0,n,r]*(ctx.mpf('1.0')*ctx.fac(2*k-2*r)/ctx.fac(k-r))\\n                    xd[0,n,k] -= ((-1)**(k-r))*add\\n        xd[0,n,-2]=0; xd[0,n,-1]=0; xd[0,n,3*n//2+1]=0\\n    for mu in range(-2,der+1):\\n        for n in range(-2,L):\\n            for k in range(-3,max(1,3*n//2+2)):\\n                if( (mu<0)or (n<0) or(k<0)or (k>3*n//2)):\\n                    xd[mu,n,k] = 0\\n    for mu in range(1,der+1):\\n        for n in range(0,L):\\n            ctx.prec = xwpd[n]+10\\n            for k in range(0,3*n//2+1):\\n                aux=(2*mu-2)*xd[mu-2,n-2,k-3]+2*(xsigma+n-2)*xd[mu-1,n-2,k-3]\\n                xd[mu,n,k] = aux - xd[mu-1,n-1,k-1]\\n\\n    #  Now we compute the working precisions ywpd[k]\\n    #   Se II equation (92)\\n    ywpd={}\\n    d1 = max(6,ctx.mag(40*L*L))\\n    yd2 = 13+ctx.mag((1+abs(ysigma))*yA)-ctx.mag(yeps4)-1\\n    yconst = ctx.ln(8/(ctx.pi*ctx.pi*a*a*yB1*yB1)) /2\\n    for n in range(0,L):\\n        yd3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*yconst)+yd2\\n        ywpd[n]=max(yd3,d1)\\n\\n    # procedure of II Section 3.17\\n    ctx.prec = ywpd[1]+10\\n    ypsigma = 1-(2*ysigma)\\n    yd = {}\\n    yd[0,0,-2]=0; yd[0,0,-1]=0; yd[0,0,0]=1; yd[0,0,1]=0\\n    yd[0,-1,-2]=0; yd[0,-1,-1]=0; yd[0,-1,0]=1; yd[0,-1,1]=0\\n    for n in range(1,L):\\n        ctx.prec = ywpd[n]+10\\n        for k in range(0,3*n//2+1):\\n            m = 3*n-2*k\\n            if(m!=0):\\n                m1 = ctx.one/m\\n                c1= m1/4\\n                c2=(ypsigma*m1)/2\\n                c3=-(m+1)\\n                yd[0,n,k]=c3*yd[0,n-1,k-2]+c1*yd[0,n-1,k]+c2*yd[0,n-1,k-1]\\n            else:\\n                yd[0,n,k]=0\\n                for r in range(0,k):\\n                    add=yd[0,n,r]*(ctx.mpf('1.0')*ctx.fac(2*k-2*r)/ctx.fac(k-r))\\n                    yd[0,n,k] -= ((-1)**(k-r))*add\\n        yd[0,n,-2]=0; yd[0,n,-1]=0; yd[0,n,3*n//2+1]=0\\n\\n    for mu in range(-2,der+1):\\n        for n in range(-2,L):\\n            for k in range(-3,max(1,3*n//2+2)):\\n                if( (mu<0)or (n<0) or(k<0)or (k>3*n//2)):\\n                    yd[mu,n,k] = 0\\n    for mu in range(1,der+1):\\n        for n in range(0,L):\\n            ctx.prec = ywpd[n]+10\\n            for k in range(0,3*n//2+1):\\n                aux=(2*mu-2)*yd[mu-2,n-2,k-3]+2*(ysigma+n-2)*yd[mu-1,n-2,k-3]\\n                yd[mu,n,k] = aux - yd[mu-1,n-1,k-1]\\n\\n    # COMPUTING THE COEFFICIENTS xtcoef[k,l]\\n    #  See II Section 3.9\\n    #\\n    # computing the needed wp\\n    xwptcoef={}\\n    xwpterm={}\\n    ctx.prec = 15\\n    c1 = ctx.mag(40*(L+2))\\n    xc2 = ctx.mag(68*(L+2)*xA)\\n    xc4 = ctx.mag(xB1*a*math.sqrt(ctx.pi))-1\\n    for k in range(0,L):\\n        xc3 = xc2 - k*xc4+ctx.mag(ctx.fac(k+0.5))/2.\\n        xwptcoef[k] = (max(c1,xc3-ctx.mag(xeps4)+1)+1 +20)*1.5\\n        xwpterm[k] = (max(c1,ctx.mag(L+2)+xc3-ctx.mag(xeps3)+1)+1 +20)\\n    ywptcoef={}\\n    ywpterm={}\\n    ctx.prec = 15\\n    c1 = ctx.mag(40*(L+2))\\n    yc2 = ctx.mag(68*(L+2)*yA)\\n    yc4 = ctx.mag(yB1*a*math.sqrt(ctx.pi))-1\\n    for k in range(0,L):\\n        yc3 = yc2 - k*yc4+ctx.mag(ctx.fac(k+0.5))/2.\\n        ywptcoef[k] = ((max(c1,yc3-ctx.mag(yeps4)+1))+10)*1.5\\n        ywpterm[k] = (max(c1,ctx.mag(L+2)+yc3-ctx.mag(yeps3)+1)+1)+10\\n\\n    # check of power of pi\\n    # computing the fortcoef[mu,k,ell]\\n    xfortcoef={}\\n    for mu in range(0,der+1):\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                xfortcoef[mu,k,ell]=0\\n    for mu in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = xwptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                xfortcoef[mu,k,ell]=xd[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell]\\n                xfortcoef[mu,k,ell]=xfortcoef[mu,k,ell]/((2*ctx.j)**ell)\\n\\n    def trunc_a(t):\\n        wp = ctx.prec\\n        ctx.prec = wp + 2\\n        aa = ctx.sqrt(t/(2*ctx.pi))\\n        ctx.prec = wp\\n        return aa\\n\\n    # computing the tcoef[k,ell]\\n    xtcoef={}\\n    for mu in range(0,der+1):\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                xtcoef[mu,k,ell]=0\\n    ctx.prec = max(xwptcoef[0],ywptcoef[0])+3\\n    aa= trunc_a(t)\\n    la = -ctx.ln(aa)\\n\\n    for chi in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = xwptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                xtcoef[chi,k,ell] =0\\n                for mu in range(0, chi+1):\\n                    tcoefter=ctx.binomial(chi,mu)*ctx.power(la,mu)*xfortcoef[chi-mu,k,ell]\\n                    xtcoef[chi,k,ell] += tcoefter\\n\\n    # COMPUTING THE COEFFICIENTS ytcoef[k,l]\\n    #  See II Section 3.9\\n    #\\n    # computing the needed wp\\n    # check of power of pi\\n    # computing the fortcoef[mu,k,ell]\\n    yfortcoef={}\\n    for mu in range(0,der+1):\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                yfortcoef[mu,k,ell]=0\\n    for mu in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = ywptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                yfortcoef[mu,k,ell]=yd[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell]\\n                yfortcoef[mu,k,ell]=yfortcoef[mu,k,ell]/((2*ctx.j)**ell)\\n    # computing the tcoef[k,ell]\\n    ytcoef={}\\n    for chi in range(0,der+1):\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                ytcoef[chi,k,ell]=0\\n    for chi in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = ywptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                ytcoef[chi,k,ell] =0\\n                for mu in range(0, chi+1):\\n                    tcoefter=ctx.binomial(chi,mu)*ctx.power(la,mu)*yfortcoef[chi-mu,k,ell]\\n                    ytcoef[chi,k,ell] += tcoefter\\n\\n    # COMPUTING tv[k,ell]\\n    # See II Section 3.8\\n    #\\n    #  a has a good value\\n    ctx.prec = max(xwptcoef[0], ywptcoef[0])+2\\n    av = {}\\n    av[0] = 1\\n    av[1] = av[0]/a\\n\\n    ctx.prec = max(xwptcoef[0],ywptcoef[0])\\n    for k in range(2,L):\\n        av[k] = av[k-1] * av[1]\\n\\n    # Computing the quotients\\n    xtv = {}\\n    for chi in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = xwptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                xtv[chi,k,ell] = xtcoef[chi,k,ell]* av[k]\\n    # Computing the quotients\\n    ytv = {}\\n    for chi in range(0,der+1):\\n        for k in range(0,L):\\n            ctx.prec = ywptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                ytv[chi,k,ell] = ytcoef[chi,k,ell]* av[k]\\n\\n    # COMPUTING THE TERMS xterm[k]\\n    # See II Section 3.6\\n    xterm = {}\\n    for chi in range(0,der+1):\\n        for n in range(0,L):\\n            ctx.prec = xwpterm[n]\\n            te = 0\\n            for k in range(0, 3*n//2+1):\\n                te += xtv[chi,n,k]\\n            xterm[chi,n] = te\\n\\n    # COMPUTING THE TERMS yterm[k]\\n    # See II Section 3.6\\n    yterm = {}\\n    for chi in range(0,der+1):\\n        for n in range(0,L):\\n            ctx.prec = ywpterm[n]\\n            te = 0\\n            for k in range(0, 3*n//2+1):\\n                te += ytv[chi,n,k]\\n            yterm[chi,n] = te\\n\\n    # COMPUTING  rssum\\n    # See II Section 3.5\\n    xrssum={}\\n    ctx.prec=15\\n    xrsbound = math.sqrt(ctx.pi) * xc /(xb*a)\\n    ctx.prec=15\\n    xwprssum = ctx.mag(4.4*((L+3)**2)*xrsbound / xeps2)\\n    xwprssum = max(xwprssum, ctx.mag(10*(L+1)))\\n    ctx.prec = xwprssum\\n    for chi in range(0,der+1):\\n        xrssum[chi] = 0\\n        for k in range(1,L+1):\\n            xrssum[chi] += xterm[chi,L-k]\\n    yrssum={}\\n    ctx.prec=15\\n    yrsbound = math.sqrt(ctx.pi) * yc /(yb*a)\\n    ctx.prec=15\\n    ywprssum = ctx.mag(4.4*((L+3)**2)*yrsbound / yeps2)\\n    ywprssum = max(ywprssum, ctx.mag(10*(L+1)))\\n    ctx.prec = ywprssum\\n    for chi in range(0,der+1):\\n        yrssum[chi] = 0\\n        for k in range(1,L+1):\\n            yrssum[chi] += yterm[chi,L-k]\\n\\n    # COMPUTING S3\\n    # See II Section 3.19\\n    ctx.prec = 15\\n    A2 = 2**(max(ctx.mag(abs(xrssum[0])), ctx.mag(abs(yrssum[0]))))\\n    eps8 = eps/(3*A2)\\n    T = t *ctx.ln(t/(2*ctx.pi))\\n    xwps3 = 5 +  ctx.mag((1+(2/eps8)*ctx.power(a,-xsigma))*T)\\n    ywps3 = 5 +  ctx.mag((1+(2/eps8)*ctx.power(a,-ysigma))*T)\\n\\n    ctx.prec = max(xwps3, ywps3)\\n\\n    tpi = t/(2*ctx.pi)\\n    arg = (t/2)*ctx.ln(tpi)-(t/2)-ctx.pi/8\\n    U = ctx.expj(-arg)\\n    a = trunc_a(t)\\n    xasigma = ctx.power(a, -xsigma)\\n    yasigma = ctx.power(a, -ysigma)\\n    xS3 = ((-1)**(N-1)) * xasigma * U\\n    yS3 = ((-1)**(N-1)) * yasigma * U\\n\\n    # COMPUTING S1 the zetasum\\n    # See II Section 3.18\\n    ctx.prec = 15\\n    xwpsum =  4+ ctx.mag((N+ctx.power(N,1-xsigma))*ctx.ln(N) /eps1)\\n    ywpsum =  4+ ctx.mag((N+ctx.power(N,1-ysigma))*ctx.ln(N) /eps1)\\n    wpsum = max(xwpsum, ywpsum)\\n\\n    ctx.prec = wpsum +10\\n    '''\\n    # This can be improved\\n    xS1={}\\n    yS1={}\\n    for chi in range(0,der+1):\\n        xS1[chi] = 0\\n        yS1[chi] = 0\\n    for n in range(1,int(N)+1):\\n        ln = ctx.ln(n)\\n        xexpn = ctx.exp(-ln*(xsigma+ctx.j*t))\\n        yexpn = ctx.conj(1/(n*xexpn))\\n        for chi in range(0,der+1):\\n            pown = ctx.power(-ln, chi)\\n            xterm = pown*xexpn\\n            yterm = pown*yexpn\\n            xS1[chi] += xterm\\n            yS1[chi] += yterm\\n    '''\\n    xS1, yS1 = ctx._zetasum(s, 1, int(N)-1, range(0,der+1), True)\\n\\n    # END OF COMPUTATION of xrz, yrz\\n    #  See II Section 3.1\\n    ctx.prec = 15\\n    xabsS1 = abs(xS1[der])\\n    xabsS2 = abs(xrssum[der] * xS3)\\n    xwpend = max(6, wpinitial+ctx.mag(6*(3*xabsS1+7*xabsS2) ) )\\n\\n    ctx.prec = xwpend\\n    xrz={}\\n    for chi in range(0,der+1):\\n        xrz[chi] = xS1[chi]+xrssum[chi]*xS3\\n\\n    ctx.prec = 15\\n    yabsS1 = abs(yS1[der])\\n    yabsS2 = abs(yrssum[der] * yS3)\\n    ywpend = max(6, wpinitial+ctx.mag(6*(3*yabsS1+7*yabsS2) ) )\\n\\n    ctx.prec = ywpend\\n    yrz={}\\n    for chi in range(0,der+1):\\n        yrz[chi] = yS1[chi]+yrssum[chi]*yS3\\n        yrz[chi] = ctx.conj(yrz[chi])\\n    ctx.prec = wpinitial\\n    return xrz, yrz\\n\\ndef Rzeta_set(ctx, s, derivatives=[0]):\\n    r\\\"\\\"\\\"\\n    Computes several derivatives of the auxiliary function of Riemann `R(s)`.\\n\\n    **Definition**\\n\\n    The function is defined by\\n\\n    .. math ::\\n\\n        \\\\begin{equation}\\n        {\\\\mathop{\\\\mathcal R }\\\\nolimits}(s)=\\n        \\\\int_{0\\\\swarrow1}\\\\frac{x^{-s} e^{\\\\pi i x^2}}{e^{\\\\pi i x}-\\n        e^{-\\\\pi i x}}\\\\,dx\\n        \\\\end{equation}\\n\\n    To this function we apply the Riemann-Siegel expansion.\\n    \\\"\\\"\\\"\\n    der = max(derivatives)\\n    # First we take the value of ctx.prec\\n    # During the computation we will change ctx.prec, and finally we will\\n    # restaurate the initial value\\n    wpinitial = ctx.prec\\n    # Take the real and imaginary part of s\\n    t = ctx._im(s)\\n    sigma = ctx._re(s)\\n    # Now compute several parameter that appear on the program\\n    ctx.prec = 15\\n    a = ctx.sqrt(t/(2*ctx.pi))     #  Careful\\n    asigma = ctx.power(a, sigma)  #  Careful\\n    # We need a simple bound A1 < asigma  (see II Section 3.1 and 3.3)\\n    A1 = ctx.power(2, ctx.mag(asigma)-1)\\n    # We compute various epsilon's  (see II end of Section 3.1)\\n    eps = ctx.power(2, -wpinitial)\\n    eps1 = eps/6.\\n    eps2 = eps * A1/3.\\n    # COMPUTING SOME COEFFICIENTS THAT DEPENDS\\n    #               ON  sigma\\n    # constant b and c  (see I  Theorem 2 formula (26) )\\n    # coefficients A and B1  (see I Section 6.1 equation (50))\\n    # here we not need high precision\\n    ctx.prec = 15\\n    if sigma > 0:\\n        b = 2.\\n        c = math.pow(9,sigma)/4.44288\\n        # 4.44288 =(math.sqrt(2)*math.pi)\\n        A = math.pow(9,sigma)\\n        B1 = 1\\n    else:\\n        b = 2.25158  #  math.sqrt( (3-2* math.log(2))*math.pi )\\n        c = math.pow(2,-sigma)/4.44288\\n        A = math.pow(2,-sigma)\\n        B1 = 1.10789   #  = 2*sqrt(1-log(2))\\n    #  COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL\\n    #                         CORRECTION\\n    #  See II Section 3.2\\n    ctx.prec = 15\\n    L = 1\\n    while 3*c*ctx.gamma(L*0.5) * ctx.power(b*a,-L) >= eps2:\\n        L = L+1\\n    L = max(2,L)\\n    #  The number L has to satify some conditions.\\n    #  If not RS can not compute Rzeta(s) with the prescribed precision\\n    #  (see II, Section 3.2 condition (20)  ) and\\n    #  (II, Section 3.3 condition (22) ). Also we have added\\n    #  an additional technical  condition in Section 3.17 Proposition 17\\n    if ((3*L >= 2*a*a/25.) or (3*L+2+sigma<0) or (abs(sigma)> a/2.)):\\n        #print 'Error Riemann-Siegel can not compute with such precision'\\n        ctx.prec = wpinitial\\n        raise NotImplementedError(\\\"Riemann-Siegel can not compute with such precision\\\")\\n\\n    #  INITIALIZATION (CONTINUATION)\\n    #\\n    # eps3 is the constant defined on (II, Section 3.5 equation (27) )\\n    # each term of the RS correction must be computed with error <= eps3\\n    eps3 =  eps2/(4*L)\\n\\n    # eps4 is defined on (II Section 3.6  equation (30) )\\n    # each component of the formula (II Section 3.6 equation (29) )\\n    # must be computed with error <= eps4\\n    eps4 = eps3/(3*L)\\n\\n    # COMPUTING M.  NUMBER OF DERIVATIVES Fp[m] TO COMPUTE\\n    M = aux_M_Fp(ctx, A, eps4, a, B1, L)\\n    Fp = {}\\n    for n in range(M, 3*L-2):\\n        Fp[n] = 0\\n\\n    #  But I have not seen an instance of  M != 3*L-3\\n    #\\n    #  DETERMINATION OF  J  THE NUMBER OF TERMS NEEDED\\n    #            IN THE TAYLOR SERIES OF F.\\n    #  See II Section 3.11 equation (49))\\n    h1 = eps4/(632*A)\\n    h2 = ctx.pi*ctx.pi*B1*a *ctx.sqrt(3)*math.e*math.e\\n    h2 = h1 * ctx.power((h2/M**2),(M-1)/3) / M\\n    h3 = min(h1,h2)\\n    J=12\\n    jvalue = (2*ctx.pi)**J / ctx.gamma(J+1)\\n    while jvalue > h3:\\n        J = J+1\\n        jvalue = (2*ctx.pi)*jvalue/J\\n\\n    # COMPUTING eps5[m] for 1 <= m <= 21\\n    #  See II Section 10 equation (43)\\n    eps5={}\\n    foreps5 = math.pi*math.pi*B1*a\\n    for m in range(0,22):\\n        aux1 = math.pow(foreps5, m/3)/(316.*A)\\n        aux2 = ctx.gamma(m+1)/ctx.gamma(m/3.0+0.5)\\n        aux2 = math.sqrt(aux2)\\n        eps5[m] = aux1*aux2*eps4\\n\\n    # COMPUTING wpfp\\n    #  See II Section 3.13 equation (59)\\n    twenty = min(3*L-3, 21)+1\\n    aux = 6812*J\\n    wpfp = ctx.mag(44*J)\\n    for m in range(0, twenty):\\n        wpfp = max(wpfp, ctx.mag(aux*ctx.gamma(m+1)/eps5[m]))\\n    # COMPUTING N AND p\\n    #  See II Section\\n    ctx.prec = wpfp + ctx.mag(t) + 20\\n    a = ctx.sqrt(t/(2*ctx.pi))\\n    N = ctx.floor(a)\\n    p = 1-2*(a-N)\\n\\n    # now we get a rounded version of p to the precision wpfp\\n    # this possibly is not necessary\\n    num = ctx.floor(p*(ctx.mpf(2)**wpfp))\\n    difference = p * (ctx.mpf(2)**wpfp)-num\\n    if difference < 0.5:\\n        num = num\\n    else:\\n        num = num+1\\n    p = ctx.convert(num * (ctx.mpf(2)**(-wpfp)))\\n\\n    # COMPUTING THE COEFFICIENTS c[n] = cc[n]\\n    # We shall use the notation cc[n], since there is\\n    # a constant that is called c\\n    # See II Section 3.14\\n    # We compute the coefficients and also save then in a\\n    # cache.  The bulk of the computation is passed to\\n    # the function  coef()\\n    #\\n    #  eps6 is defined in II Section 3.13  equation (58)\\n    eps6 = ctx.power(2*ctx.pi, J)/(ctx.gamma(J+1)*3*J)\\n\\n    #  Now we compute the coefficients\\n    cc={}\\n    cont={}\\n    cont, pipowers = coef(ctx, J, eps6)\\n    cc = cont.copy()   # we need a copy since we have\\n    Fp={}\\n    for n in range(M, 3*L-2):\\n        Fp[n] = 0\\n    ctx.prec = wpfp\\n    for m in range(0,M+1):\\n        sumP = 0\\n        for k in range(2*J-m-1,-1,-1):\\n            sumP = (sumP * p) + cc[k]\\n        Fp[m] = sumP\\n        # preparation of the new coefficients\\n        for k in range(0, 2*J-m-1):\\n            cc[k] = (k+1) * cc[k+1]\\n\\n    # COMPUTING THE NUMBERS  d[n,k]\\n    #  See II Section 3.17\\n\\n    #  First we compute the working precisions wpd[k]\\n    #   Se II equation (92)\\n    wpd = {}\\n    d1 = max(6, ctx.mag(40*L*L))\\n    d2 = 13+ctx.mag((1+abs(sigma))*A)-ctx.mag(eps4)-1\\n    const = ctx.ln(8/(ctx.pi*ctx.pi*a*a*B1*B1)) /2\\n    for n in range(0,L):\\n        d3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*const)+d2\\n        wpd[n] = max(d3,d1)\\n\\n    # procedure of II Section 3.17\\n    ctx.prec = wpd[1]+10\\n    psigma = 1-(2*sigma)\\n    d = {}\\n    d[0,0,-2]=0; d[0,0,-1]=0; d[0,0,0]=1; d[0,0,1]=0\\n    d[0,-1,-2]=0; d[0,-1,-1]=0; d[0,-1,0]=1; d[0,-1,1]=0\\n    for n in range(1,L):\\n        ctx.prec = wpd[n]+10\\n        for k in range(0,3*n//2+1):\\n            m = 3*n-2*k\\n            if (m!=0):\\n                m1 = ctx.one/m\\n                c1 = m1/4\\n                c2 = (psigma*m1)/2\\n                c3 = -(m+1)\\n                d[0,n,k] = c3*d[0,n-1,k-2]+c1*d[0,n-1,k]+c2*d[0,n-1,k-1]\\n            else:\\n                d[0,n,k]=0\\n                for r in range(0,k):\\n                    add = d[0,n,r]*(ctx.one*ctx.fac(2*k-2*r)/ctx.fac(k-r))\\n                    d[0,n,k] -= ((-1)**(k-r))*add\\n        d[0,n,-2]=0; d[0,n,-1]=0; d[0,n,3*n//2+1]=0\\n\\n    for mu in range(-2,der+1):\\n        for n in range(-2,L):\\n            for k in range(-3,max(1,3*n//2+2)):\\n                if ((mu<0)or (n<0) or(k<0)or (k>3*n//2)):\\n                    d[mu,n,k] = 0\\n\\n    for mu in range(1,der+1):\\n        for n in range(0,L):\\n            ctx.prec = wpd[n]+10\\n            for k in range(0,3*n//2+1):\\n                aux=(2*mu-2)*d[mu-2,n-2,k-3]+2*(sigma+n-2)*d[mu-1,n-2,k-3]\\n                d[mu,n,k] = aux - d[mu-1,n-1,k-1]\\n\\n    # COMPUTING THE COEFFICIENTS t[k,l]\\n    #  See II Section 3.9\\n    #\\n    # computing the needed wp\\n    wptcoef = {}\\n    wpterm = {}\\n    ctx.prec = 15\\n    c1 = ctx.mag(40*(L+2))\\n    c2 = ctx.mag(68*(L+2)*A)\\n    c4 = ctx.mag(B1*a*math.sqrt(ctx.pi))-1\\n    for k in range(0,L):\\n        c3 = c2 - k*c4+ctx.mag(ctx.fac(k+0.5))/2.\\n        wptcoef[k] = max(c1,c3-ctx.mag(eps4)+1)+1 +10\\n        wpterm[k] = max(c1,ctx.mag(L+2)+c3-ctx.mag(eps3)+1)+1 +10\\n\\n    # check of power of pi\\n\\n    # computing the fortcoef[mu,k,ell]\\n    fortcoef={}\\n    for mu in derivatives:\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                fortcoef[mu,k,ell]=0\\n\\n    for mu in derivatives:\\n        for k in range(0,L):\\n            ctx.prec = wptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                fortcoef[mu,k,ell]=d[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell]\\n                fortcoef[mu,k,ell]=fortcoef[mu,k,ell]/((2*ctx.j)**ell)\\n\\n    def trunc_a(t):\\n        wp = ctx.prec\\n        ctx.prec = wp + 2\\n        aa = ctx.sqrt(t/(2*ctx.pi))\\n        ctx.prec = wp\\n        return aa\\n\\n    # computing the tcoef[chi,k,ell]\\n    tcoef={}\\n    for chi in derivatives:\\n        for k in range(0,L):\\n            for ell in range(-2,3*k//2+1):\\n                tcoef[chi,k,ell]=0\\n    ctx.prec = wptcoef[0]+3\\n    aa = trunc_a(t)\\n    la = -ctx.ln(aa)\\n\\n    for chi in derivatives:\\n        for k in range(0,L):\\n            ctx.prec = wptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                tcoef[chi,k,ell] = 0\\n                for mu in range(0, chi+1):\\n                    tcoefter = ctx.binomial(chi,mu) * la**mu * \\\\\\n                        fortcoef[chi-mu,k,ell]\\n                    tcoef[chi,k,ell] += tcoefter\\n\\n    # COMPUTING tv[k,ell]\\n    # See II Section 3.8\\n\\n    # Computing the powers av[k] = a**(-k)\\n    ctx.prec = wptcoef[0] + 2\\n\\n    # a has a good value of a.\\n    # See II Section 3.6\\n    av = {}\\n    av[0] = 1\\n    av[1] = av[0]/a\\n\\n    ctx.prec = wptcoef[0]\\n    for k in range(2,L):\\n        av[k] = av[k-1] * av[1]\\n\\n    # Computing the quotients\\n    tv = {}\\n    for chi in derivatives:\\n        for k in range(0,L):\\n            ctx.prec = wptcoef[k]\\n            for ell in range(0,3*k//2+1):\\n                tv[chi,k,ell] = tcoef[chi,k,ell]* av[k]\\n\\n    # COMPUTING THE TERMS term[k]\\n    # See II Section 3.6\\n    term = {}\\n    for chi in derivatives:\\n        for n in range(0,L):\\n            ctx.prec = wpterm[n]\\n            te = 0\\n            for k in range(0, 3*n//2+1):\\n                te += tv[chi,n,k]\\n            term[chi,n] = te\\n\\n    # COMPUTING  rssum\\n    # See II Section 3.5\\n    rssum={}\\n    ctx.prec=15\\n    rsbound = math.sqrt(ctx.pi) * c /(b*a)\\n    ctx.prec=15\\n    wprssum = ctx.mag(4.4*((L+3)**2)*rsbound / eps2)\\n    wprssum = max(wprssum, ctx.mag(10*(L+1)))\\n    ctx.prec = wprssum\\n    for chi in derivatives:\\n        rssum[chi] = 0\\n        for k in range(1,L+1):\\n            rssum[chi] += term[chi,L-k]\\n\\n    # COMPUTING S3\\n    # See II Section 3.19\\n    ctx.prec = 15\\n    A2 = 2**(ctx.mag(rssum[0]))\\n    eps8 = eps/(3* A2)\\n    T = t * ctx.ln(t/(2*ctx.pi))\\n    wps3 = 5 + ctx.mag((1+(2/eps8)*ctx.power(a,-sigma))*T)\\n\\n    ctx.prec = wps3\\n    tpi = t/(2*ctx.pi)\\n    arg = (t/2)*ctx.ln(tpi)-(t/2)-ctx.pi/8\\n    U = ctx.expj(-arg)\\n    a = trunc_a(t)\\n    asigma = ctx.power(a, -sigma)\\n    S3 = ((-1)**(N-1)) * asigma * U\\n\\n    # COMPUTING S1 the zetasum\\n    # See II Section 3.18\\n    ctx.prec = 15\\n    wpsum = 4 + ctx.mag((N+ctx.power(N,1-sigma))*ctx.ln(N)/eps1)\\n\\n    ctx.prec = wpsum + 10\\n    '''\\n    # This can be improved\\n    S1 = {}\\n    for chi in derivatives:\\n        S1[chi] = 0\\n    for n in range(1,int(N)+1):\\n        ln = ctx.ln(n)\\n        expn = ctx.exp(-ln*(sigma+ctx.j*t))\\n        for chi in derivatives:\\n            term = ctx.power(-ln, chi)*expn\\n            S1[chi] += term\\n    '''\\n    S1 = ctx._zetasum(s, 1, int(N)-1, derivatives)[0]\\n\\n    # END OF COMPUTATION\\n    #  See II Section 3.1\\n    ctx.prec = 15\\n    absS1 = abs(S1[der])\\n    absS2 = abs(rssum[der] * S3)\\n    wpend = max(6, wpinitial + ctx.mag(6*(3*absS1+7*absS2)))\\n    ctx.prec = wpend\\n    rz = {}\\n    for chi in derivatives:\\n        rz[chi] = S1[chi]+rssum[chi]*S3\\n    ctx.prec = wpinitial\\n    return rz\\n\\n\\ndef z_half(ctx,t,der=0):\\n    r\\\"\\\"\\\"\\n    z_half(t,der=0) Computes Z^(der)(t)\\n    \\\"\\\"\\\"\\n    s=ctx.mpf('0.5')+ctx.j*t\\n    wpinitial = ctx.prec\\n    ctx.prec = 15\\n    tt = t/(2*ctx.pi)\\n    wptheta = wpinitial +1 + ctx.mag(3*(tt**1.5)*ctx.ln(tt))\\n    wpz = wpinitial + 1 + ctx.mag(12*tt*ctx.ln(tt))\\n    ctx.prec = wptheta\\n    theta = ctx.siegeltheta(t)\\n    ctx.prec = wpz\\n    rz = Rzeta_set(ctx,s, range(der+1))\\n    if der > 0: ps1 = ctx._re(ctx.psi(0,s/2)/2 - ctx.ln(ctx.pi)/2)\\n    if der > 1: ps2 = ctx._re(ctx.j*ctx.psi(1,s/2)/4)\\n    if der > 2: ps3 = ctx._re(-ctx.psi(2,s/2)/8)\\n    if der > 3: ps4 = ctx._re(-ctx.j*ctx.psi(3,s/2)/16)\\n    exptheta = ctx.expj(theta)\\n    if der == 0:\\n        z = 2*exptheta*rz[0]\\n    if der == 1:\\n        zf = 2j*exptheta\\n        z = zf*(ps1*rz[0]+rz[1])\\n    if der == 2:\\n        zf = 2 * exptheta\\n        z = -zf*(2*rz[1]*ps1+rz[0]*ps1**2+rz[2]-ctx.j*rz[0]*ps2)\\n    if der == 3:\\n        zf = -2j*exptheta\\n        z = 3*rz[1]*ps1**2+rz[0]*ps1**3+3*ps1*rz[2]\\n        z = zf*(z-3j*rz[1]*ps2-3j*rz[0]*ps1*ps2+rz[3]-rz[0]*ps3)\\n    if der == 4:\\n        zf = 2*exptheta\\n        z = 4*rz[1]*ps1**3+rz[0]*ps1**4+6*ps1**2*rz[2]\\n        z = z-12j*rz[1]*ps1*ps2-6j*rz[0]*ps1**2*ps2-6j*rz[2]*ps2-3*rz[0]*ps2*ps2\\n        z = z + 4*ps1*rz[3]-4*rz[1]*ps3-4*rz[0]*ps1*ps3+rz[4]+ctx.j*rz[0]*ps4\\n        z = zf*z\\n    ctx.prec = wpinitial\\n    return ctx._re(z)\\n\\ndef zeta_half(ctx, s, k=0):\\n    \\\"\\\"\\\"\\n    zeta_half(s,k=0) Computes zeta^(k)(s) when Re s = 0.5\\n    \\\"\\\"\\\"\\n    wpinitial = ctx.prec\\n    sigma = ctx._re(s)\\n    t = ctx._im(s)\\n    #--- compute wptheta, wpR, wpbasic ---\\n    ctx.prec = 53\\n    #  X see II Section 3.21 (109) and (110)\\n    if sigma > 0:\\n        X = ctx.sqrt(abs(s))\\n    else:\\n        X = (2*ctx.pi)**(sigma-1) * abs(1-s)**(0.5-sigma)\\n    # M1  see II Section 3.21 (111) and (112)\\n    if sigma > 0:\\n        M1 = 2*ctx.sqrt(t/(2*ctx.pi))\\n    else:\\n        M1 = 4 * t * X\\n    # T  see II Section 3.21 (113)\\n    abst = abs(0.5-s)\\n    T = 2* abst*math.log(abst)\\n    # computing wpbasic, wptheta, wpR  see II Section 3.21\\n    wpbasic = max(6,3+ctx.mag(t))\\n    wpbasic2 = 2+ctx.mag(2.12*M1+21.2*M1*X+1.3*M1*X*T)+wpinitial+1\\n    wpbasic = max(wpbasic, wpbasic2)\\n    wptheta = max(4, 3+ctx.mag(2.7*M1*X)+wpinitial+1)\\n    wpR = 3+ctx.mag(1.1+2*X)+wpinitial+1\\n    ctx.prec = wptheta\\n    theta = ctx.siegeltheta(t-ctx.j*(sigma-ctx.mpf('0.5')))\\n    if k > 0: ps1 = (ctx._re(ctx.psi(0,s/2)))/2 - ctx.ln(ctx.pi)/2\\n    if k > 1: ps2 = -(ctx._im(ctx.psi(1,s/2)))/4\\n    if k > 2: ps3 = -(ctx._re(ctx.psi(2,s/2)))/8\\n    if k > 3: ps4 = (ctx._im(ctx.psi(3,s/2)))/16\\n    ctx.prec = wpR\\n    xrz = Rzeta_set(ctx,s,range(k+1))\\n    yrz={}\\n    for chi in range(0,k+1):\\n        yrz[chi] = ctx.conj(xrz[chi])\\n    ctx.prec = wpbasic\\n    exptheta = ctx.expj(-2*theta)\\n    if k==0:\\n        zv = xrz[0]+exptheta*yrz[0]\\n    if k==1:\\n        zv1 = -yrz[1] - 2*yrz[0]*ps1\\n        zv = xrz[1] + exptheta*zv1\\n    if k==2:\\n        zv1 = 4*yrz[1]*ps1+4*yrz[0]*(ps1**2)+yrz[2]+2j*yrz[0]*ps2\\n        zv = xrz[2]+exptheta*zv1\\n    if k==3:\\n        zv1 = -12*yrz[1]*ps1**2-8*yrz[0]*ps1**3-6*yrz[2]*ps1-6j*yrz[1]*ps2\\n        zv1 = zv1 - 12j*yrz[0]*ps1*ps2-yrz[3]+2*yrz[0]*ps3\\n        zv = xrz[3]+exptheta*zv1\\n    if k == 4:\\n        zv1 = 32*yrz[1]*ps1**3 +16*yrz[0]*ps1**4+24*yrz[2]*ps1**2\\n        zv1 = zv1 +48j*yrz[1]*ps1*ps2+48j*yrz[0]*(ps1**2)*ps2\\n        zv1 = zv1+12j*yrz[2]*ps2-12*yrz[0]*ps2**2+8*yrz[3]*ps1-8*yrz[1]*ps3\\n        zv1 = zv1-16*yrz[0]*ps1*ps3+yrz[4]-2j*yrz[0]*ps4\\n        zv = xrz[4]+exptheta*zv1\\n    ctx.prec = wpinitial\\n    return zv\\n\\ndef zeta_offline(ctx, s, k=0):\\n    \\\"\\\"\\\"\\n    Computes zeta^(k)(s) off the line\\n    \\\"\\\"\\\"\\n    wpinitial = ctx.prec\\n    sigma = ctx._re(s)\\n    t = ctx._im(s)\\n    #--- compute wptheta, wpR, wpbasic ---\\n    ctx.prec = 53\\n    #  X see II Section 3.21 (109) and (110)\\n    if sigma > 0:\\n        X = ctx.power(abs(s), 0.5)\\n    else:\\n        X = ctx.power(2*ctx.pi, sigma-1)*ctx.power(abs(1-s),0.5-sigma)\\n    # M1  see II Section 3.21 (111) and (112)\\n    if (sigma > 0):\\n        M1 = 2*ctx.sqrt(t/(2*ctx.pi))\\n    else:\\n        M1 = 4 * t * X\\n    # M2  see II Section 3.21 (111) and (112)\\n    if (1-sigma > 0):\\n        M2 = 2*ctx.sqrt(t/(2*ctx.pi))\\n    else:\\n        M2 = 4*t*ctx.power(2*ctx.pi, -sigma)*ctx.power(abs(s),sigma-0.5)\\n    # T  see II Section 3.21 (113)\\n    abst = abs(0.5-s)\\n    T = 2* abst*math.log(abst)\\n    # computing wpbasic, wptheta, wpR  see II Section 3.21\\n    wpbasic = max(6,3+ctx.mag(t))\\n    wpbasic2 = 2+ctx.mag(2.12*M1+21.2*M2*X+1.3*M2*X*T)+wpinitial+1\\n    wpbasic = max(wpbasic, wpbasic2)\\n    wptheta = max(4, 3+ctx.mag(2.7*M2*X)+wpinitial+1)\\n    wpR = 3+ctx.mag(1.1+2*X)+wpinitial+1\\n    ctx.prec = wptheta\\n    theta = ctx.siegeltheta(t-ctx.j*(sigma-ctx.mpf('0.5')))\\n    s1 = s\\n    s2 = ctx.conj(1-s1)\\n    ctx.prec = wpR\\n    xrz, yrz = Rzeta_simul(ctx, s, k)\\n    if k > 0: ps1 = (ctx.psi(0,s1/2)+ctx.psi(0,(1-s1)/2))/4 - ctx.ln(ctx.pi)/2\\n    if k > 1: ps2 = ctx.j*(ctx.psi(1,s1/2)-ctx.psi(1,(1-s1)/2))/8\\n    if k > 2: ps3 = -(ctx.psi(2,s1/2)+ctx.psi(2,(1-s1)/2))/16\\n    if k > 3: ps4 = -ctx.j*(ctx.psi(3,s1/2)-ctx.psi(3,(1-s1)/2))/32\\n    ctx.prec = wpbasic\\n    exptheta = ctx.expj(-2*theta)\\n    if k == 0:\\n        zv = xrz[0]+exptheta*yrz[0]\\n    if k == 1:\\n        zv1 = -yrz[1]-2*yrz[0]*ps1\\n        zv = xrz[1]+exptheta*zv1\\n    if k == 2:\\n        zv1 = 4*yrz[1]*ps1+4*yrz[0]*(ps1**2) +yrz[2]+2j*yrz[0]*ps2\\n        zv = xrz[2]+exptheta*zv1\\n    if k == 3:\\n        zv1 = -12*yrz[1]*ps1**2 -8*yrz[0]*ps1**3-6*yrz[2]*ps1-6j*yrz[1]*ps2\\n        zv1 = zv1 - 12j*yrz[0]*ps1*ps2-yrz[3]+2*yrz[0]*ps3\\n        zv = xrz[3]+exptheta*zv1\\n    if k == 4:\\n        zv1 = 32*yrz[1]*ps1**3 +16*yrz[0]*ps1**4+24*yrz[2]*ps1**2\\n        zv1 = zv1 +48j*yrz[1]*ps1*ps2+48j*yrz[0]*(ps1**2)*ps2\\n        zv1 = zv1+12j*yrz[2]*ps2-12*yrz[0]*ps2**2+8*yrz[3]*ps1-8*yrz[1]*ps3\\n        zv1 = zv1-16*yrz[0]*ps1*ps3+yrz[4]-2j*yrz[0]*ps4\\n        zv = xrz[4]+exptheta*zv1\\n    ctx.prec = wpinitial\\n    return zv\\n\\ndef z_offline(ctx, w, k=0):\\n    r\\\"\\\"\\\"\\n    Computes Z(w) and its derivatives off the line\\n    \\\"\\\"\\\"\\n    s = ctx.mpf('0.5')+ctx.j*w\\n    s1 = s\\n    s2 = ctx.conj(1-s1)\\n    wpinitial = ctx.prec\\n    ctx.prec = 35\\n    #  X see II Section 3.21 (109) and (110)\\n    # M1  see II Section 3.21 (111) and (112)\\n    if (ctx._re(s1) >= 0):\\n        M1 = 2*ctx.sqrt(ctx._im(s1)/(2 * ctx.pi))\\n        X = ctx.sqrt(abs(s1))\\n    else:\\n        X = (2*ctx.pi)**(ctx._re(s1)-1) * abs(1-s1)**(0.5-ctx._re(s1))\\n        M1 = 4 * ctx._im(s1)*X\\n    # M2  see II Section 3.21 (111) and (112)\\n    if (ctx._re(s2) >= 0):\\n        M2 = 2*ctx.sqrt(ctx._im(s2)/(2 * ctx.pi))\\n    else:\\n        M2 = 4 * ctx._im(s2)*(2*ctx.pi)**(ctx._re(s2)-1)*abs(1-s2)**(0.5-ctx._re(s2))\\n    # T  see II Section 3.21  Prop. 27\\n    T = 2*abs(ctx.siegeltheta(w))\\n    # defining some precisions\\n    # see II Section 3.22 (115), (116), (117)\\n    aux1 = ctx.sqrt(X)\\n    aux2 = aux1*(M1+M2)\\n    aux3 = 3 +wpinitial\\n    wpbasic = max(6, 3+ctx.mag(T), ctx.mag(aux2*(26+2*T))+aux3)\\n    wptheta = max(4,ctx.mag(2.04*aux2)+aux3)\\n    wpR = ctx.mag(4*aux1)+aux3\\n    # now the computations\\n    ctx.prec = wptheta\\n    theta = ctx.siegeltheta(w)\\n    ctx.prec = wpR\\n    xrz, yrz = Rzeta_simul(ctx,s,k)\\n    pta = 0.25 + 0.5j*w\\n    ptb = 0.25 - 0.5j*w\\n    if k > 0: ps1 = 0.25*(ctx.psi(0,pta)+ctx.psi(0,ptb)) - ctx.ln(ctx.pi)/2\\n    if k > 1: ps2 = (1j/8)*(ctx.psi(1,pta)-ctx.psi(1,ptb))\\n    if k > 2: ps3 = (-1./16)*(ctx.psi(2,pta)+ctx.psi(2,ptb))\\n    if k > 3: ps4 = (-1j/32)*(ctx.psi(3,pta)-ctx.psi(3,ptb))\\n    ctx.prec = wpbasic\\n    exptheta = ctx.expj(theta)\\n    if k == 0:\\n        zv = exptheta*xrz[0]+yrz[0]/exptheta\\n    j = ctx.j\\n    if k == 1:\\n        zv = j*exptheta*(xrz[1]+xrz[0]*ps1)-j*(yrz[1]+yrz[0]*ps1)/exptheta\\n    if k == 2:\\n        zv = exptheta*(-2*xrz[1]*ps1-xrz[0]*ps1**2-xrz[2]+j*xrz[0]*ps2)\\n        zv =zv + (-2*yrz[1]*ps1-yrz[0]*ps1**2-yrz[2]-j*yrz[0]*ps2)/exptheta\\n    if k == 3:\\n        zv1 = -3*xrz[1]*ps1**2-xrz[0]*ps1**3-3*xrz[2]*ps1+j*3*xrz[1]*ps2\\n        zv1 = (zv1+ 3j*xrz[0]*ps1*ps2-xrz[3]+xrz[0]*ps3)*j*exptheta\\n        zv2 = 3*yrz[1]*ps1**2+yrz[0]*ps1**3+3*yrz[2]*ps1+j*3*yrz[1]*ps2\\n        zv2 = j*(zv2 + 3j*yrz[0]*ps1*ps2+ yrz[3]-yrz[0]*ps3)/exptheta\\n        zv = zv1+zv2\\n    if k == 4:\\n        zv1 = 4*xrz[1]*ps1**3+xrz[0]*ps1**4 + 6*xrz[2]*ps1**2\\n        zv1 = zv1-12j*xrz[1]*ps1*ps2-6j*xrz[0]*ps1**2*ps2-6j*xrz[2]*ps2\\n        zv1 = zv1-3*xrz[0]*ps2*ps2+4*xrz[3]*ps1-4*xrz[1]*ps3-4*xrz[0]*ps1*ps3\\n        zv1 = zv1+xrz[4]+j*xrz[0]*ps4\\n        zv2 = 4*yrz[1]*ps1**3+yrz[0]*ps1**4 + 6*yrz[2]*ps1**2\\n        zv2 = zv2+12j*yrz[1]*ps1*ps2+6j*yrz[0]*ps1**2*ps2+6j*yrz[2]*ps2\\n        zv2 = zv2-3*yrz[0]*ps2*ps2+4*yrz[3]*ps1-4*yrz[1]*ps3-4*yrz[0]*ps1*ps3\\n        zv2 = zv2+yrz[4]-j*yrz[0]*ps4\\n        zv = exptheta*zv1+zv2/exptheta\\n    ctx.prec = wpinitial\\n    return zv\\n\\n@defun\\ndef rs_zeta(ctx, s, derivative=0, **kwargs):\\n    if derivative > 4:\\n        raise NotImplementedError\\n    s = ctx.convert(s)\\n    re = ctx._re(s); im = ctx._im(s)\\n    if im < 0:\\n        z = ctx.conj(ctx.rs_zeta(ctx.conj(s), derivative))\\n        return z\\n    critical_line = (re == 0.5)\\n    if critical_line:\\n        return zeta_half(ctx, s, derivative)\\n    else:\\n        return zeta_offline(ctx, s, derivative)\\n\\n@defun\\ndef rs_z(ctx, w, derivative=0):\\n    w = ctx.convert(w)\\n    re = ctx._re(w); im = ctx._im(w)\\n    if re < 0:\\n        return rs_z(ctx, -w, derivative)\\n    critical_line = (im == 0)\\n    if critical_line :\\n        return z_half(ctx, w, derivative)\\n    else:\\n        return z_offline(ctx, w, derivative)\\n\\n\\nr\\\"\\\"\\\"\\nElliptic functions historically comprise the elliptic integrals\\nand their inverses, and originate from the problem of computing the\\narc length of an ellipse. From a more modern point of view,\\nan elliptic function is defined as a doubly periodic function, i.e.\\na function which satisfies\\n\\n.. math ::\\n\\n    f(z + 2 \\\\omega_1) = f(z + 2 \\\\omega_2) = f(z)\\n\\nfor some half-periods `\\\\omega_1, \\\\omega_2` with\\n`\\\\mathrm{Im}[\\\\omega_1 / \\\\omega_2] > 0`. The canonical elliptic\\nfunctions are the Jacobi elliptic functions. More broadly, this section\\nincludes  quasi-doubly periodic functions (such as the Jacobi theta\\nfunctions) and other functions useful in the study of elliptic functions.\\n\\nMany different conventions for the arguments of\\nelliptic functions are in use. It is even standard to use\\ndifferent parameterizations for different functions in the same\\ntext or software (and mpmath is no exception).\\nThe usual parameters are the elliptic nome `q`, which usually\\nmust satisfy `|q| < 1`; the elliptic parameter `m` (an arbitrary\\ncomplex number); the elliptic modulus `k` (an arbitrary complex\\nnumber); and the half-period ratio `\\\\tau`, which usually must\\nsatisfy `\\\\mathrm{Im}[\\\\tau] > 0`.\\nThese quantities can be expressed in terms of each other\\nusing the following relations:\\n\\n.. math ::\\n\\n    m = k^2\\n\\n.. math ::\\n\\n    \\\\tau = i \\\\frac{K(1-m)}{K(m)}\\n\\n.. math ::\\n\\n    q = e^{i \\\\pi \\\\tau}\\n\\n.. math ::\\n\\n    k = \\\\frac{\\\\vartheta_2^2(q)}{\\\\vartheta_3^2(q)}\\n\\nIn addition, an alternative definition is used for the nome in\\nnumber theory, which we here denote by q-bar:\\n\\n.. math ::\\n\\n    \\\\bar{q} = q^2 = e^{2 i \\\\pi \\\\tau}\\n\\nFor convenience, mpmath provides functions to convert\\nbetween the various parameters (:func:`~mpmath.qfrom`, :func:`~mpmath.mfrom`,\\n:func:`~mpmath.kfrom`, :func:`~mpmath.taufrom`, :func:`~mpmath.qbarfrom`).\\n\\n**References**\\n\\n1. [AbramowitzStegun]_\\n\\n2. [WhittakerWatson]_\\n\\n\\\"\\\"\\\"\\n\\nfrom .functions import defun, defun_wrapped\\n\\n@defun_wrapped\\ndef eta(ctx, tau):\\n    r\\\"\\\"\\\"\\n    Returns the Dedekind eta function of tau in the upper half-plane.\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> eta(1j); gamma(0.25) / (2*pi**0.75)\\n        (0.7682254223260566590025942 + 0.0j)\\n        0.7682254223260566590025942\\n        >>> tau = sqrt(2) + sqrt(5)*1j\\n        >>> eta(-1/tau); sqrt(-1j*tau) * eta(tau)\\n        (0.9022859908439376463573294 + 0.07985093673948098408048575j)\\n        (0.9022859908439376463573295 + 0.07985093673948098408048575j)\\n        >>> eta(tau+1); exp(pi*1j/12) * eta(tau)\\n        (0.4493066139717553786223114 + 0.3290014793877986663915939j)\\n        (0.4493066139717553786223114 + 0.3290014793877986663915939j)\\n        >>> f = lambda z: diff(eta, z) / eta(z)\\n        >>> chop(36*diff(f,tau)**2 - 24*diff(f,tau,2)*f(tau) + diff(f,tau,3))\\n        0.0\\n\\n    \\\"\\\"\\\"\\n    if ctx.im(tau) <= 0.0:\\n        raise ValueError(\\\"eta is only defined in the upper half-plane\\\")\\n    q = ctx.expjpi(tau/12)\\n    return q * ctx.qp(q**24)\\n\\ndef nome(ctx, m):\\n    m = ctx.convert(m)\\n    if not m:\\n        return m\\n    if m == ctx.one:\\n        return m\\n    if ctx.isnan(m):\\n        return m\\n    if ctx.isinf(m):\\n        if m == ctx.ninf:\\n            return type(m)(-1)\\n        else:\\n            return ctx.mpc(-1)\\n    a = ctx.ellipk(ctx.one-m)\\n    b = ctx.ellipk(m)\\n    v = ctx.exp(-ctx.pi*a/b)\\n    if not ctx._im(m) and ctx._re(m) < 1:\\n        if ctx._is_real_type(m):\\n            return v.real\\n        else:\\n            return v.real + 0j\\n    elif m == 2:\\n        v = ctx.mpc(0, v.imag)\\n    return v\\n\\n@defun_wrapped\\ndef qfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):\\n    r\\\"\\\"\\\"\\n    Returns the elliptic nome `q`, given any of `q, m, k, \\\\tau, \\\\bar{q}`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qfrom(q=0.25)\\n        0.25\\n        >>> qfrom(m=mfrom(q=0.25))\\n        0.25\\n        >>> qfrom(k=kfrom(q=0.25))\\n        0.25\\n        >>> qfrom(tau=taufrom(q=0.25))\\n        (0.25 + 0.0j)\\n        >>> qfrom(qbar=qbarfrom(q=0.25))\\n        0.25\\n\\n    \\\"\\\"\\\"\\n    if q is not None:\\n        return ctx.convert(q)\\n    if m is not None:\\n        return nome(ctx, m)\\n    if k is not None:\\n        return nome(ctx, ctx.convert(k)**2)\\n    if tau is not None:\\n        return ctx.expjpi(tau)\\n    if qbar is not None:\\n        return ctx.sqrt(qbar)\\n\\n@defun_wrapped\\ndef qbarfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):\\n    r\\\"\\\"\\\"\\n    Returns the number-theoretic nome `\\\\bar q`, given any of\\n    `q, m, k, \\\\tau, \\\\bar{q}`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> qbarfrom(qbar=0.25)\\n        0.25\\n        >>> qbarfrom(q=qfrom(qbar=0.25))\\n        0.25\\n        >>> qbarfrom(m=extraprec(20)(mfrom)(qbar=0.25))  # ill-conditioned\\n        0.25\\n        >>> qbarfrom(k=extraprec(20)(kfrom)(qbar=0.25))  # ill-conditioned\\n        0.25\\n        >>> qbarfrom(tau=taufrom(qbar=0.25))\\n        (0.25 + 0.0j)\\n\\n    \\\"\\\"\\\"\\n    if qbar is not None:\\n        return ctx.convert(qbar)\\n    if q is not None:\\n        return ctx.convert(q) ** 2\\n    if m is not None:\\n        return nome(ctx, m) ** 2\\n    if k is not None:\\n        return nome(ctx, ctx.convert(k)**2) ** 2\\n    if tau is not None:\\n        return ctx.expjpi(2*tau)\\n\\n@defun_wrapped\\ndef taufrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):\\n    r\\\"\\\"\\\"\\n    Returns the elliptic half-period ratio `\\\\tau`, given any of\\n    `q, m, k, \\\\tau, \\\\bar{q}`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> taufrom(tau=0.5j)\\n        (0.0 + 0.5j)\\n        >>> taufrom(q=qfrom(tau=0.5j))\\n        (0.0 + 0.5j)\\n        >>> taufrom(m=mfrom(tau=0.5j))\\n        (0.0 + 0.5j)\\n        >>> taufrom(k=kfrom(tau=0.5j))\\n        (0.0 + 0.5j)\\n        >>> taufrom(qbar=qbarfrom(tau=0.5j))\\n        (0.0 + 0.5j)\\n\\n    \\\"\\\"\\\"\\n    if tau is not None:\\n        return ctx.convert(tau)\\n    if m is not None:\\n        m = ctx.convert(m)\\n        return ctx.j*ctx.ellipk(1-m)/ctx.ellipk(m)\\n    if k is not None:\\n        k = ctx.convert(k)\\n        return ctx.j*ctx.ellipk(1-k**2)/ctx.ellipk(k**2)\\n    if q is not None:\\n        return ctx.log(q) / (ctx.pi*ctx.j)\\n    if qbar is not None:\\n        qbar = ctx.convert(qbar)\\n        return ctx.log(qbar) / (2*ctx.pi*ctx.j)\\n\\n@defun_wrapped\\ndef kfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):\\n    r\\\"\\\"\\\"\\n    Returns the elliptic modulus `k`, given any of\\n    `q, m, k, \\\\tau, \\\\bar{q}`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> kfrom(k=0.25)\\n        0.25\\n        >>> kfrom(m=mfrom(k=0.25))\\n        0.25\\n        >>> kfrom(q=qfrom(k=0.25))\\n        0.25\\n        >>> kfrom(tau=taufrom(k=0.25))\\n        (0.25 + 0.0j)\\n        >>> kfrom(qbar=qbarfrom(k=0.25))\\n        0.25\\n\\n    As `q \\\\to 1` and `q \\\\to -1`, `k` rapidly approaches\\n    `1` and `i \\\\infty` respectively::\\n\\n        >>> kfrom(q=0.75)\\n        0.9999999999999899166471767\\n        >>> kfrom(q=-0.75)\\n        (0.0 + 7041781.096692038332790615j)\\n        >>> kfrom(q=1)\\n        1\\n        >>> kfrom(q=-1)\\n        (0.0 + +infj)\\n    \\\"\\\"\\\"\\n    if k is not None:\\n        return ctx.convert(k)\\n    if m is not None:\\n        return ctx.sqrt(m)\\n    if tau is not None:\\n        q = ctx.expjpi(tau)\\n    if qbar is not None:\\n        q = ctx.sqrt(qbar)\\n    if q == 1:\\n        return q\\n    if q == -1:\\n        return ctx.mpc(0,'inf')\\n    return (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**2\\n\\n@defun_wrapped\\ndef mfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):\\n    r\\\"\\\"\\\"\\n    Returns the elliptic parameter `m`, given any of\\n    `q, m, k, \\\\tau, \\\\bar{q}`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> mfrom(m=0.25)\\n        0.25\\n        >>> mfrom(q=qfrom(m=0.25))\\n        0.25\\n        >>> mfrom(k=kfrom(m=0.25))\\n        0.25\\n        >>> mfrom(tau=taufrom(m=0.25))\\n        (0.25 + 0.0j)\\n        >>> mfrom(qbar=qbarfrom(m=0.25))\\n        0.25\\n\\n    As `q \\\\to 1` and `q \\\\to -1`, `m` rapidly approaches\\n    `1` and `-\\\\infty` respectively::\\n\\n        >>> mfrom(q=0.75)\\n        0.9999999999999798332943533\\n        >>> mfrom(q=-0.75)\\n        -49586681013729.32611558353\\n        >>> mfrom(q=1)\\n        1.0\\n        >>> mfrom(q=-1)\\n        -inf\\n\\n    The inverse nome as a function of `q` has an integer\\n    Taylor series expansion::\\n\\n        >>> taylor(lambda q: mfrom(q), 0, 7)\\n        [0.0, 16.0, -128.0, 704.0, -3072.0, 11488.0, -38400.0, 117632.0]\\n\\n    \\\"\\\"\\\"\\n    if m is not None:\\n        return m\\n    if k is not None:\\n        return k**2\\n    if tau is not None:\\n        q = ctx.expjpi(tau)\\n    if qbar is not None:\\n        q = ctx.sqrt(qbar)\\n    if q == 1:\\n        return ctx.convert(q)\\n    if q == -1:\\n        return q*ctx.inf\\n    v = (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**4\\n    if ctx._is_real_type(q) and q < 0:\\n        v = v.real\\n    return v\\n\\njacobi_spec = {\\n  'sn' : ([3],[2],[1],[4], 'sin', 'tanh'),\\n  'cn' : ([4],[2],[2],[4], 'cos', 'sech'),\\n  'dn' : ([4],[3],[3],[4], '1', 'sech'),\\n  'ns' : ([2],[3],[4],[1], 'csc', 'coth'),\\n  'nc' : ([2],[4],[4],[2], 'sec', 'cosh'),\\n  'nd' : ([3],[4],[4],[3], '1', 'cosh'),\\n  'sc' : ([3],[4],[1],[2], 'tan', 'sinh'),\\n  'sd' : ([3,3],[2,4],[1],[3], 'sin', 'sinh'),\\n  'cd' : ([3],[2],[2],[3], 'cos', '1'),\\n  'cs' : ([4],[3],[2],[1], 'cot', 'csch'),\\n  'dc' : ([2],[3],[3],[2], 'sec', '1'),\\n  'ds' : ([2,4],[3,3],[3],[1], 'csc', 'csch'),\\n  'cc' : None,\\n  'ss' : None,\\n  'nn' : None,\\n  'dd' : None\\n}\\n\\n@defun\\ndef ellipfun(ctx, kind, u=None, m=None, q=None, k=None, tau=None):\\n    try:\\n        S = jacobi_spec[kind]\\n    except KeyError:\\n        raise ValueError(\\\"First argument must be a two-character string \\\"\\n            \\\"containing 's', 'c', 'd' or 'n', e.g.: 'sn'\\\")\\n    if u is None:\\n        def f(*args, **kwargs):\\n            return ctx.ellipfun(kind, *args, **kwargs)\\n        f.__name__ = kind\\n        return f\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 10\\n        u = ctx.convert(u)\\n        q = ctx.qfrom(m=m, q=q, k=k, tau=tau)\\n        if S is None:\\n            v = ctx.one + 0*q*u\\n        elif q == ctx.zero:\\n            if S[4] == '1': v = ctx.one\\n            else:           v = getattr(ctx, S[4])(u)\\n            v += 0*q*u\\n        elif q == ctx.one:\\n            if S[5] == '1': v = ctx.one\\n            else:           v = getattr(ctx, S[5])(u)\\n            v += 0*q*u\\n        else:\\n            t = u / ctx.jtheta(3, 0, q)**2\\n            v = ctx.one\\n            for a in S[0]: v *= ctx.jtheta(a, 0, q)\\n            for b in S[1]: v /= ctx.jtheta(b, 0, q)\\n            for c in S[2]: v *= ctx.jtheta(c, t, q)\\n            for d in S[3]: v /= ctx.jtheta(d, t, q)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\n@defun_wrapped\\ndef kleinj(ctx, tau=None, **kwargs):\\n    r\\\"\\\"\\\"\\n    Evaluates the Klein j-invariant, which is a modular function defined for\\n    `\\\\tau` in the upper half-plane as\\n\\n    .. math ::\\n\\n        J(\\\\tau) = \\\\frac{g_2^3(\\\\tau)}{g_2^3(\\\\tau) - 27 g_3^2(\\\\tau)}\\n\\n    where `g_2` and `g_3` are the modular invariants of the Weierstrass\\n    elliptic function,\\n\\n    .. math ::\\n\\n        g_2(\\\\tau) = 60 \\\\sum_{(m,n) \\\\in \\\\mathbb{Z}^2 \\\\setminus (0,0)} (m \\\\tau+n)^{-4}\\n\\n        g_3(\\\\tau) = 140 \\\\sum_{(m,n) \\\\in \\\\mathbb{Z}^2 \\\\setminus (0,0)} (m \\\\tau+n)^{-6}.\\n\\n    An alternative, common notation is that of the j-function\\n    `j(\\\\tau) = 1728 J(\\\\tau)`.\\n\\n    **Plots**\\n\\n    .. literalinclude :: /plots/kleinj.py\\n    .. image :: /plots/kleinj.png\\n    .. literalinclude :: /plots/kleinj2.py\\n    .. image :: /plots/kleinj2.png\\n\\n    **Examples**\\n\\n    Verifying the functional equation `J(\\\\tau) = J(\\\\tau+1) = J(-\\\\tau^{-1})`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> tau = 0.625+0.75*j\\n        >>> tau = 0.625+0.75*j\\n        >>> kleinj(tau)\\n        (-0.1507492166511182267125242 + 0.07595948379084571927228948j)\\n        >>> kleinj(tau+1)\\n        (-0.1507492166511182267125242 + 0.07595948379084571927228948j)\\n        >>> kleinj(-1/tau)\\n        (-0.1507492166511182267125242 + 0.07595948379084571927228946j)\\n\\n    The j-function has a famous Laurent series expansion in terms of the nome\\n    `\\\\bar{q}`, `j(\\\\tau) = \\\\bar{q}^{-1} + 744 + 196884\\\\bar{q} + \\\\ldots`::\\n\\n        >>> mp.dps = 15\\n        >>> taylor(lambda q: 1728*q*kleinj(qbar=q), 0, 5, singular=True)\\n        [1.0, 744.0, 196884.0, 21493760.0, 864299970.0, 20245856256.0]\\n\\n    The j-function admits exact evaluation at special algebraic points\\n    related to the Heegner numbers 1, 2, 3, 7, 11, 19, 43, 67, 163::\\n\\n        >>> @extraprec(10)\\n        ... def h(n):\\n        ...     v = (1+sqrt(n)*j)\\n        ...     if n > 2:\\n        ...         v *= 0.5\\n        ...     return v\\n        ...\\n        >>> mp.dps = 25\\n        >>> for n in [1,2,3,7,11,19,43,67,163]:\\n        ...     n, chop(1728*kleinj(h(n)))\\n        ...\\n        (1, 1728.0)\\n        (2, 8000.0)\\n        (3, 0.0)\\n        (7, -3375.0)\\n        (11, -32768.0)\\n        (19, -884736.0)\\n        (43, -884736000.0)\\n        (67, -147197952000.0)\\n        (163, -262537412640768000.0)\\n\\n    Also at other special points, the j-function assumes explicit\\n    algebraic values, e.g.::\\n\\n        >>> chop(1728*kleinj(j*sqrt(5)))\\n        1264538.909475140509320227\\n        >>> identify(cbrt(_))      # note: not simplified\\n        '((100+sqrt(13520))/2)'\\n        >>> (50+26*sqrt(5))**3\\n        1264538.909475140509320227\\n\\n    \\\"\\\"\\\"\\n    q = ctx.qfrom(tau=tau, **kwargs)\\n    t2 = ctx.jtheta(2,0,q)\\n    t3 = ctx.jtheta(3,0,q)\\n    t4 = ctx.jtheta(4,0,q)\\n    P = (t2**8 + t3**8 + t4**8)**3\\n    Q = 54*(t2*t3*t4)**8\\n    return P/Q\\n\\n\\ndef RF_calc(ctx, x, y, z, r):\\n    if y == z: return RC_calc(ctx, x, y, r)\\n    if x == z: return RC_calc(ctx, y, x, r)\\n    if x == y: return RC_calc(ctx, z, x, r)\\n    if not (ctx.isnormal(x) and ctx.isnormal(y) and ctx.isnormal(z)):\\n        if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z):\\n            return x*y*z\\n        if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z):\\n            return ctx.zero\\n    xm,ym,zm = x,y,z\\n    A0 = Am = (x+y+z)/3\\n    Q = ctx.root(3*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z))\\n    g = ctx.mpf(0.25)\\n    pow4 = ctx.one\\n    while 1:\\n        xs = ctx.sqrt(xm)\\n        ys = ctx.sqrt(ym)\\n        zs = ctx.sqrt(zm)\\n        lm = xs*ys + xs*zs + ys*zs\\n        Am1 = (Am+lm)*g\\n        xm, ym, zm = (xm+lm)*g, (ym+lm)*g, (zm+lm)*g\\n        if pow4 * Q < abs(Am):\\n            break\\n        Am = Am1\\n        pow4 *= g\\n    t = pow4/Am\\n    X = (A0-x)*t\\n    Y = (A0-y)*t\\n    Z = -X-Y\\n    E2 = X*Y-Z**2\\n    E3 = X*Y*Z\\n    return ctx.power(Am,-0.5) * (9240-924*E2+385*E2**2+660*E3-630*E2*E3)/9240\\n\\ndef RC_calc(ctx, x, y, r, pv=True):\\n    if not (ctx.isnormal(x) and ctx.isnormal(y)):\\n        if ctx.isinf(x) or ctx.isinf(y):\\n            return 1/(x*y)\\n        if y == 0:\\n            return ctx.inf\\n        if x == 0:\\n            return ctx.pi / ctx.sqrt(y) / 2\\n        raise ValueError\\n    # Cauchy principal value\\n    if pv and ctx._im(y) == 0 and ctx._re(y) < 0:\\n        return ctx.sqrt(x/(x-y)) * RC_calc(ctx, x-y, -y, r)\\n    if x == y:\\n        return 1/ctx.sqrt(x)\\n    extraprec = 2*max(0,-ctx.mag(x-y)+ctx.mag(x))\\n    ctx.prec += extraprec\\n    if ctx._is_real_type(x) and ctx._is_real_type(y):\\n        x = ctx._re(x)\\n        y = ctx._re(y)\\n        a = ctx.sqrt(x/y)\\n        if x < y:\\n            b = ctx.sqrt(y-x)\\n            v = ctx.acos(a)/b\\n        else:\\n            b = ctx.sqrt(x-y)\\n            v = ctx.acosh(a)/b\\n    else:\\n        sx = ctx.sqrt(x)\\n        sy = ctx.sqrt(y)\\n        v = ctx.acos(sx/sy)/(ctx.sqrt((1-x/y))*sy)\\n    ctx.prec -= extraprec\\n    return v\\n\\ndef RJ_calc(ctx, x, y, z, p, r, integration):\\n    \\\"\\\"\\\"\\n    With integration == 0, computes RJ only using Carlson's algorithm\\n    (may be wrong for some values).\\n    With integration == 1, uses an initial integration to make sure\\n    Carlson's algorithm is correct.\\n    With integration == 2, uses only integration.\\n    \\\"\\\"\\\"\\n    if not (ctx.isnormal(x) and ctx.isnormal(y) and \\\\\\n        ctx.isnormal(z) and ctx.isnormal(p)):\\n        if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z) or ctx.isnan(p):\\n            return x*y*z\\n        if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z) or ctx.isinf(p):\\n            return ctx.zero\\n    if not p:\\n        return ctx.inf\\n    if (not x) + (not y) + (not z) > 1:\\n        return ctx.inf\\n    # Check conditions and fall back on integration for argument\\n    # reduction if needed. The following conditions might be needlessly\\n    # restrictive.\\n    initial_integral = ctx.zero\\n    if integration >= 1:\\n        ok = (x.real >= 0 and y.real >= 0 and z.real >= 0 and p.real > 0)\\n        if not ok:\\n            if x == p or y == p or z == p:\\n                ok = True\\n        if not ok:\\n            if p.imag != 0 or p.real >= 0:\\n                if (x.imag == 0 and x.real >= 0 and ctx.conj(y) == z):\\n                    ok = True\\n                if (y.imag == 0 and y.real >= 0 and ctx.conj(x) == z):\\n                    ok = True\\n                if (z.imag == 0 and z.real >= 0 and ctx.conj(x) == y):\\n                    ok = True\\n        if not ok or (integration == 2):\\n            N = ctx.ceil(-min(x.real, y.real, z.real, p.real)) + 1\\n            # Integrate around any singularities\\n            if all((t.imag >= 0 or t.real > 0) for t in [x, y, z, p]):\\n                margin = ctx.j\\n            elif all((t.imag < 0 or t.real > 0) for t in [x, y, z, p]):\\n                margin = -ctx.j\\n            else:\\n                margin = 1\\n                # Go through the upper half-plane, but low enough that any\\n                # parameter starting in the lower plane doesn't cross the\\n                # branch cut\\n                for t in [x, y, z, p]:\\n                    if t.imag >= 0 or t.real > 0:\\n                        continue\\n                    margin = min(margin, abs(t.imag) * 0.5)\\n                margin *= ctx.j\\n            N += margin\\n            F = lambda t: 1/(ctx.sqrt(t+x)*ctx.sqrt(t+y)*ctx.sqrt(t+z)*(t+p))\\n            if integration == 2:\\n                return 1.5 * ctx.quadsubdiv(F, [0, N, ctx.inf])\\n            initial_integral = 1.5 * ctx.quadsubdiv(F, [0, N])\\n            x += N; y += N; z += N; p += N\\n    xm,ym,zm,pm = x,y,z,p\\n    A0 = Am = (x + y + z + 2*p)/5\\n    delta = (p-x)*(p-y)*(p-z)\\n    Q = ctx.root(0.25*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z),abs(A0-p))\\n    g = ctx.mpf(0.25)\\n    pow4 = ctx.one\\n    S = 0\\n    while 1:\\n        sx = ctx.sqrt(xm)\\n        sy = ctx.sqrt(ym)\\n        sz = ctx.sqrt(zm)\\n        sp = ctx.sqrt(pm)\\n        lm = sx*sy + sx*sz + sy*sz\\n        Am1 = (Am+lm)*g\\n        xm = (xm+lm)*g; ym = (ym+lm)*g; zm = (zm+lm)*g; pm = (pm+lm)*g\\n        dm = (sp+sx) * (sp+sy) * (sp+sz)\\n        em = delta * pow4**3 / dm**2\\n        if pow4 * Q < abs(Am):\\n            break\\n        T = RC_calc(ctx, ctx.one, ctx.one+em, r) * pow4 / dm\\n        S += T\\n        pow4 *= g\\n        Am = Am1\\n    t = pow4 / Am\\n    X = (A0-x)*t\\n    Y = (A0-y)*t\\n    Z = (A0-z)*t\\n    P = (-X-Y-Z)/2\\n    E2 = X*Y + X*Z + Y*Z - 3*P**2\\n    E3 = X*Y*Z + 2*E2*P + 4*P**3\\n    E4 = (2*X*Y*Z + E2*P + 3*P**3)*P\\n    E5 = X*Y*Z*P**2\\n    P = 24024 - 5148*E2 + 2457*E2**2 + 4004*E3 - 4158*E2*E3 - 3276*E4 + 2772*E5\\n    Q = 24024\\n    v1 = pow4 * ctx.power(Am, -1.5) * P/Q\\n    v2 = 6*S\\n    return initial_integral + v1 + v2\\n\\n@defun\\ndef elliprf(ctx, x, y, z):\\n    r\\\"\\\"\\\"\\n    Evaluates the Carlson symmetric elliptic integral of the first kind\\n\\n    .. math ::\\n\\n        R_F(x,y,z) = \\\\frac{1}{2}\\n            \\\\int_0^{\\\\infty} \\\\frac{dt}{\\\\sqrt{(t+x)(t+y)(t+z)}}\\n\\n    which is defined for `x,y,z \\\\notin (-\\\\infty,0)`, and with\\n    at most one of `x,y,z` being zero.\\n\\n    For real `x,y,z \\\\ge 0`, the principal square root is taken in the integrand.\\n    For complex `x,y,z`, the principal square root is taken as `t \\\\to \\\\infty`\\n    and as `t \\\\to 0` non-principal branches are chosen as necessary so as to\\n    make the integrand continuous.\\n\\n    **Examples**\\n\\n    Some basic values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> elliprf(0,1,1); pi/2\\n        1.570796326794896619231322\\n        1.570796326794896619231322\\n        >>> elliprf(0,1,inf)\\n        0.0\\n        >>> elliprf(1,1,1)\\n        1.0\\n        >>> elliprf(2,2,2)**2\\n        0.5\\n        >>> elliprf(1,0,0); elliprf(0,0,1); elliprf(0,1,0); elliprf(0,0,0)\\n        +inf\\n        +inf\\n        +inf\\n        +inf\\n\\n    Representing complete elliptic integrals in terms of `R_F`::\\n\\n        >>> m = mpf(0.75)\\n        >>> ellipk(m); elliprf(0,1-m,1)\\n        2.156515647499643235438675\\n        2.156515647499643235438675\\n        >>> ellipe(m); elliprf(0,1-m,1)-m*elliprd(0,1-m,1)/3\\n        1.211056027568459524803563\\n        1.211056027568459524803563\\n\\n    Some symmetries and argument transformations::\\n\\n        >>> x,y,z = 2,3,4\\n        >>> elliprf(x,y,z); elliprf(y,x,z); elliprf(z,y,x)\\n        0.5840828416771517066928492\\n        0.5840828416771517066928492\\n        0.5840828416771517066928492\\n        >>> k = mpf(100000)\\n        >>> elliprf(k*x,k*y,k*z); k**(-0.5) * elliprf(x,y,z)\\n        0.001847032121923321253219284\\n        0.001847032121923321253219284\\n        >>> l = sqrt(x*y) + sqrt(y*z) + sqrt(z*x)\\n        >>> elliprf(x,y,z); 2*elliprf(x+l,y+l,z+l)\\n        0.5840828416771517066928492\\n        0.5840828416771517066928492\\n        >>> elliprf((x+l)/4,(y+l)/4,(z+l)/4)\\n        0.5840828416771517066928492\\n\\n    Comparing with numerical integration::\\n\\n        >>> x,y,z = 2,3,4\\n        >>> elliprf(x,y,z)\\n        0.5840828416771517066928492\\n        >>> f = lambda t: 0.5*((t+x)*(t+y)*(t+z))**(-0.5)\\n        >>> q = extradps(25)(quad)\\n        >>> q(f, [0,inf])\\n        0.5840828416771517066928492\\n\\n    With the following arguments, the square root in the integrand becomes\\n    discontinuous at `t = 1/2` if the principal branch is used. To obtain\\n    the right value, `-\\\\sqrt{r}` must be taken instead of `\\\\sqrt{r}`\\n    on `t \\\\in (0, 1/2)`::\\n\\n        >>> x,y,z = j-1,j,0\\n        >>> elliprf(x,y,z)\\n        (0.7961258658423391329305694 - 1.213856669836495986430094j)\\n        >>> -q(f, [0,0.5]) + q(f, [0.5,inf])\\n        (0.7961258658423391329305694 - 1.213856669836495986430094j)\\n\\n    The so-called *first lemniscate constant*, a transcendental number::\\n\\n        >>> elliprf(0,1,2)\\n        1.31102877714605990523242\\n        >>> extradps(25)(quad)(lambda t: 1/sqrt(1-t**4), [0,1])\\n        1.31102877714605990523242\\n        >>> gamma('1/4')**2/(4*sqrt(2*pi))\\n        1.31102877714605990523242\\n\\n    **References**\\n\\n    1. [Carlson]_\\n    2. [DLMF]_ Chapter 19. Elliptic Integrals\\n\\n    \\\"\\\"\\\"\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    z = ctx.convert(z)\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 20\\n        tol = ctx.eps * 2**10\\n        v = RF_calc(ctx, x, y, z, tol)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\n@defun\\ndef elliprc(ctx, x, y, pv=True):\\n    r\\\"\\\"\\\"\\n    Evaluates the degenerate Carlson symmetric elliptic integral\\n    of the first kind\\n\\n    .. math ::\\n\\n        R_C(x,y) = R_F(x,y,y) =\\n            \\\\frac{1}{2} \\\\int_0^{\\\\infty} \\\\frac{dt}{(t+y) \\\\sqrt{(t+x)}}.\\n\\n    If `y \\\\in (-\\\\infty,0)`, either a value defined by continuity,\\n    or with *pv=True* the Cauchy principal value, can be computed.\\n\\n    If `x \\\\ge 0, y > 0`, the value can be expressed in terms of\\n    elementary functions as\\n\\n    .. math ::\\n\\n        R_C(x,y) =\\n        \\\\begin{cases}\\n          \\\\dfrac{1}{\\\\sqrt{y-x}}\\n            \\\\cos^{-1}\\\\left(\\\\sqrt{\\\\dfrac{x}{y}}\\\\right),   & x < y \\\\\\\\\\n          \\\\dfrac{1}{\\\\sqrt{y}},                          & x = y \\\\\\\\\\n          \\\\dfrac{1}{\\\\sqrt{x-y}}\\n            \\\\cosh^{-1}\\\\left(\\\\sqrt{\\\\dfrac{x}{y}}\\\\right),  & x > y \\\\\\\\\\n        \\\\end{cases}.\\n\\n    **Examples**\\n\\n    Some special values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> elliprc(1,2)*4; elliprc(0,1)*2; +pi\\n        3.141592653589793238462643\\n        3.141592653589793238462643\\n        3.141592653589793238462643\\n        >>> elliprc(1,0)\\n        +inf\\n        >>> elliprc(5,5)**2\\n        0.2\\n        >>> elliprc(1,inf); elliprc(inf,1); elliprc(inf,inf)\\n        0.0\\n        0.0\\n        0.0\\n\\n    Comparing with the elementary closed-form solution::\\n\\n        >>> elliprc('1/3', '1/5'); sqrt(7.5)*acosh(sqrt('5/3'))\\n        2.041630778983498390751238\\n        2.041630778983498390751238\\n        >>> elliprc('1/5', '1/3'); sqrt(7.5)*acos(sqrt('3/5'))\\n        1.875180765206547065111085\\n        1.875180765206547065111085\\n\\n    Comparing with numerical integration::\\n\\n        >>> q = extradps(25)(quad)\\n        >>> elliprc(2, -3, pv=True)\\n        0.3333969101113672670749334\\n        >>> elliprc(2, -3, pv=False)\\n        (0.3333969101113672670749334 + 0.7024814731040726393156375j)\\n        >>> 0.5*q(lambda t: 1/(sqrt(t+2)*(t-3)), [0,3-j,6,inf])\\n        (0.3333969101113672670749334 + 0.7024814731040726393156375j)\\n\\n    \\\"\\\"\\\"\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 20\\n        tol = ctx.eps * 2**10\\n        v = RC_calc(ctx, x, y, tol, pv)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\n@defun\\ndef elliprj(ctx, x, y, z, p, integration=1):\\n    r\\\"\\\"\\\"\\n    Evaluates the Carlson symmetric elliptic integral of the third kind\\n\\n    .. math ::\\n\\n        R_J(x,y,z,p) = \\\\frac{3}{2}\\n            \\\\int_0^{\\\\infty} \\\\frac{dt}{(t+p)\\\\sqrt{(t+x)(t+y)(t+z)}}.\\n\\n    Like :func:`~mpmath.elliprf`, the branch of the square root in the integrand\\n    is defined so as to be continuous along the path of integration for\\n    complex values of the arguments.\\n\\n    **Examples**\\n\\n    Some values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> elliprj(1,1,1,1)\\n        1.0\\n        >>> elliprj(2,2,2,2); 1/(2*sqrt(2))\\n        0.3535533905932737622004222\\n        0.3535533905932737622004222\\n        >>> elliprj(0,1,2,2)\\n        1.067937989667395702268688\\n        >>> 3*(2*gamma('5/4')**2-pi**2/gamma('1/4')**2)/(sqrt(2*pi))\\n        1.067937989667395702268688\\n        >>> elliprj(0,1,1,2); 3*pi*(2-sqrt(2))/4\\n        1.380226776765915172432054\\n        1.380226776765915172432054\\n        >>> elliprj(1,3,2,0); elliprj(0,1,1,0); elliprj(0,0,0,0)\\n        +inf\\n        +inf\\n        +inf\\n        >>> elliprj(1,inf,1,0); elliprj(1,1,1,inf)\\n        0.0\\n        0.0\\n        >>> chop(elliprj(1+j, 1-j, 1, 1))\\n        0.8505007163686739432927844\\n\\n    Scale transformation::\\n\\n        >>> x,y,z,p = 2,3,4,5\\n        >>> k = mpf(100000)\\n        >>> elliprj(k*x,k*y,k*z,k*p); k**(-1.5)*elliprj(x,y,z,p)\\n        4.521291677592745527851168e-9\\n        4.521291677592745527851168e-9\\n\\n    Comparing with numerical integration::\\n\\n        >>> elliprj(1,2,3,4)\\n        0.2398480997495677621758617\\n        >>> f = lambda t: 1/((t+4)*sqrt((t+1)*(t+2)*(t+3)))\\n        >>> 1.5*quad(f, [0,inf])\\n        0.2398480997495677621758617\\n        >>> elliprj(1,2+1j,3,4-2j)\\n        (0.216888906014633498739952 + 0.04081912627366673332369512j)\\n        >>> f = lambda t: 1/((t+4-2j)*sqrt((t+1)*(t+2+1j)*(t+3)))\\n        >>> 1.5*quad(f, [0,inf])\\n        (0.216888906014633498739952 + 0.04081912627366673332369511j)\\n\\n    \\\"\\\"\\\"\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    z = ctx.convert(z)\\n    p = ctx.convert(p)\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 20\\n        tol = ctx.eps * 2**10\\n        v = RJ_calc(ctx, x, y, z, p, tol, integration)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\n@defun\\ndef elliprd(ctx, x, y, z):\\n    r\\\"\\\"\\\"\\n    Evaluates the degenerate Carlson symmetric elliptic integral\\n    of the third kind or Carlson elliptic integral of the\\n    second kind `R_D(x,y,z) = R_J(x,y,z,z)`.\\n\\n    See :func:`~mpmath.elliprj` for additional information.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> elliprd(1,2,3)\\n        0.2904602810289906442326534\\n        >>> elliprj(1,2,3,3)\\n        0.2904602810289906442326534\\n\\n    The so-called *second lemniscate constant*, a transcendental number::\\n\\n        >>> elliprd(0,2,1)/3\\n        0.5990701173677961037199612\\n        >>> extradps(25)(quad)(lambda t: t**2/sqrt(1-t**4), [0,1])\\n        0.5990701173677961037199612\\n        >>> gamma('3/4')**2/sqrt(2*pi)\\n        0.5990701173677961037199612\\n\\n    \\\"\\\"\\\"\\n    return ctx.elliprj(x,y,z,z)\\n\\n@defun\\ndef elliprg(ctx, x, y, z):\\n    r\\\"\\\"\\\"\\n    Evaluates the Carlson completely symmetric elliptic integral\\n    of the second kind\\n\\n    .. math ::\\n\\n        R_G(x,y,z) = \\\\frac{1}{4} \\\\int_0^{\\\\infty}\\n            \\\\frac{t}{\\\\sqrt{(t+x)(t+y)(t+z)}}\\n            \\\\left( \\\\frac{x}{t+x} + \\\\frac{y}{t+y} + \\\\frac{z}{t+z}\\\\right) dt.\\n\\n    **Examples**\\n\\n    Evaluation for real and complex arguments::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> elliprg(0,1,1)*4; +pi\\n        3.141592653589793238462643\\n        3.141592653589793238462643\\n        >>> elliprg(0,0.5,1)\\n        0.6753219405238377512600874\\n        >>> chop(elliprg(1+j, 1-j, 2))\\n        1.172431327676416604532822\\n\\n    A double integral that can be evaluated in terms of `R_G`::\\n\\n        >>> x,y,z = 2,3,4\\n        >>> def f(t,u):\\n        ...     st = fp.sin(t); ct = fp.cos(t)\\n        ...     su = fp.sin(u); cu = fp.cos(u)\\n        ...     return (x*(st*cu)**2 + y*(st*su)**2 + z*ct**2)**0.5 * st\\n        ...\\n        >>> nprint(mpf(fp.quad(f, [0,fp.pi], [0,2*fp.pi])/(4*fp.pi)), 13)\\n        1.725503028069\\n        >>> nprint(elliprg(x,y,z), 13)\\n        1.725503028069\\n\\n    \\\"\\\"\\\"\\n    x = ctx.convert(x)\\n    y = ctx.convert(y)\\n    z = ctx.convert(z)\\n    zeros = (not x) + (not y) + (not z)\\n    if zeros == 3:\\n        return (x+y+z)*0\\n    if zeros == 2:\\n        if x: return 0.5*ctx.sqrt(x)\\n        if y: return 0.5*ctx.sqrt(y)\\n        return 0.5*ctx.sqrt(z)\\n    if zeros == 1:\\n        if not z:\\n            x, z = z, x\\n    def terms():\\n        T1 = 0.5*z*ctx.elliprf(x,y,z)\\n        T2 = -0.5*(x-z)*(y-z)*ctx.elliprd(x,y,z)/3\\n        T3 = 0.5*ctx.sqrt(x)*ctx.sqrt(y)/ctx.sqrt(z)\\n        return T1,T2,T3\\n    return ctx.sum_accurately(terms)\\n\\n\\n@defun_wrapped\\ndef ellipf(ctx, phi, m):\\n    r\\\"\\\"\\\"\\n    Evaluates the Legendre incomplete elliptic integral of the first kind\\n\\n     .. math ::\\n\\n        F(\\\\phi,m) = \\\\int_0^{\\\\phi} \\\\frac{dt}{\\\\sqrt{1-m \\\\sin^2 t}}\\n\\n    or equivalently\\n\\n    .. math ::\\n\\n        F(\\\\phi,m) = \\\\int_0^{\\\\sin \\\\phi}\\n        \\\\frac{dt}{\\\\left(\\\\sqrt{1-t^2}\\\\right)\\\\left(\\\\sqrt{1-mt^2}\\\\right)}.\\n\\n    The function reduces to a complete elliptic integral of the first kind\\n    (see :func:`~mpmath.ellipk`) when `\\\\phi = \\\\frac{\\\\pi}{2}`; that is,\\n\\n    .. math ::\\n\\n        F\\\\left(\\\\frac{\\\\pi}{2}, m\\\\right) = K(m).\\n\\n    In the defining integral, it is assumed that the principal branch\\n    of the square root is taken and that the path of integration avoids\\n    crossing any branch cuts. Outside `-\\\\pi/2 \\\\le \\\\Re(\\\\phi) \\\\le \\\\pi/2`,\\n    the function extends quasi-periodically as\\n\\n    .. math ::\\n\\n        F(\\\\phi + n \\\\pi, m) = 2 n K(m) + F(\\\\phi,m), n \\\\in \\\\mathbb{Z}.\\n\\n    **Plots**\\n\\n    .. literalinclude :: /plots/ellipf.py\\n    .. image :: /plots/ellipf.png\\n\\n    **Examples**\\n\\n    Basic values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> ellipf(0,1)\\n        0.0\\n        >>> ellipf(0,0)\\n        0.0\\n        >>> ellipf(1,0); ellipf(2+3j,0)\\n        1.0\\n        (2.0 + 3.0j)\\n        >>> ellipf(1,1); log(sec(1)+tan(1))\\n        1.226191170883517070813061\\n        1.226191170883517070813061\\n        >>> ellipf(pi/2, -0.5); ellipk(-0.5)\\n        1.415737208425956198892166\\n        1.415737208425956198892166\\n        >>> ellipf(pi/2+eps, 1); ellipf(-pi/2-eps, 1)\\n        +inf\\n        +inf\\n        >>> ellipf(1.5, 1)\\n        3.340677542798311003320813\\n\\n    Comparing with numerical integration::\\n\\n        >>> z,m = 0.5, 1.25\\n        >>> ellipf(z,m)\\n        0.5287219202206327872978255\\n        >>> quad(lambda t: (1-m*sin(t)**2)**(-0.5), [0,z])\\n        0.5287219202206327872978255\\n\\n    The arguments may be complex numbers::\\n\\n        >>> ellipf(3j, 0.5)\\n        (0.0 + 1.713602407841590234804143j)\\n        >>> ellipf(3+4j, 5-6j)\\n        (1.269131241950351323305741 - 0.3561052815014558335412538j)\\n        >>> z,m = 2+3j, 1.25\\n        >>> k = 1011\\n        >>> ellipf(z+pi*k,m); ellipf(z,m) + 2*k*ellipk(m)\\n        (4086.184383622179764082821 - 3003.003538923749396546871j)\\n        (4086.184383622179764082821 - 3003.003538923749396546871j)\\n\\n    For `|\\\\Re(z)| < \\\\pi/2`, the function can be expressed as a\\n    hypergeometric series of two variables\\n    (see :func:`~mpmath.appellf1`)::\\n\\n        >>> z,m = 0.5, 0.25\\n        >>> ellipf(z,m)\\n        0.5050887275786480788831083\\n        >>> sin(z)*appellf1(0.5,0.5,0.5,1.5,sin(z)**2,m*sin(z)**2)\\n        0.5050887275786480788831083\\n\\n    \\\"\\\"\\\"\\n    z = phi\\n    if not (ctx.isnormal(z) and ctx.isnormal(m)):\\n        if m == 0:\\n            return z + m\\n        if z == 0:\\n            return z * m\\n        if m == ctx.inf or m == ctx.ninf: return z/m\\n        raise ValueError\\n    x = z.real\\n    ctx.prec += max(0, ctx.mag(x))\\n    pi = +ctx.pi\\n    away = abs(x) > pi/2\\n    if m == 1:\\n        if away:\\n            return ctx.inf\\n    if away:\\n        d = ctx.nint(x/pi)\\n        z = z-pi*d\\n        P = 2*d*ctx.ellipk(m)\\n    else:\\n        P = 0\\n    c, s = ctx.cos_sin(z)\\n    return s * ctx.elliprf(c**2, 1-m*s**2, 1) + P\\n\\n@defun_wrapped\\ndef ellipe(ctx, *args):\\n    r\\\"\\\"\\\"\\n    Called with a single argument `m`, evaluates the Legendre complete\\n    elliptic integral of the second kind, `E(m)`, defined by\\n\\n        .. math :: E(m) = \\\\int_0^{\\\\pi/2} \\\\sqrt{1-m \\\\sin^2 t} \\\\, dt \\\\,=\\\\,\\n            \\\\frac{\\\\pi}{2}\\n            \\\\,_2F_1\\\\left(\\\\frac{1}{2}, -\\\\frac{1}{2}, 1, m\\\\right).\\n\\n    Called with two arguments `\\\\phi, m`, evaluates the incomplete elliptic\\n    integral of the second kind\\n\\n     .. math ::\\n\\n        E(\\\\phi,m) = \\\\int_0^{\\\\phi} \\\\sqrt{1-m \\\\sin^2 t} \\\\, dt =\\n                    \\\\int_0^{\\\\sin z}\\n                    \\\\frac{\\\\sqrt{1-mt^2}}{\\\\sqrt{1-t^2}} \\\\, dt.\\n\\n    The incomplete integral reduces to a complete integral when\\n    `\\\\phi = \\\\frac{\\\\pi}{2}`; that is,\\n\\n    .. math ::\\n\\n        E\\\\left(\\\\frac{\\\\pi}{2}, m\\\\right) = E(m).\\n\\n    In the defining integral, it is assumed that the principal branch\\n    of the square root is taken and that the path of integration avoids\\n    crossing any branch cuts. Outside `-\\\\pi/2 \\\\le \\\\Re(z) \\\\le \\\\pi/2`,\\n    the function extends quasi-periodically as\\n\\n    .. math ::\\n\\n        E(\\\\phi + n \\\\pi, m) = 2 n E(m) + E(\\\\phi,m), n \\\\in \\\\mathbb{Z}.\\n\\n    **Plots**\\n\\n    .. literalinclude :: /plots/ellipe.py\\n    .. image :: /plots/ellipe.png\\n\\n    **Examples for the complete integral**\\n\\n    Basic values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> ellipe(0)\\n        1.570796326794896619231322\\n        >>> ellipe(1)\\n        1.0\\n        >>> ellipe(-1)\\n        1.910098894513856008952381\\n        >>> ellipe(2)\\n        (0.5990701173677961037199612 + 0.5990701173677961037199612j)\\n        >>> ellipe(inf)\\n        (0.0 + +infj)\\n        >>> ellipe(-inf)\\n        +inf\\n\\n    Verifying the defining integral and hypergeometric\\n    representation::\\n\\n        >>> ellipe(0.5)\\n        1.350643881047675502520175\\n        >>> quad(lambda t: sqrt(1-0.5*sin(t)**2), [0, pi/2])\\n        1.350643881047675502520175\\n        >>> pi/2*hyp2f1(0.5,-0.5,1,0.5)\\n        1.350643881047675502520175\\n\\n    Evaluation is supported for arbitrary complex `m`::\\n\\n        >>> ellipe(0.5+0.25j)\\n        (1.360868682163129682716687 - 0.1238733442561786843557315j)\\n        >>> ellipe(3+4j)\\n        (1.499553520933346954333612 - 1.577879007912758274533309j)\\n\\n    A definite integral::\\n\\n        >>> quad(ellipe, [0,1])\\n        1.333333333333333333333333\\n\\n    **Examples for the incomplete integral**\\n\\n    Basic values and limits::\\n\\n        >>> ellipe(0,1)\\n        0.0\\n        >>> ellipe(0,0)\\n        0.0\\n        >>> ellipe(1,0)\\n        1.0\\n        >>> ellipe(2+3j,0)\\n        (2.0 + 3.0j)\\n        >>> ellipe(1,1); sin(1)\\n        0.8414709848078965066525023\\n        0.8414709848078965066525023\\n        >>> ellipe(pi/2, -0.5); ellipe(-0.5)\\n        1.751771275694817862026502\\n        1.751771275694817862026502\\n        >>> ellipe(pi/2, 1); ellipe(-pi/2, 1)\\n        1.0\\n        -1.0\\n        >>> ellipe(1.5, 1)\\n        0.9974949866040544309417234\\n\\n    Comparing with numerical integration::\\n\\n        >>> z,m = 0.5, 1.25\\n        >>> ellipe(z,m)\\n        0.4740152182652628394264449\\n        >>> quad(lambda t: sqrt(1-m*sin(t)**2), [0,z])\\n        0.4740152182652628394264449\\n\\n    The arguments may be complex numbers::\\n\\n        >>> ellipe(3j, 0.5)\\n        (0.0 + 7.551991234890371873502105j)\\n        >>> ellipe(3+4j, 5-6j)\\n        (24.15299022574220502424466 + 75.2503670480325997418156j)\\n        >>> k = 35\\n        >>> z,m = 2+3j, 1.25\\n        >>> ellipe(z+pi*k,m); ellipe(z,m) + 2*k*ellipe(m)\\n        (48.30138799412005235090766 + 17.47255216721987688224357j)\\n        (48.30138799412005235090766 + 17.47255216721987688224357j)\\n\\n    For `|\\\\Re(z)| < \\\\pi/2`, the function can be expressed as a\\n    hypergeometric series of two variables\\n    (see :func:`~mpmath.appellf1`)::\\n\\n        >>> z,m = 0.5, 0.25\\n        >>> ellipe(z,m)\\n        0.4950017030164151928870375\\n        >>> sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2)\\n        0.4950017030164151928870376\\n\\n    \\\"\\\"\\\"\\n    if len(args) == 1:\\n        return ctx._ellipe(args[0])\\n    else:\\n        phi, m = args\\n    z = phi\\n    if not (ctx.isnormal(z) and ctx.isnormal(m)):\\n        if m == 0:\\n            return z + m\\n        if z == 0:\\n            return z * m\\n        if m == ctx.inf or m == ctx.ninf:\\n            return ctx.inf\\n        raise ValueError\\n    x = z.real\\n    ctx.prec += max(0, ctx.mag(x))\\n    pi = +ctx.pi\\n    away = abs(x) > pi/2\\n    if away:\\n        d = ctx.nint(x/pi)\\n        z = z-pi*d\\n        P = 2*d*ctx.ellipe(m)\\n    else:\\n        P = 0\\n    def terms():\\n        c, s = ctx.cos_sin(z)\\n        x = c**2\\n        y = 1-m*s**2\\n        RF = ctx.elliprf(x, y, 1)\\n        RD = ctx.elliprd(x, y, 1)\\n        return s*RF, -m*s**3*RD/3\\n    return ctx.sum_accurately(terms) + P\\n\\n@defun_wrapped\\ndef ellippi(ctx, *args):\\n    r\\\"\\\"\\\"\\n    Called with three arguments `n, \\\\phi, m`, evaluates the Legendre\\n    incomplete elliptic integral of the third kind\\n\\n    .. math ::\\n\\n        \\\\Pi(n; \\\\phi, m) = \\\\int_0^{\\\\phi}\\n            \\\\frac{dt}{(1-n \\\\sin^2 t) \\\\sqrt{1-m \\\\sin^2 t}} =\\n            \\\\int_0^{\\\\sin \\\\phi}\\n            \\\\frac{dt}{(1-nt^2) \\\\sqrt{1-t^2} \\\\sqrt{1-mt^2}}.\\n\\n    Called with two arguments `n, m`, evaluates the complete\\n    elliptic integral of the third kind\\n    `\\\\Pi(n,m) = \\\\Pi(n; \\\\frac{\\\\pi}{2},m)`.\\n\\n    In the defining integral, it is assumed that the principal branch\\n    of the square root is taken and that the path of integration avoids\\n    crossing any branch cuts. Outside `-\\\\pi/2 \\\\le \\\\Re(\\\\phi) \\\\le \\\\pi/2`,\\n    the function extends quasi-periodically as\\n\\n    .. math ::\\n\\n        \\\\Pi(n,\\\\phi+k\\\\pi,m) = 2k\\\\Pi(n,m) + \\\\Pi(n,\\\\phi,m), k \\\\in \\\\mathbb{Z}.\\n\\n    **Plots**\\n\\n    .. literalinclude :: /plots/ellippi.py\\n    .. image :: /plots/ellippi.png\\n\\n    **Examples for the complete integral**\\n\\n    Some basic values and limits::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> ellippi(0,-5); ellipk(-5)\\n        0.9555039270640439337379334\\n        0.9555039270640439337379334\\n        >>> ellippi(inf,2)\\n        0.0\\n        >>> ellippi(2,inf)\\n        0.0\\n        >>> abs(ellippi(1,5))\\n        +inf\\n        >>> abs(ellippi(0.25,1))\\n        +inf\\n\\n    Evaluation in terms of simpler functions::\\n\\n        >>> ellippi(0.25,0.25); ellipe(0.25)/(1-0.25)\\n        1.956616279119236207279727\\n        1.956616279119236207279727\\n        >>> ellippi(3,0); pi/(2*sqrt(-2))\\n        (0.0 - 1.11072073453959156175397j)\\n        (0.0 - 1.11072073453959156175397j)\\n        >>> ellippi(-3,0); pi/(2*sqrt(4))\\n        0.7853981633974483096156609\\n        0.7853981633974483096156609\\n\\n    **Examples for the incomplete integral**\\n\\n    Basic values and limits::\\n\\n        >>> ellippi(0.25,-0.5); ellippi(0.25,pi/2,-0.5)\\n        1.622944760954741603710555\\n        1.622944760954741603710555\\n        >>> ellippi(1,0,1)\\n        0.0\\n        >>> ellippi(inf,0,1)\\n        0.0\\n        >>> ellippi(0,0.25,0.5); ellipf(0.25,0.5)\\n        0.2513040086544925794134591\\n        0.2513040086544925794134591\\n        >>> ellippi(1,1,1); (log(sec(1)+tan(1))+sec(1)*tan(1))/2\\n        2.054332933256248668692452\\n        2.054332933256248668692452\\n        >>> ellippi(0.25, 53*pi/2, 0.75); 53*ellippi(0.25,0.75)\\n        135.240868757890840755058\\n        135.240868757890840755058\\n        >>> ellippi(0.5,pi/4,0.5); 2*ellipe(pi/4,0.5)-1/sqrt(3)\\n        0.9190227391656969903987269\\n        0.9190227391656969903987269\\n\\n    Complex arguments are supported::\\n\\n        >>> ellippi(0.5, 5+6j-2*pi, -7-8j)\\n        (-0.3612856620076747660410167 + 0.5217735339984807829755815j)\\n\\n    Some degenerate cases::\\n\\n        >>> ellippi(1,1)\\n        +inf\\n        >>> ellippi(1,0)\\n        +inf\\n        >>> ellippi(1,2,0)\\n        +inf\\n        >>> ellippi(1,2,1)\\n        +inf\\n        >>> ellippi(1,0,1)\\n        0.0\\n\\n    \\\"\\\"\\\"\\n    if len(args) == 2:\\n        n, m = args\\n        complete = True\\n        z = phi = ctx.pi/2\\n    else:\\n        n, phi, m = args\\n        complete = False\\n        z = phi\\n    if not (ctx.isnormal(n) and ctx.isnormal(z) and ctx.isnormal(m)):\\n        if ctx.isnan(n) or ctx.isnan(z) or ctx.isnan(m):\\n            raise ValueError\\n        if complete:\\n            if m == 0:\\n                if n == 1:\\n                    return ctx.inf\\n                return ctx.pi/(2*ctx.sqrt(1-n))\\n            if n == 0: return ctx.ellipk(m)\\n            if ctx.isinf(n) or ctx.isinf(m): return ctx.zero\\n        else:\\n            if z == 0: return z\\n            if ctx.isinf(n): return ctx.zero\\n            if ctx.isinf(m): return ctx.zero\\n        if ctx.isinf(n) or ctx.isinf(z) or ctx.isinf(m):\\n            raise ValueError\\n    if complete:\\n        if m == 1:\\n            if n == 1:\\n                return ctx.inf\\n            return -ctx.inf/ctx.sign(n-1)\\n        away = False\\n    else:\\n        x = z.real\\n        ctx.prec += max(0, ctx.mag(x))\\n        pi = +ctx.pi\\n        away = abs(x) > pi/2\\n    if away:\\n        d = ctx.nint(x/pi)\\n        z = z-pi*d\\n        P = 2*d*ctx.ellippi(n,m)\\n        if ctx.isinf(P):\\n            return ctx.inf\\n    else:\\n        P = 0\\n    def terms():\\n        if complete:\\n            c, s = ctx.zero, ctx.one\\n        else:\\n            c, s = ctx.cos_sin(z)\\n        x = c**2\\n        y = 1-m*s**2\\n        RF = ctx.elliprf(x, y, 1)\\n        RJ = ctx.elliprj(x, y, 1, 1-n*s**2)\\n        return s*RF, n*s**3*RJ/3\\n    return ctx.sum_accurately(terms) + P\\n\\n\\n# contributed to mpmath by Kristopher L. Kuhlman, February 2017\\n# contributed to mpmath by Guillermo Navas-Palencia, February 2022\\n\\nclass InverseLaplaceTransform(object):\\n    r\\\"\\\"\\\"\\n    Inverse Laplace transform methods are implemented using this\\n    class, in order to simplify the code and provide a common\\n    infrastructure.\\n\\n    Implement a custom inverse Laplace transform algorithm by\\n    subclassing :class:`InverseLaplaceTransform` and implementing the\\n    appropriate methods. The subclass can then be used by\\n    :func:`~mpmath.invertlaplace` by passing it as the *method*\\n    argument.\\n    \\\"\\\"\\\"\\n\\n    def __init__(self, ctx):\\n        self.ctx = ctx\\n\\n    def calc_laplace_parameter(self, t, **kwargs):\\n        r\\\"\\\"\\\"\\n        Determine the vector of Laplace parameter values needed for an\\n        algorithm, this will depend on the choice of algorithm (de\\n        Hoog is default), the algorithm-specific parameters passed (or\\n        default ones), and desired time.\\n        \\\"\\\"\\\"\\n        raise NotImplementedError\\n\\n    def calc_time_domain_solution(self, fp):\\n        r\\\"\\\"\\\"\\n        Compute the time domain solution, after computing the\\n        Laplace-space function evaluations at the abscissa required\\n        for the algorithm. Abscissa computed for one algorithm are\\n        typically not useful for another algorithm.\\n        \\\"\\\"\\\"\\n        raise NotImplementedError\\n\\n\\nclass FixedTalbot(InverseLaplaceTransform):\\n\\n    def calc_laplace_parameter(self, t, **kwargs):\\n        r\\\"\\\"\\\"The \\\"fixed\\\" Talbot method deforms the Bromwich contour towards\\n        `-\\\\infty` in the shape of a parabola. Traditionally the Talbot\\n        algorithm has adjustable parameters, but the \\\"fixed\\\" version\\n        does not. The `r` parameter could be passed in as a parameter,\\n        if you want to override the default given by (Abate & Valko,\\n        2004).\\n\\n        The Laplace parameter is sampled along a parabola opening\\n        along the negative imaginary axis, with the base of the\\n        parabola along the real axis at\\n        `p=\\\\frac{r}{t_\\\\mathrm{max}}`. As the number of terms used in\\n        the approximation (degree) grows, the abscissa required for\\n        function evaluation tend towards `-\\\\infty`, requiring high\\n        precision to prevent overflow.  If any poles, branch cuts or\\n        other singularities exist such that the deformed Bromwich\\n        contour lies to the left of the singularity, the method will\\n        fail.\\n\\n        **Optional arguments**\\n\\n        :class:`~mpmath.calculus.inverselaplace.FixedTalbot.calc_laplace_parameter`\\n        recognizes the following keywords\\n\\n        *tmax*\\n            maximum time associated with vector of times\\n            (typically just the time requested)\\n        *degree*\\n            integer order of approximation (M = number of terms)\\n        *r*\\n            abscissa for `p_0` (otherwise computed using rule\\n            of thumb `2M/5`)\\n\\n        The working precision will be increased according to a rule of\\n        thumb. If 'degree' is not specified, the working precision and\\n        degree are chosen to hopefully achieve the dps of the calling\\n        context. If 'degree' is specified, the working precision is\\n        chosen to achieve maximum resulting precision for the\\n        specified degree.\\n\\n        .. math ::\\n\\n            p_0=\\\\frac{r}{t}\\n\\n        .. math ::\\n\\n            p_i=\\\\frac{i r \\\\pi}{Mt_\\\\mathrm{max}}\\\\left[\\\\cot\\\\left(\\n            \\\\frac{i\\\\pi}{M}\\\\right) + j \\\\right] \\\\qquad 1\\\\le i <M\\n\\n        where `j=\\\\sqrt{-1}`, `r=2M/5`, and `t_\\\\mathrm{max}` is the\\n        maximum specified time.\\n\\n        \\\"\\\"\\\"\\n\\n        # required\\n        # ------------------------------\\n        # time of desired approximation\\n        self.t = self.ctx.convert(t)\\n\\n        # optional\\n        # ------------------------------\\n        # maximum time desired (used for scaling) default is requested\\n        # time.\\n        self.tmax = self.ctx.convert(kwargs.get('tmax', self.t))\\n\\n        # empirical relationships used here based on a linear fit of\\n        # requested and delivered dps for exponentially decaying time\\n        # functions for requested dps up to 512.\\n\\n        if 'degree' in kwargs:\\n            self.degree = kwargs['degree']\\n            self.dps_goal = self.degree\\n        else:\\n            self.dps_goal = int(1.72*self.ctx.dps)\\n            self.degree = max(12, int(1.38*self.dps_goal))\\n\\n        M = self.degree\\n\\n        # this is adjusting the dps of the calling context hopefully\\n        # the caller doesn't monkey around with it between calling\\n        # this routine and calc_time_domain_solution()\\n        self.dps_orig = self.ctx.dps\\n        self.ctx.dps = self.dps_goal\\n\\n        # Abate & Valko rule of thumb for r parameter\\n        self.r = kwargs.get('r', self.ctx.fraction(2, 5)*M)\\n\\n        self.theta = self.ctx.linspace(0.0, self.ctx.pi, M+1)\\n\\n        self.cot_theta = self.ctx.matrix(M, 1)\\n        self.cot_theta[0] = 0  # not used\\n\\n        # all but time-dependent part of p\\n        self.delta = self.ctx.matrix(M, 1)\\n        self.delta[0] = self.r\\n\\n        for i in range(1, M):\\n            self.cot_theta[i] = self.ctx.cot(self.theta[i])\\n            self.delta[i] = self.r*self.theta[i]*(self.cot_theta[i] + 1j)\\n\\n        self.p = self.ctx.matrix(M, 1)\\n        self.p = self.delta/self.tmax\\n\\n        # NB: p is complex (mpc)\\n\\n    def calc_time_domain_solution(self, fp, t, manual_prec=False):\\n        r\\\"\\\"\\\"The fixed Talbot time-domain solution is computed from the\\n        Laplace-space function evaluations using\\n\\n        .. math ::\\n\\n            f(t,M)=\\\\frac{2}{5t}\\\\sum_{k=0}^{M-1}\\\\Re \\\\left[\\n            \\\\gamma_k \\\\bar{f}(p_k)\\\\right]\\n\\n        where\\n\\n        .. math ::\\n\\n            \\\\gamma_0 = \\\\frac{1}{2}e^{r}\\\\bar{f}(p_0)\\n\\n        .. math ::\\n\\n            \\\\gamma_k = e^{tp_k}\\\\left\\\\lbrace 1 + \\\\frac{jk\\\\pi}{M}\\\\left[1 +\\n            \\\\cot \\\\left( \\\\frac{k \\\\pi}{M} \\\\right)^2 \\\\right] - j\\\\cot\\\\left(\\n            \\\\frac{k \\\\pi}{M}\\\\right)\\\\right \\\\rbrace \\\\qquad 1\\\\le k<M.\\n\\n        Again, `j=\\\\sqrt{-1}`.\\n\\n        Before calling this function, call\\n        :class:`~mpmath.calculus.inverselaplace.FixedTalbot.calc_laplace_parameter`\\n        to set the parameters and compute the required coefficients.\\n\\n        **References**\\n\\n        1. Abate, J., P. Valko (2004). Multi-precision Laplace\\n           transform inversion. *International Journal for Numerical\\n           Methods in Engineering* 60:979-993,\\n           http://dx.doi.org/10.1002/nme.995\\n        2. Talbot, A. (1979). The accurate numerical inversion of\\n           Laplace transforms. *IMA Journal of Applied Mathematics*\\n           23(1):97, http://dx.doi.org/10.1093/imamat/23.1.97\\n        \\\"\\\"\\\"\\n\\n        # required\\n        # ------------------------------\\n        self.t = self.ctx.convert(t)\\n\\n        # assume fp was computed from p matrix returned from\\n        # calc_laplace_parameter(), so is already a list or matrix of\\n        # mpmath 'mpc' types\\n\\n        # these were computed in previous call to\\n        # calc_laplace_parameter()\\n        theta = self.theta\\n        delta = self.delta\\n        M = self.degree\\n        p = self.p\\n        r = self.r\\n\\n        ans = self.ctx.matrix(M, 1)\\n        ans[0] = self.ctx.exp(delta[0])*fp[0]/2\\n\\n        for i in range(1, M):\\n            ans[i] = self.ctx.exp(delta[i])*fp[i]*(\\n                1 + 1j*theta[i]*(1 + self.cot_theta[i]**2) -\\n                1j*self.cot_theta[i])\\n\\n        result = self.ctx.fraction(2, 5)*self.ctx.fsum(ans)/self.t\\n\\n        # setting dps back to value when calc_laplace_parameter was\\n        # called, unless flag is set.\\n        if not manual_prec:\\n            self.ctx.dps = self.dps_orig\\n\\n        return result.real\\n\\n\\n# ****************************************\\n\\nclass Stehfest(InverseLaplaceTransform):\\n\\n    def calc_laplace_parameter(self, t, **kwargs):\\n        r\\\"\\\"\\\"\\n        The Gaver-Stehfest method is a discrete approximation of the\\n        Widder-Post inversion algorithm, rather than a direct\\n        approximation of the Bromwich contour integral.\\n\\n        The method abscissa along the real axis, and therefore has\\n        issues inverting oscillatory functions (which have poles in\\n        pairs away from the real axis).\\n\\n        The working precision will be increased according to a rule of\\n        thumb. If 'degree' is not specified, the working precision and\\n        degree are chosen to hopefully achieve the dps of the calling\\n        context. If 'degree' is specified, the working precision is\\n        chosen to achieve maximum resulting precision for the\\n        specified degree.\\n\\n        .. math ::\\n\\n            p_k = \\\\frac{k \\\\log 2}{t} \\\\qquad 1 \\\\le k \\\\le M\\n        \\\"\\\"\\\"\\n\\n        # required\\n        # ------------------------------\\n        # time of desired approximation\\n        self.t = self.ctx.convert(t)\\n\\n        # optional\\n        # ------------------------------\\n\\n        # empirical relationships used here based on a linear fit of\\n        # requested and delivered dps for exponentially decaying time\\n        # functions for requested dps up to 512.\\n\\n        if 'degree' in kwargs:\\n            self.degree = kwargs['degree']\\n            self.dps_goal = int(1.38*self.degree)\\n        else:\\n            self.dps_goal = int(2.93*self.ctx.dps)\\n            self.degree = max(16, self.dps_goal)\\n\\n        # _coeff routine requires even degree\\n        if self.degree % 2 > 0:\\n            self.degree += 1\\n\\n        M = self.degree\\n\\n        # this is adjusting the dps of the calling context\\n        # hopefully the caller doesn't monkey around with it\\n        # between calling this routine and calc_time_domain_solution()\\n        self.dps_orig = self.ctx.dps\\n        self.ctx.dps = self.dps_goal\\n\\n        self.V = self._coeff()\\n        self.p = self.ctx.matrix(self.ctx.arange(1, M+1))*self.ctx.ln2/self.t\\n\\n        # NB: p is real (mpf)\\n\\n    def _coeff(self):\\n        r\\\"\\\"\\\"Salzer summation weights (aka, \\\"Stehfest coefficients\\\")\\n        only depend on the approximation order (M) and the precision\\\"\\\"\\\"\\n\\n        M = self.degree\\n        M2 = int(M/2)  # checked earlier that M is even\\n\\n        V = self.ctx.matrix(M, 1)\\n\\n        # Salzer summation weights\\n        # get very large in magnitude and oscillate in sign,\\n        # if the precision is not high enough, there will be\\n        # catastrophic cancellation\\n        for k in range(1, M+1):\\n            z = self.ctx.matrix(min(k, M2)+1, 1)\\n            for j in range(int((k+1)/2), min(k, M2)+1):\\n                z[j] = (self.ctx.power(j, M2)*self.ctx.fac(2*j)/\\n                        (self.ctx.fac(M2-j)*self.ctx.fac(j)*\\n                         self.ctx.fac(j-1)*self.ctx.fac(k-j)*\\n                         self.ctx.fac(2*j-k)))\\n            V[k-1] = self.ctx.power(-1, k+M2)*self.ctx.fsum(z)\\n\\n        return V\\n\\n    def calc_time_domain_solution(self, fp, t, manual_prec=False):\\n        r\\\"\\\"\\\"Compute time-domain Stehfest algorithm solution.\\n\\n        .. math ::\\n\\n            f(t,M) = \\\\frac{\\\\log 2}{t} \\\\sum_{k=1}^{M} V_k \\\\bar{f}\\\\left(\\n            p_k \\\\right)\\n\\n        where\\n\\n        .. math ::\\n\\n            V_k = (-1)^{k + N/2} \\\\sum^{\\\\min(k,N/2)}_{i=\\\\lfloor(k+1)/2 \\\\rfloor}\\n            \\\\frac{i^{\\\\frac{N}{2}}(2i)!}{\\\\left(\\\\frac{N}{2}-i \\\\right)! \\\\, i! \\\\,\\n            \\\\left(i-1 \\\\right)! \\\\, \\\\left(k-i\\\\right)! \\\\, \\\\left(2i-k \\\\right)!}\\n\\n        As the degree increases, the abscissa (`p_k`) only increase\\n        linearly towards `\\\\infty`, but the Stehfest coefficients\\n        (`V_k`) alternate in sign and increase rapidly in sign,\\n        requiring high precision to prevent overflow or loss of\\n        significance when evaluating the sum.\\n\\n        **References**\\n\\n        1. Widder, D. (1941). *The Laplace Transform*. Princeton.\\n        2. Stehfest, H. (1970). Algorithm 368: numerical inversion of\\n           Laplace transforms. *Communications of the ACM* 13(1):47-49,\\n           http://dx.doi.org/10.1145/361953.361969\\n\\n        \\\"\\\"\\\"\\n\\n        # required\\n        self.t = self.ctx.convert(t)\\n\\n        # assume fp was computed from p matrix returned from\\n        # calc_laplace_parameter(), so is already\\n        # a list or matrix of mpmath 'mpf' types\\n\\n        result = self.ctx.fdot(self.V, fp)*self.ctx.ln2/self.t\\n\\n        # setting dps back to value when calc_laplace_parameter was called\\n        if not manual_prec:\\n            self.ctx.dps = self.dps_orig\\n\\n        # ignore any small imaginary part\\n        return result.real\\n\\n\\n# ****************************************\\n\\nclass deHoog(InverseLaplaceTransform):\\n\\n    def calc_laplace_parameter(self, t, **kwargs):\\n        r\\\"\\\"\\\"the de Hoog, Knight & Stokes algorithm is an\\n        accelerated form of the Fourier series numerical\\n        inverse Laplace transform algorithms.\\n\\n        .. math ::\\n\\n            p_k = \\\\gamma + \\\\frac{jk}{T} \\\\qquad 0 \\\\le k < 2M+1\\n\\n        where\\n\\n        .. math ::\\n\\n            \\\\gamma = \\\\alpha - \\\\frac{\\\\log \\\\mathrm{tol}}{2T},\\n\\n        `j=\\\\sqrt{-1}`, `T = 2t_\\\\mathrm{max}` is a scaled time,\\n        `\\\\alpha=10^{-\\\\mathrm{dps\\\\_goal}}` is the real part of the\\n        rightmost pole or singularity, which is chosen based on the\\n        desired accuracy (assuming the rightmost singularity is 0),\\n        and `\\\\mathrm{tol}=10\\\\alpha` is the desired tolerance, which is\\n        chosen in relation to `\\\\alpha`.`\\n\\n        When increasing the degree, the abscissa increase towards\\n        `j\\\\infty`, but more slowly than the fixed Talbot\\n        algorithm. The de Hoog et al. algorithm typically does better\\n        with oscillatory functions of time, and less well-behaved\\n        functions. The method tends to be slower than the Talbot and\\n        Stehfest algorithsm, especially so at very high precision\\n        (e.g., `>500` digits precision).\\n\\n        \\\"\\\"\\\"\\n\\n        # required\\n        # ------------------------------\\n        self.t = self.ctx.convert(t)\\n\\n        # optional\\n        # ------------------------------\\n        self.tmax = kwargs.get('tmax', self.t)\\n\\n        # empirical relationships used here based on a linear fit of\\n        # requested and delivered dps for exponentially decaying time\\n        # functions for requested dps up to 512.\\n\\n        if 'degree' in kwargs:\\n            self.degree = kwargs['degree']\\n            self.dps_goal = int(1.38*self.degree)\\n        else:\\n            self.dps_goal = int(self.ctx.dps*1.36)\\n            self.degree = max(10, self.dps_goal)\\n\\n        # 2*M+1 terms in approximation\\n        M = self.degree\\n\\n        # adjust alpha component of abscissa of convergence for higher\\n        # precision\\n        tmp = self.ctx.power(10.0, -self.dps_goal)\\n        self.alpha = self.ctx.convert(kwargs.get('alpha', tmp))\\n\\n        # desired tolerance (here simply related to alpha)\\n        self.tol = self.ctx.convert(kwargs.get('tol', self.alpha*10.0))\\n        self.np = 2*self.degree+1  # number of terms in approximation\\n\\n        # this is adjusting the dps of the calling context\\n        # hopefully the caller doesn't monkey around with it\\n        # between calling this routine and calc_time_domain_solution()\\n        self.dps_orig = self.ctx.dps\\n        self.ctx.dps = self.dps_goal\\n\\n        # scaling factor (likely tun-able, but 2 is typical)\\n        self.scale = kwargs.get('scale', 2)\\n        self.T = self.ctx.convert(kwargs.get('T', self.scale*self.tmax))\\n\\n        self.p = self.ctx.matrix(2*M+1, 1)\\n        self.gamma = self.alpha - self.ctx.log(self.tol)/(self.scale*self.T)\\n        self.p = (self.gamma + self.ctx.pi*\\n                  self.ctx.matrix(self.ctx.arange(self.np))/self.T*1j)\\n\\n        # NB: p is complex (mpc)\\n\\n    def calc_time_domain_solution(self, fp, t, manual_prec=False):\\n        r\\\"\\\"\\\"Calculate time-domain solution for\\n        de Hoog, Knight & Stokes algorithm.\\n\\n        The un-accelerated Fourier series approach is:\\n\\n        .. math ::\\n\\n            f(t,2M+1) = \\\\frac{e^{\\\\gamma t}}{T} \\\\sum_{k=0}^{2M}{}^{'}\\n            \\\\Re\\\\left[\\\\bar{f}\\\\left( p_k \\\\right)\\n            e^{i\\\\pi t/T} \\\\right],\\n\\n        where the prime on the summation indicates the first term is halved.\\n\\n        This simplistic approach requires so many function evaluations\\n        that it is not practical. Non-linear acceleration is\\n        accomplished via Pade-approximation and an analytic expression\\n        for the remainder of the continued fraction. See the original\\n        paper (reference 2 below) a detailed description of the\\n        numerical approach.\\n\\n        **References**\\n\\n        1. Davies, B. (2005). *Integral Transforms and their\\n           Applications*, Third Edition. Springer.\\n        2. de Hoog, F., J. Knight, A. Stokes (1982). An improved\\n           method for numerical inversion of Laplace transforms. *SIAM\\n           Journal of Scientific and Statistical Computing* 3:357-366,\\n           http://dx.doi.org/10.1137/0903022\\n\\n        \\\"\\\"\\\"\\n\\n        M = self.degree\\n        np = self.np\\n        T = self.T\\n\\n        self.t = self.ctx.convert(t)\\n\\n        # would it be useful to try re-using\\n        # space between e&q and A&B?\\n        e = self.ctx.zeros(np, M+1)\\n        q = self.ctx.matrix(2*M, M)\\n        d = self.ctx.matrix(np, 1)\\n        A = self.ctx.zeros(np+1, 1)\\n        B = self.ctx.ones(np+1, 1)\\n\\n        # initialize Q-D table\\n        e[:, 0] = 0.0 + 0j\\n        q[0, 0] = fp[1]/(fp[0]/2)\\n        for i in range(1, 2*M):\\n            q[i, 0] = fp[i+1]/fp[i]\\n\\n        # rhombus rule for filling triangular Q-D table (e & q)\\n        for r in range(1, M+1):\\n            # start with e, column 1, 0:2*M-2\\n            mr = 2*(M-r) + 1\\n            e[0:mr, r] = q[1:mr+1, r-1] - q[0:mr, r-1] + e[1:mr+1, r-1]\\n            if not r == M:\\n                rq = r+1\\n                mr = 2*(M-rq)+1 + 2\\n                for i in range(mr):\\n                    q[i, rq-1] = q[i+1, rq-2]*e[i+1, rq-1]/e[i, rq-1]\\n\\n        # build up continued fraction coefficients (d)\\n        d[0] = fp[0]/2\\n        for r in range(1, M+1):\\n            d[2*r-1] = -q[0, r-1]  # even terms\\n            d[2*r]   = -e[0, r]    # odd terms\\n\\n        # seed A and B for recurrence\\n        A[0] = 0.0 + 0.0j\\n        A[1] = d[0]\\n        B[0:2] = 1.0 + 0.0j\\n\\n        # base of the power series\\n        z = self.ctx.expjpi(self.t/T)  # i*pi is already in fcn\\n\\n        # coefficients of Pade approximation (A & B)\\n        # using recurrence for all but last term\\n        for i in range(1, 2*M):\\n            A[i+1] = A[i] + d[i]*A[i-1]*z\\n            B[i+1] = B[i] + d[i]*B[i-1]*z\\n\\n        # \\\"improved remainder\\\" to continued fraction\\n        brem = (1 + (d[2*M-1] - d[2*M])*z)/2\\n        # powm1(x,y) computes x^y - 1 more accurately near zero\\n        rem = brem*self.ctx.powm1(1 + d[2*M]*z/brem,\\n                                  self.ctx.fraction(1, 2))\\n\\n        # last term of recurrence using new remainder\\n        A[np] = A[2*M] + rem*A[2*M-1]\\n        B[np] = B[2*M] + rem*B[2*M-1]\\n\\n        # diagonal Pade approximation\\n        # F=A/B represents accelerated trapezoid rule\\n        result = self.ctx.exp(self.gamma*self.t)/T*(A[np]/B[np]).real\\n\\n        # setting dps back to value when calc_laplace_parameter was called\\n        if not manual_prec:\\n            self.ctx.dps = self.dps_orig\\n\\n        return result\\n\\n\\n# ****************************************\\n\\nclass Cohen(InverseLaplaceTransform):\\n\\n    def calc_laplace_parameter(self, t, **kwargs):\\n        r\\\"\\\"\\\"The Cohen algorithm accelerates the convergence of the nearly\\n        alternating series resulting from the application of the trapezoidal\\n        rule to the Bromwich contour inversion integral.\\n\\n        .. math ::\\n\\n            p_k = \\\\frac{\\\\gamma}{2 t} + \\\\frac{\\\\pi i k}{t} \\\\qquad 0 \\\\le k < M\\n\\n        where\\n\\n        .. math ::\\n\\n            \\\\gamma = \\\\frac{2}{3} (d + \\\\log(10) + \\\\log(2 t)),\\n\\n        `d = \\\\mathrm{dps\\\\_goal}`, which is chosen based on the desired\\n        accuracy using the method developed in [1] to improve numerical\\n        stability. The Cohen algorithm shows robustness similar to the de Hoog\\n        et al. algorithm, but it is faster than the fixed Talbot algorithm.\\n\\n        **Optional arguments**\\n\\n        *degree*\\n            integer order of the approximation (M = number of terms)\\n        *alpha*\\n            abscissa for `p_0` (controls the discretization error)\\n\\n        The working precision will be increased according to a rule of\\n        thumb. If 'degree' is not specified, the working precision and\\n        degree are chosen to hopefully achieve the dps of the calling\\n        context. If 'degree' is specified, the working precision is\\n        chosen to achieve maximum resulting precision for the\\n        specified degree.\\n\\n        **References**\\n\\n        1. P. Glasserman, J. Ruiz-Mata (2006). Computing the credit loss\\n        distribution in the Gaussian copula model: a comparison of methods.\\n        *Journal of Credit Risk* 2(4):33-66, 10.21314/JCR.2006.057\\n\\n        \\\"\\\"\\\"\\n        self.t = self.ctx.convert(t)\\n\\n        if 'degree' in kwargs:\\n            self.degree = kwargs['degree']\\n            self.dps_goal = int(1.5 * self.degree)\\n        else:\\n            self.dps_goal = int(self.ctx.dps * 1.74)\\n            self.degree = max(22, int(1.31 * self.dps_goal))\\n\\n        M = self.degree + 1\\n\\n        # this is adjusting the dps of the calling context hopefully\\n        # the caller doesn't monkey around with it between calling\\n        # this routine and calc_time_domain_solution()\\n        self.dps_orig = self.ctx.dps\\n        self.ctx.dps = self.dps_goal\\n\\n        ttwo = 2 * self.t\\n        tmp = self.ctx.dps * self.ctx.log(10) + self.ctx.log(ttwo)\\n        tmp = self.ctx.fraction(2, 3) * tmp\\n        self.alpha = self.ctx.convert(kwargs.get('alpha', tmp))\\n\\n        # all but time-dependent part of p\\n        a_t = self.alpha / ttwo\\n        p_t = self.ctx.pi * 1j / self.t\\n\\n        self.p = self.ctx.matrix(M, 1)\\n        self.p[0] = a_t\\n\\n        for i in range(1, M):\\n            self.p[i] = a_t + i * p_t\\n\\n    def calc_time_domain_solution(self, fp, t, manual_prec=False):\\n        r\\\"\\\"\\\"Calculate time-domain solution for Cohen algorithm.\\n\\n        The accelerated nearly alternating series is:\\n\\n        .. math ::\\n\\n            f(t, M) = \\\\frac{e^{\\\\gamma / 2}}{t} \\\\left[\\\\frac{1}{2}\\n            \\\\Re\\\\left(\\\\bar{f}\\\\left(\\\\frac{\\\\gamma}{2t}\\\\right) \\\\right) -\\n            \\\\sum_{k=0}^{M-1}\\\\frac{c_{M,k}}{d_M}\\\\Re\\\\left(\\\\bar{f}\\n            \\\\left(\\\\frac{\\\\gamma + 2(k+1) \\\\pi i}{2t}\\\\right)\\\\right)\\\\right],\\n\\n        where coefficients `\\\\frac{c_{M, k}}{d_M}` are described in [1].\\n\\n        1. H. Cohen, F. Rodriguez Villegas, D. Zagier (2000). Convergence\\n        acceleration of alternating series. *Experiment. Math* 9(1):3-12\\n\\n        \\\"\\\"\\\"\\n        self.t = self.ctx.convert(t)\\n\\n        n = self.degree\\n        M = n + 1\\n\\n        A = self.ctx.matrix(M, 1)\\n        for i in range(M):\\n            A[i] = fp[i].real\\n\\n        d = (3 + self.ctx.sqrt(8)) ** n\\n        d = (d + 1 / d) / 2\\n        b = -self.ctx.one\\n        c = -d\\n        s = 0\\n\\n        for k in range(n):\\n            c = b - c\\n            s = s + c * A[k + 1]\\n            b = 2 * (k + n) * (k - n) * b / ((2 * k + 1) * (k + self.ctx.one))\\n\\n        result = self.ctx.exp(self.alpha / 2) / self.t * (A[0] / 2 - s / d)\\n\\n        # setting dps back to value when calc_laplace_parameter was\\n        # called, unless flag is set.\\n        if not manual_prec:\\n            self.ctx.dps = self.dps_orig\\n\\n        return result\\n\\n\\n# ****************************************\\n\\nclass LaplaceTransformInversionMethods(object):\\n    def __init__(ctx, *args, **kwargs):\\n        ctx._fixed_talbot = FixedTalbot(ctx)\\n        ctx._stehfest = Stehfest(ctx)\\n        ctx._de_hoog = deHoog(ctx)\\n        ctx._cohen = Cohen(ctx)\\n\\n    def invertlaplace(ctx, f, t, **kwargs):\\n        r\\\"\\\"\\\"Computes the numerical inverse Laplace transform for a\\n        Laplace-space function at a given time.  The function being\\n        evaluated is assumed to be a real-valued function of time.\\n\\n        The user must supply a Laplace-space function `\\\\bar{f}(p)`,\\n        and a desired time at which to estimate the time-domain\\n        solution `f(t)`.\\n\\n        A few basic examples of Laplace-space functions with known\\n        inverses (see references [1,2]) :\\n\\n        .. math ::\\n\\n            \\\\mathcal{L}\\\\left\\\\lbrace f(t) \\\\right\\\\rbrace=\\\\bar{f}(p)\\n\\n        .. math ::\\n\\n            \\\\mathcal{L}^{-1}\\\\left\\\\lbrace \\\\bar{f}(p) \\\\right\\\\rbrace = f(t)\\n\\n        .. math ::\\n\\n            \\\\bar{f}(p) = \\\\frac{1}{(p+1)^2}\\n\\n        .. math ::\\n\\n            f(t) = t e^{-t}\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> tt = [0.001, 0.01, 0.1, 1, 10]\\n        >>> fp = lambda p: 1/(p+1)**2\\n        >>> ft = lambda t: t*exp(-t)\\n        >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='talbot')\\n        (0.000999000499833375, 8.57923043561212e-20)\\n        >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='talbot')\\n        (0.00990049833749168, 3.27007646698047e-19)\\n        >>> ft(tt[2]),ft(tt[2])-invertlaplace(fp,tt[2],method='talbot')\\n        (0.090483741803596, -1.75215800052168e-18)\\n        >>> ft(tt[3]),ft(tt[3])-invertlaplace(fp,tt[3],method='talbot')\\n        (0.367879441171442, 1.2428864009344e-17)\\n        >>> ft(tt[4]),ft(tt[4])-invertlaplace(fp,tt[4],method='talbot')\\n        (0.000453999297624849, 4.04513489306658e-20)\\n\\n        The methods also work for higher precision:\\n\\n        >>> mp.dps = 100; mp.pretty = True\\n        >>> nstr(ft(tt[0]),15),nstr(ft(tt[0])-invertlaplace(fp,tt[0],method='talbot'),15)\\n        ('0.000999000499833375', '-4.96868310693356e-105')\\n        >>> nstr(ft(tt[1]),15),nstr(ft(tt[1])-invertlaplace(fp,tt[1],method='talbot'),15)\\n        ('0.00990049833749168', '1.23032291513122e-104')\\n\\n        .. math ::\\n\\n            \\\\bar{f}(p) = \\\\frac{1}{p^2+1}\\n\\n        .. math ::\\n\\n            f(t) = \\\\mathrm{J}_0(t)\\n\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> fp = lambda p: 1/sqrt(p*p + 1)\\n        >>> ft = lambda t: besselj(0,t)\\n        >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='dehoog')\\n        (0.999999750000016, -6.09717765032273e-18)\\n        >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='dehoog')\\n        (0.99997500015625, -5.61756281076169e-17)\\n\\n        .. math ::\\n\\n            \\\\bar{f}(p) = \\\\frac{\\\\log p}{p}\\n\\n        .. math ::\\n\\n            f(t) = -\\\\gamma -\\\\log t\\n\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> fp = lambda p: log(p)/p\\n        >>> ft = lambda t: -euler-log(t)\\n        >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='stehfest')\\n        (6.3305396140806, -1.92126634837863e-16)\\n        >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='stehfest')\\n        (4.02795452108656, -4.81486093200704e-16)\\n\\n        **Options**\\n\\n        :func:`~mpmath.invertlaplace` recognizes the following optional\\n        keywords valid for all methods:\\n\\n        *method*\\n            Chooses numerical inverse Laplace transform algorithm\\n            (described below).\\n        *degree*\\n            Number of terms used in the approximation\\n\\n        **Algorithms**\\n\\n        Mpmath implements four numerical inverse Laplace transform\\n        algorithms, attributed to: Talbot, Stehfest, and de Hoog,\\n        Knight and Stokes. These can be selected by using\\n        *method='talbot'*, *method='stehfest'*, *method='dehoog'* or\\n        *method='cohen'* or by passing the classes *method=FixedTalbot*,\\n        *method=Stehfest*, *method=deHoog*, or *method=Cohen*. The functions\\n        :func:`~mpmath.invlaptalbot`, :func:`~mpmath.invlapstehfest`,\\n        :func:`~mpmath.invlapdehoog`, and :func:`~mpmath.invlapcohen`\\n        are also available as shortcuts.\\n\\n        All four algorithms implement a heuristic balance between the\\n        requested precision and the precision used internally for the\\n        calculations. This has been tuned for a typical exponentially\\n        decaying function and precision up to few hundred decimal\\n        digits.\\n\\n        The Laplace transform converts the variable time (i.e., along\\n        a line) into a parameter given by the right half of the\\n        complex `p`-plane.  Singularities, poles, and branch cuts in\\n        the complex `p`-plane contain all the information regarding\\n        the time behavior of the corresponding function. Any numerical\\n        method must therefore sample `p`-plane \\\"close enough\\\" to the\\n        singularities to accurately characterize them, while not\\n        getting too close to have catastrophic cancellation, overflow,\\n        or underflow issues. Most significantly, if one or more of the\\n        singularities in the `p`-plane is not on the left side of the\\n        Bromwich contour, its effects will be left out of the computed\\n        solution, and the answer will be completely wrong.\\n\\n        *Talbot*\\n\\n        The fixed Talbot method is high accuracy and fast, but the\\n        method can catastrophically fail for certain classes of time-domain\\n        behavior, including a Heaviside step function for positive\\n        time (e.g., `H(t-2)`), or some oscillatory behaviors. The\\n        Talbot method usually has adjustable parameters, but the\\n        \\\"fixed\\\" variety implemented here does not. This method\\n        deforms the Bromwich integral contour in the shape of a\\n        parabola towards `-\\\\infty`, which leads to problems\\n        when the solution has a decaying exponential in it (e.g., a\\n        Heaviside step function is equivalent to multiplying by a\\n        decaying exponential in Laplace space).\\n\\n        *Stehfest*\\n\\n        The Stehfest algorithm only uses abscissa along the real axis\\n        of the complex `p`-plane to estimate the time-domain\\n        function. Oscillatory time-domain functions have poles away\\n        from the real axis, so this method does not work well with\\n        oscillatory functions, especially high-frequency ones. This\\n        method also depends on summation of terms in a series that\\n        grows very large, and will have catastrophic cancellation\\n        during summation if the working precision is too low.\\n\\n        *de Hoog et al.*\\n\\n        The de Hoog, Knight, and Stokes method is essentially a\\n        Fourier-series quadrature-type approximation to the Bromwich\\n        contour integral, with non-linear series acceleration and an\\n        analytical expression for the remainder term. This method is\\n        typically one of the most robust. This method also involves the\\n        greatest amount of overhead, so it is typically the slowest of the\\n        four methods at high precision.\\n\\n        *Cohen*\\n\\n        The Cohen method is a trapezoidal rule approximation to the Bromwich\\n        contour integral, with linear acceleration for alternating\\n        series. This method is as robust as the de Hoog et al method and the\\n        fastest of the four methods at high precision, and is therefore the\\n        default method.\\n\\n        **Singularities**\\n\\n        All numerical inverse Laplace transform methods have problems\\n        at large time when the Laplace-space function has poles,\\n        singularities, or branch cuts to the right of the origin in\\n        the complex plane. For simple poles in `\\\\bar{f}(p)` at the\\n        `p`-plane origin, the time function is constant in time (e.g.,\\n        `\\\\mathcal{L}\\\\left\\\\lbrace 1 \\\\right\\\\rbrace=1/p` has a pole at\\n        `p=0`). A pole in `\\\\bar{f}(p)` to the left of the origin is a\\n        decreasing function of time (e.g., `\\\\mathcal{L}\\\\left\\\\lbrace\\n        e^{-t/2} \\\\right\\\\rbrace=1/(p+1/2)` has a pole at `p=-1/2`), and\\n        a pole to the right of the origin leads to an increasing\\n        function in time (e.g., `\\\\mathcal{L}\\\\left\\\\lbrace t e^{t/4}\\n        \\\\right\\\\rbrace = 1/(p-1/4)^2` has a pole at `p=1/4`).  When\\n        singularities occur off the real `p` axis, the time-domain\\n        function is oscillatory. For example `\\\\mathcal{L}\\\\left\\\\lbrace\\n        \\\\mathrm{J}_0(t) \\\\right\\\\rbrace=1/\\\\sqrt{p^2+1}` has a branch cut\\n        starting at `p=j=\\\\sqrt{-1}` and is a decaying oscillatory\\n        function, This range of behaviors is illustrated in Duffy [3]\\n        Figure 4.10.4, p. 228.\\n\\n        In general as `p \\\\rightarrow \\\\infty` `t \\\\rightarrow 0` and\\n        vice-versa. All numerical inverse Laplace transform methods\\n        require their abscissa to shift closer to the origin for\\n        larger times. If the abscissa shift left of the rightmost\\n        singularity in the Laplace domain, the answer will be\\n        completely wrong (the effect of singularities to the right of\\n        the Bromwich contour are not included in the results).\\n\\n        For example, the following exponentially growing function has\\n        a pole at `p=3`:\\n\\n        .. math ::\\n\\n            \\\\bar{f}(p)=\\\\frac{1}{p^2-9}\\n\\n        .. math ::\\n\\n            f(t)=\\\\frac{1}{3}\\\\sinh 3t\\n\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> fp = lambda p: 1/(p*p-9)\\n        >>> ft = lambda t: sinh(3*t)/3\\n        >>> tt = [0.01,0.1,1.0,10.0]\\n        >>> ft(tt[0]),invertlaplace(fp,tt[0],method='talbot')\\n        (0.0100015000675014, 0.0100015000675014)\\n        >>> ft(tt[1]),invertlaplace(fp,tt[1],method='talbot')\\n        (0.101506764482381, 0.101506764482381)\\n        >>> ft(tt[2]),invertlaplace(fp,tt[2],method='talbot')\\n        (3.33929164246997, 3.33929164246997)\\n        >>> ft(tt[3]),invertlaplace(fp,tt[3],method='talbot')\\n        (1781079096920.74, -1.61331069624091e-14)\\n\\n        **References**\\n\\n        1. [DLMF]_ section 1.14 (http://dlmf.nist.gov/1.14T4)\\n        2. Cohen, A.M. (2007). Numerical Methods for Laplace Transform\\n           Inversion, Springer.\\n        3. Duffy, D.G. (1998). Advanced Engineering Mathematics, CRC Press.\\n\\n        **Numerical Inverse Laplace Transform Reviews**\\n\\n        1. Bellman, R., R.E. Kalaba, J.A. Lockett (1966). *Numerical\\n           inversion of the Laplace transform: Applications to Biology,\\n           Economics, Engineering, and Physics*. Elsevier.\\n        2. Davies, B., B. Martin (1979). Numerical inversion of the\\n           Laplace transform: a survey and comparison of methods. *Journal\\n           of Computational Physics* 33:1-32,\\n           http://dx.doi.org/10.1016/0021-9991(79)90025-1\\n        3. Duffy, D.G. (1993). On the numerical inversion of Laplace\\n           transforms: Comparison of three new methods on characteristic\\n           problems from applications. *ACM Transactions on Mathematical\\n           Software* 19(3):333-359, http://dx.doi.org/10.1145/155743.155788\\n        4. Kuhlman, K.L., (2013). Review of Inverse Laplace Transform\\n           Algorithms for Laplace-Space Numerical Approaches, *Numerical\\n           Algorithms*, 63(2):339-355.\\n           http://dx.doi.org/10.1007/s11075-012-9625-3\\n\\n        \\\"\\\"\\\"\\n\\n        rule = kwargs.get('method', 'cohen')\\n        if type(rule) is str:\\n            lrule = rule.lower()\\n            if lrule == 'talbot':\\n                rule = ctx._fixed_talbot\\n            elif lrule == 'stehfest':\\n                rule = ctx._stehfest\\n            elif lrule == 'dehoog':\\n                rule = ctx._de_hoog\\n            elif rule == 'cohen':\\n                rule = ctx._cohen\\n            else:\\n                raise ValueError(\\\"unknown invlap algorithm: %s\\\" % rule)\\n        else:\\n            rule = rule(ctx)\\n\\n        # determine the vector of Laplace-space parameter\\n        # needed for the requested method and desired time\\n        rule.calc_laplace_parameter(t, **kwargs)\\n\\n        # compute the Laplace-space function evalutations\\n        # at the required abscissa.\\n        fp = [f(p) for p in rule.p]\\n\\n        # compute the time-domain solution from the\\n        # Laplace-space function evaluations\\n        return rule.calc_time_domain_solution(fp, t)\\n\\n    # shortcuts for the above function for specific methods\\n    def invlaptalbot(ctx, *args, **kwargs):\\n        kwargs['method'] = 'talbot'\\n        return ctx.invertlaplace(*args, **kwargs)\\n\\n    def invlapstehfest(ctx, *args, **kwargs):\\n        kwargs['method'] = 'stehfest'\\n        return ctx.invertlaplace(*args, **kwargs)\\n\\n    def invlapdehoog(ctx, *args, **kwargs):\\n        kwargs['method'] = 'dehoog'\\n        return ctx.invertlaplace(*args, **kwargs)\\n\\n    def invlapcohen(ctx, *args, **kwargs):\\n        kwargs['method'] = 'cohen'\\n        return ctx.invertlaplace(*args, **kwargs)\\n\\n\\n# ****************************************\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\nfrom ..libmp.backend import xrange\\nfrom .calculus import defun\\n\\n#----------------------------------------------------------------------------#\\n#                              Approximation methods                         #\\n#----------------------------------------------------------------------------#\\n\\n# The Chebyshev approximation formula is given at:\\n# http://mathworld.wolfram.com/ChebyshevApproximationFormula.html\\n\\n# The only major changes in the following code is that we return the\\n# expanded polynomial coefficients instead of Chebyshev coefficients,\\n# and that we automatically transform [a,b] -> [-1,1] and back\\n# for convenience.\\n\\n# Coefficient in Chebyshev approximation\\ndef chebcoeff(ctx,f,a,b,j,N):\\n    s = ctx.mpf(0)\\n    h = ctx.mpf(0.5)\\n    for k in range(1, N+1):\\n        t = ctx.cospi((k-h)/N)\\n        s += f(t*(b-a)*h + (b+a)*h) * ctx.cospi(j*(k-h)/N)\\n    return 2*s/N\\n\\n# Generate Chebyshev polynomials T_n(ax+b) in expanded form\\ndef chebT(ctx, a=1, b=0):\\n    Tb = [1]\\n    yield Tb\\n    Ta = [b, a]\\n    while 1:\\n        yield Ta\\n        # Recurrence: T[n+1](ax+b) = 2*(ax+b)*T[n](ax+b) - T[n-1](ax+b)\\n        Tmp = [0] + [2*a*t for t in Ta]\\n        for i, c in enumerate(Ta): Tmp[i] += 2*b*c\\n        for i, c in enumerate(Tb): Tmp[i] -= c\\n        Ta, Tb = Tmp, Ta\\n\\n@defun\\ndef chebyfit(ctx, f, interval, N, error=False):\\n    r\\\"\\\"\\\"\\n    Computes a polynomial of degree `N-1` that approximates the\\n    given function `f` on the interval `[a, b]`. With ``error=True``,\\n    :func:`~mpmath.chebyfit` also returns an accurate estimate of the\\n    maximum absolute error; that is, the maximum value of\\n    `|f(x) - P(x)|` for `x \\\\in [a, b]`.\\n\\n    :func:`~mpmath.chebyfit` uses the Chebyshev approximation formula,\\n    which gives a nearly optimal solution: that is, the maximum\\n    error of the approximating polynomial is very close to\\n    the smallest possible for any polynomial of the same degree.\\n\\n    Chebyshev approximation is very useful if one needs repeated\\n    evaluation of an expensive function, such as function defined\\n    implicitly by an integral or a differential equation. (For\\n    example, it could be used to turn a slow mpmath function\\n    into a fast machine-precision version of the same.)\\n\\n    **Examples**\\n\\n    Here we use :func:`~mpmath.chebyfit` to generate a low-degree approximation\\n    of `f(x) = \\\\cos(x)`, valid on the interval `[1, 2]`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> poly, err = chebyfit(cos, [1, 2], 5, error=True)\\n        >>> nprint(poly)\\n        [0.00291682, 0.146166, -0.732491, 0.174141, 0.949553]\\n        >>> nprint(err, 12)\\n        1.61351758081e-5\\n\\n    The polynomial can be evaluated using ``polyval``::\\n\\n        >>> nprint(polyval(poly, 1.6), 12)\\n        -0.0291858904138\\n        >>> nprint(cos(1.6), 12)\\n        -0.0291995223013\\n\\n    Sampling the true error at 1000 points shows that the error\\n    estimate generated by ``chebyfit`` is remarkably good::\\n\\n        >>> error = lambda x: abs(cos(x) - polyval(poly, x))\\n        >>> nprint(max([error(1+n/1000.) for n in range(1000)]), 12)\\n        1.61349954245e-5\\n\\n    **Choice of degree**\\n\\n    The degree `N` can be set arbitrarily high, to obtain an\\n    arbitrarily good approximation. As a rule of thumb, an\\n    `N`-term Chebyshev approximation is good to `N/(b-a)` decimal\\n    places on a unit interval (although this depends on how\\n    well-behaved `f` is). The cost grows accordingly: ``chebyfit``\\n    evaluates the function `(N^2)/2` times to compute the\\n    coefficients and an additional `N` times to estimate the error.\\n\\n    **Possible issues**\\n\\n    One should be careful to use a sufficiently high working\\n    precision both when calling ``chebyfit`` and when evaluating\\n    the resulting polynomial, as the polynomial is sometimes\\n    ill-conditioned. It is for example difficult to reach\\n    15-digit accuracy when evaluating the polynomial using\\n    machine precision floats, no matter the theoretical\\n    accuracy of the polynomial. (The option to return the\\n    coefficients in Chebyshev form should be made available\\n    in the future.)\\n\\n    It is important to note the Chebyshev approximation works\\n    poorly if `f` is not smooth. A function containing singularities,\\n    rapid oscillation, etc can be approximated more effectively by\\n    multiplying it by a weight function that cancels out the\\n    nonsmooth features, or by dividing the interval into several\\n    segments.\\n    \\\"\\\"\\\"\\n    a, b = ctx._as_points(interval)\\n    orig = ctx.prec\\n    try:\\n        ctx.prec = orig + int(N**0.5) + 20\\n        c = [chebcoeff(ctx,f,a,b,k,N) for k in range(N)]\\n        d = [ctx.zero] * N\\n        d[0] = -c[0]/2\\n        h = ctx.mpf(0.5)\\n        T = chebT(ctx, ctx.mpf(2)/(b-a), ctx.mpf(-1)*(b+a)/(b-a))\\n        for (k, Tk) in zip(range(N), T):\\n            for i in range(len(Tk)):\\n                d[i] += c[k]*Tk[i]\\n        d = d[::-1]\\n        # Estimate maximum error\\n        err = ctx.zero\\n        for k in range(N):\\n            x = ctx.cos(ctx.pi*k/N) * (b-a)*h + (b+a)*h\\n            err = max(err, abs(f(x) - ctx.polyval(d, x)))\\n    finally:\\n        ctx.prec = orig\\n    if error:\\n        return d, +err\\n    else:\\n        return d\\n\\n@defun\\ndef fourier(ctx, f, interval, N):\\n    r\\\"\\\"\\\"\\n    Computes the Fourier series of degree `N` of the given function\\n    on the interval `[a, b]`. More precisely, :func:`~mpmath.fourier` returns\\n    two lists `(c, s)` of coefficients (the cosine series and sine\\n    series, respectively), such that\\n\\n    .. math ::\\n\\n        f(x) \\\\sim \\\\sum_{k=0}^N\\n            c_k \\\\cos(k m x) + s_k \\\\sin(k m x)\\n\\n    where `m = 2 \\\\pi / (b-a)`.\\n\\n    Note that many texts define the first coefficient as `2 c_0` instead\\n    of `c_0`. The easiest way to evaluate the computed series correctly\\n    is to pass it to :func:`~mpmath.fourierval`.\\n\\n    **Examples**\\n\\n    The function `f(x) = x` has a simple Fourier series on the standard\\n    interval `[-\\\\pi, \\\\pi]`. The cosine coefficients are all zero (because\\n    the function has odd symmetry), and the sine coefficients are\\n    rational numbers::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> c, s = fourier(lambda x: x, [-pi, pi], 5)\\n        >>> nprint(c)\\n        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\\n        >>> nprint(s)\\n        [0.0, 2.0, -1.0, 0.666667, -0.5, 0.4]\\n\\n    This computes a Fourier series of a nonsymmetric function on\\n    a nonstandard interval::\\n\\n        >>> I = [-1, 1.5]\\n        >>> f = lambda x: x**2 - 4*x + 1\\n        >>> cs = fourier(f, I, 4)\\n        >>> nprint(cs[0])\\n        [0.583333, 1.12479, -1.27552, 0.904708, -0.441296]\\n        >>> nprint(cs[1])\\n        [0.0, -2.6255, 0.580905, 0.219974, -0.540057]\\n\\n    It is instructive to plot a function along with its truncated\\n    Fourier series::\\n\\n        >>> plot([f, lambda x: fourierval(cs, I, x)], I) #doctest: +SKIP\\n\\n    Fourier series generally converge slowly (and may not converge\\n    pointwise). For example, if `f(x) = \\\\cosh(x)`, a 10-term Fourier\\n    series gives an `L^2` error corresponding to 2-digit accuracy::\\n\\n        >>> I = [-1, 1]\\n        >>> cs = fourier(cosh, I, 9)\\n        >>> g = lambda x: (cosh(x) - fourierval(cs, I, x))**2\\n        >>> nprint(sqrt(quad(g, I)))\\n        0.00467963\\n\\n    :func:`~mpmath.fourier` uses numerical quadrature. For nonsmooth functions,\\n    the accuracy (and speed) can be improved by including all singular\\n    points in the interval specification::\\n\\n        >>> nprint(fourier(abs, [-1, 1], 0), 10)\\n        ([0.5000441648], [0.0])\\n        >>> nprint(fourier(abs, [-1, 0, 1], 0), 10)\\n        ([0.5], [0.0])\\n\\n    \\\"\\\"\\\"\\n    interval = ctx._as_points(interval)\\n    a = interval[0]\\n    b = interval[-1]\\n    L = b-a\\n    cos_series = []\\n    sin_series = []\\n    cutoff = ctx.eps*10\\n    for n in xrange(N+1):\\n        m = 2*n*ctx.pi/L\\n        an = 2*ctx.quadgl(lambda t: f(t)*ctx.cos(m*t), interval)/L\\n        bn = 2*ctx.quadgl(lambda t: f(t)*ctx.sin(m*t), interval)/L\\n        if n == 0:\\n            an /= 2\\n        if abs(an) < cutoff: an = ctx.zero\\n        if abs(bn) < cutoff: bn = ctx.zero\\n        cos_series.append(an)\\n        sin_series.append(bn)\\n    return cos_series, sin_series\\n\\n@defun\\ndef fourierval(ctx, series, interval, x):\\n    \\\"\\\"\\\"\\n    Evaluates a Fourier series (in the format computed by\\n    by :func:`~mpmath.fourier` for the given interval) at the point `x`.\\n\\n    The series should be a pair `(c, s)` where `c` is the\\n    cosine series and `s` is the sine series. The two lists\\n    need not have the same length.\\n    \\\"\\\"\\\"\\n    cs, ss = series\\n    ab = ctx._as_points(interval)\\n    a = interval[0]\\n    b = interval[-1]\\n    m = 2*ctx.pi/(ab[-1]-ab[0])\\n    s = ctx.zero\\n    s += ctx.fsum(cs[n]*ctx.cos(m*n*x) for n in xrange(len(cs)) if cs[n])\\n    s += ctx.fsum(ss[n]*ctx.sin(m*n*x) for n in xrange(len(ss)) if ss[n])\\n    return s\\n\\n\\nfrom bisect import bisect\\nfrom ..libmp.backend import xrange\\n\\nclass ODEMethods(object):\\n    pass\\n\\ndef ode_taylor(ctx, derivs, x0, y0, tol_prec, n):\\n    h = tol = ctx.ldexp(1, -tol_prec)\\n    dim = len(y0)\\n    xs = [x0]\\n    ys = [y0]\\n    x = x0\\n    y = y0\\n    orig = ctx.prec\\n    try:\\n        ctx.prec = orig*(1+n)\\n        # Use n steps with Euler's method to get\\n        # evaluation points for derivatives\\n        for i in range(n):\\n            fxy = derivs(x, y)\\n            y = [y[i]+h*fxy[i] for i in xrange(len(y))]\\n            x += h\\n            xs.append(x)\\n            ys.append(y)\\n        # Compute derivatives\\n        ser = [[] for d in range(dim)]\\n        for j in range(n+1):\\n            s = [0]*dim\\n            b = (-1) ** (j & 1)\\n            k = 1\\n            for i in range(j+1):\\n                for d in range(dim):\\n                    s[d] += b * ys[i][d]\\n                b = (b * (j-k+1)) // (-k)\\n                k += 1\\n            scale = h**(-j) / ctx.fac(j)\\n            for d in range(dim):\\n                s[d] = s[d] * scale\\n                ser[d].append(s[d])\\n    finally:\\n        ctx.prec = orig\\n    # Estimate radius for which we can get full accuracy.\\n    # XXX: do this right for zeros\\n    radius = ctx.one\\n    for ts in ser:\\n        if ts[-1]:\\n            radius = min(radius, ctx.nthroot(tol/abs(ts[-1]), n))\\n    radius /= 2  # XXX\\n    return ser, x0+radius\\n\\ndef odefun(ctx, F, x0, y0, tol=None, degree=None, method='taylor', verbose=False):\\n    r\\\"\\\"\\\"\\n    Returns a function `y(x) = [y_0(x), y_1(x), \\\\ldots, y_n(x)]`\\n    that is a numerical solution of the `n+1`-dimensional first-order\\n    ordinary differential equation (ODE) system\\n\\n    .. math ::\\n\\n        y_0'(x) = F_0(x, [y_0(x), y_1(x), \\\\ldots, y_n(x)])\\n\\n        y_1'(x) = F_1(x, [y_0(x), y_1(x), \\\\ldots, y_n(x)])\\n\\n        \\\\vdots\\n\\n        y_n'(x) = F_n(x, [y_0(x), y_1(x), \\\\ldots, y_n(x)])\\n\\n    The derivatives are specified by the vector-valued function\\n    *F* that evaluates\\n    `[y_0', \\\\ldots, y_n'] = F(x, [y_0, \\\\ldots, y_n])`.\\n    The initial point `x_0` is specified by the scalar argument *x0*,\\n    and the initial value `y(x_0) =  [y_0(x_0), \\\\ldots, y_n(x_0)]` is\\n    specified by the vector argument *y0*.\\n\\n    For convenience, if the system is one-dimensional, you may optionally\\n    provide just a scalar value for *y0*. In this case, *F* should accept\\n    a scalar *y* argument and return a scalar. The solution function\\n    *y* will return scalar values instead of length-1 vectors.\\n\\n    Evaluation of the solution function `y(x)` is permitted\\n    for any `x \\\\ge x_0`.\\n\\n    A high-order ODE can be solved by transforming it into first-order\\n    vector form. This transformation is described in standard texts\\n    on ODEs. Examples will also be given below.\\n\\n    **Options, speed and accuracy**\\n\\n    By default, :func:`~mpmath.odefun` uses a high-order Taylor series\\n    method. For reasonably well-behaved problems, the solution will\\n    be fully accurate to within the working precision. Note that\\n    *F* must be possible to evaluate to very high precision\\n    for the generation of Taylor series to work.\\n\\n    To get a faster but less accurate solution, you can set a large\\n    value for *tol* (which defaults roughly to *eps*). If you just\\n    want to plot the solution or perform a basic simulation,\\n    *tol = 0.01* is likely sufficient.\\n\\n    The *degree* argument controls the degree of the solver (with\\n    *method='taylor'*, this is the degree of the Taylor series\\n    expansion). A higher degree means that a longer step can be taken\\n    before a new local solution must be generated from *F*,\\n    meaning that fewer steps are required to get from `x_0` to a given\\n    `x_1`. On the other hand, a higher degree also means that each\\n    local solution becomes more expensive (i.e., more evaluations of\\n    *F* are required per step, and at higher precision).\\n\\n    The optimal setting therefore involves a tradeoff. Generally,\\n    decreasing the *degree* for Taylor series is likely to give faster\\n    solution at low precision, while increasing is likely to be better\\n    at higher precision.\\n\\n    The function\\n    object returned by :func:`~mpmath.odefun` caches the solutions at all step\\n    points and uses polynomial interpolation between step points.\\n    Therefore, once `y(x_1)` has been evaluated for some `x_1`,\\n    `y(x)` can be evaluated very quickly for any `x_0 \\\\le x \\\\le x_1`.\\n    and continuing the evaluation up to `x_2 > x_1` is also fast.\\n\\n    **Examples of first-order ODEs**\\n\\n    We will solve the standard test problem `y'(x) = y(x), y(0) = 1`\\n    which has explicit solution `y(x) = \\\\exp(x)`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> f = odefun(lambda x, y: y, 0, 1)\\n        >>> for x in [0, 1, 2.5]:\\n        ...     print((f(x), exp(x)))\\n        ...\\n        (1.0, 1.0)\\n        (2.71828182845905, 2.71828182845905)\\n        (12.1824939607035, 12.1824939607035)\\n\\n    The solution with high precision::\\n\\n        >>> mp.dps = 50\\n        >>> f = odefun(lambda x, y: y, 0, 1)\\n        >>> f(1)\\n        2.7182818284590452353602874713526624977572470937\\n        >>> exp(1)\\n        2.7182818284590452353602874713526624977572470937\\n\\n    Using the more general vectorized form, the test problem\\n    can be input as (note that *f* returns a 1-element vector)::\\n\\n        >>> mp.dps = 15\\n        >>> f = odefun(lambda x, y: [y[0]], 0, [1])\\n        >>> f(1)\\n        [2.71828182845905]\\n\\n    :func:`~mpmath.odefun` can solve nonlinear ODEs, which are generally\\n    impossible (and at best difficult) to solve analytically. As\\n    an example of a nonlinear ODE, we will solve `y'(x) = x \\\\sin(y(x))`\\n    for `y(0) = \\\\pi/2`. An exact solution happens to be known\\n    for this problem, and is given by\\n    `y(x) = 2 \\\\tan^{-1}\\\\left(\\\\exp\\\\left(x^2/2\\\\right)\\\\right)`::\\n\\n        >>> f = odefun(lambda x, y: x*sin(y), 0, pi/2)\\n        >>> for x in [2, 5, 10]:\\n        ...     print((f(x), 2*atan(exp(mpf(x)**2/2))))\\n        ...\\n        (2.87255666284091, 2.87255666284091)\\n        (3.14158520028345, 3.14158520028345)\\n        (3.14159265358979, 3.14159265358979)\\n\\n    If `F` is independent of `y`, an ODE can be solved using direct\\n    integration. We can therefore obtain a reference solution with\\n    :func:`~mpmath.quad`::\\n\\n        >>> f = lambda x: (1+x**2)/(1+x**3)\\n        >>> g = odefun(lambda x, y: f(x), pi, 0)\\n        >>> g(2*pi)\\n        0.72128263801696\\n        >>> quad(f, [pi, 2*pi])\\n        0.72128263801696\\n\\n    **Examples of second-order ODEs**\\n\\n    We will solve the harmonic oscillator equation `y''(x) + y(x) = 0`.\\n    To do this, we introduce the helper functions `y_0 = y, y_1 = y_0'`\\n    whereby the original equation can be written as `y_1' + y_0' = 0`. Put\\n    together, we get the first-order, two-dimensional vector ODE\\n\\n    .. math ::\\n\\n        \\\\begin{cases}\\n        y_0' = y_1 \\\\\\\\\\n        y_1' = -y_0\\n        \\\\end{cases}\\n\\n    To get a well-defined IVP, we need two initial values. With\\n    `y(0) = y_0(0) = 1` and `-y'(0) = y_1(0) = 0`, the problem will of\\n    course be solved by `y(x) = y_0(x) = \\\\cos(x)` and\\n    `-y'(x) = y_1(x) = \\\\sin(x)`. We check this::\\n\\n        >>> f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0])\\n        >>> for x in [0, 1, 2.5, 10]:\\n        ...     nprint(f(x), 15)\\n        ...     nprint([cos(x), sin(x)], 15)\\n        ...     print(\\\"---\\\")\\n        ...\\n        [1.0, 0.0]\\n        [1.0, 0.0]\\n        ---\\n        [0.54030230586814, 0.841470984807897]\\n        [0.54030230586814, 0.841470984807897]\\n        ---\\n        [-0.801143615546934, 0.598472144103957]\\n        [-0.801143615546934, 0.598472144103957]\\n        ---\\n        [-0.839071529076452, -0.54402111088937]\\n        [-0.839071529076452, -0.54402111088937]\\n        ---\\n\\n    Note that we get both the sine and the cosine solutions\\n    simultaneously.\\n\\n    **TODO**\\n\\n    * Better automatic choice of degree and step size\\n    * Make determination of Taylor series convergence radius\\n      more robust\\n    * Allow solution for `x < x_0`\\n    * Allow solution for complex `x`\\n    * Test for difficult (ill-conditioned) problems\\n    * Implement Runge-Kutta and other algorithms\\n\\n    \\\"\\\"\\\"\\n    if tol:\\n        tol_prec = int(-ctx.log(tol, 2))+10\\n    else:\\n        tol_prec = ctx.prec+10\\n    degree = degree or (3 + int(3*ctx.dps/2.))\\n    workprec = ctx.prec + 40\\n    try:\\n        len(y0)\\n        return_vector = True\\n    except TypeError:\\n        F_ = F\\n        F = lambda x, y: [F_(x, y[0])]\\n        y0 = [y0]\\n        return_vector = False\\n    ser, xb = ode_taylor(ctx, F, x0, y0, tol_prec, degree)\\n    series_boundaries = [x0, xb]\\n    series_data = [(ser, x0, xb)]\\n    # We will be working with vectors of Taylor series\\n    def mpolyval(ser, a):\\n        return [ctx.polyval(s[::-1], a) for s in ser]\\n    # Find nearest expansion point; compute if necessary\\n    def get_series(x):\\n        if x < x0:\\n            raise ValueError\\n        n = bisect(series_boundaries, x)\\n        if n < len(series_boundaries):\\n            return series_data[n-1]\\n        while 1:\\n            ser, xa, xb = series_data[-1]\\n            if verbose:\\n                print(\\\"Computing Taylor series for [%f, %f]\\\" % (xa, xb))\\n            y = mpolyval(ser, xb-xa)\\n            xa = xb\\n            ser, xb = ode_taylor(ctx, F, xb, y, tol_prec, degree)\\n            series_boundaries.append(xb)\\n            series_data.append((ser, xa, xb))\\n            if x <= xb:\\n                return series_data[-1]\\n    # Evaluation function\\n    def interpolant(x):\\n        x = ctx.convert(x)\\n        orig = ctx.prec\\n        try:\\n            ctx.prec = workprec\\n            ser, xa, xb = get_series(x)\\n            y = mpolyval(ser, x-xa)\\n        finally:\\n            ctx.prec = orig\\n        if return_vector:\\n            return [+yk for yk in y]\\n        else:\\n            return +y[0]\\n    return interpolant\\n\\nODEMethods.odefun = odefun\\n\\nif __name__ == \\\"__main__\\\":\\n    import doctest\\n    doctest.testmod()\\n\\n\\nfrom ..libmp.backend import xrange\\nfrom .calculus import defun\\n\\ntry:\\n    iteritems = dict.iteritems\\nexcept AttributeError:\\n    iteritems = dict.items\\n\\n#----------------------------------------------------------------------------#\\n#                                Differentiation                             #\\n#----------------------------------------------------------------------------#\\n\\n@defun\\ndef difference(ctx, s, n):\\n    r\\\"\\\"\\\"\\n    Given a sequence `(s_k)` containing at least `n+1` items, returns the\\n    `n`-th forward difference,\\n\\n    .. math ::\\n\\n        \\\\Delta^n = \\\\sum_{k=0}^{\\\\infty} (-1)^{k+n} {n \\\\choose k} s_k.\\n    \\\"\\\"\\\"\\n    n = int(n)\\n    d = ctx.zero\\n    b = (-1) ** (n & 1)\\n    for k in xrange(n+1):\\n        d += b * s[k]\\n        b = (b * (k-n)) // (k+1)\\n    return d\\n\\ndef hsteps(ctx, f, x, n, prec, **options):\\n    singular = options.get('singular')\\n    addprec = options.get('addprec', 10)\\n    direction = options.get('direction', 0)\\n    workprec = (prec+2*addprec) * (n+1)\\n    orig = ctx.prec\\n    try:\\n        ctx.prec = workprec\\n        h = options.get('h')\\n        if h is None:\\n            if options.get('relative'):\\n                hextramag = int(ctx.mag(x))\\n            else:\\n                hextramag = 0\\n            h = ctx.ldexp(1, -prec-addprec-hextramag)\\n        else:\\n            h = ctx.convert(h)\\n        # Directed: steps x, x+h, ... x+n*h\\n        direction = options.get('direction', 0)\\n        if direction:\\n            h *= ctx.sign(direction)\\n            steps = xrange(n+1)\\n            norm = h\\n        # Central: steps x-n*h, x-(n-2)*h ..., x, ..., x+(n-2)*h, x+n*h\\n        else:\\n            steps = xrange(-n, n+1, 2)\\n            norm = (2*h)\\n        # Perturb\\n        if singular:\\n            x += 0.5*h\\n        values = [f(x+k*h) for k in steps]\\n        return values, norm, workprec\\n    finally:\\n        ctx.prec = orig\\n\\n\\n@defun\\ndef diff(ctx, f, x, n=1, **options):\\n    r\\\"\\\"\\\"\\n    Numerically computes the derivative of `f`, `f'(x)`, or generally for\\n    an integer `n \\\\ge 0`, the `n`-th derivative `f^{(n)}(x)`.\\n    A few basic examples are::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> diff(lambda x: x**2 + x, 1.0)\\n        3.0\\n        >>> diff(lambda x: x**2 + x, 1.0, 2)\\n        2.0\\n        >>> diff(lambda x: x**2 + x, 1.0, 3)\\n        0.0\\n        >>> nprint([diff(exp, 3, n) for n in range(5)])   # exp'(x) = exp(x)\\n        [20.0855, 20.0855, 20.0855, 20.0855, 20.0855]\\n\\n    Even more generally, given a tuple of arguments `(x_1, \\\\ldots, x_k)`\\n    and order `(n_1, \\\\ldots, n_k)`, the partial derivative\\n    `f^{(n_1,\\\\ldots,n_k)}(x_1,\\\\ldots,x_k)` is evaluated. For example::\\n\\n        >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (0,1))\\n        2.75\\n        >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (1,1))\\n        3.0\\n\\n    **Options**\\n\\n    The following optional keyword arguments are recognized:\\n\\n    ``method``\\n        Supported methods are ``'step'`` or ``'quad'``: derivatives may be\\n        computed using either a finite difference with a small step\\n        size `h` (default), or numerical quadrature.\\n    ``direction``\\n        Direction of finite difference: can be -1 for a left\\n        difference, 0 for a central difference (default), or +1\\n        for a right difference; more generally can be any complex number.\\n    ``addprec``\\n        Extra precision for `h` used to account for the function's\\n        sensitivity to perturbations (default = 10).\\n    ``relative``\\n        Choose `h` relative to the magnitude of `x`, rather than an\\n        absolute value; useful for large or tiny `x` (default = False).\\n    ``h``\\n        As an alternative to ``addprec`` and ``relative``, manually\\n        select the step size `h`.\\n    ``singular``\\n        If True, evaluation exactly at the point `x` is avoided; this is\\n        useful for differentiating functions with removable singularities.\\n        Default = False.\\n    ``radius``\\n        Radius of integration contour (with ``method = 'quad'``).\\n        Default = 0.25. A larger radius typically is faster and more\\n        accurate, but it must be chosen so that `f` has no\\n        singularities within the radius from the evaluation point.\\n\\n    A finite difference requires `n+1` function evaluations and must be\\n    performed at `(n+1)` times the target precision. Accordingly, `f` must\\n    support fast evaluation at high precision.\\n\\n    With integration, a larger number of function evaluations is\\n    required, but not much extra precision is required. For high order\\n    derivatives, this method may thus be faster if f is very expensive to\\n    evaluate at high precision.\\n\\n    **Further examples**\\n\\n    The direction option is useful for computing left- or right-sided\\n    derivatives of nonsmooth functions::\\n\\n        >>> diff(abs, 0, direction=0)\\n        0.0\\n        >>> diff(abs, 0, direction=1)\\n        1.0\\n        >>> diff(abs, 0, direction=-1)\\n        -1.0\\n\\n    More generally, if the direction is nonzero, a right difference\\n    is computed where the step size is multiplied by sign(direction).\\n    For example, with direction=+j, the derivative from the positive\\n    imaginary direction will be computed::\\n\\n        >>> diff(abs, 0, direction=j)\\n        (0.0 - 1.0j)\\n\\n    With integration, the result may have a small imaginary part\\n    even even if the result is purely real::\\n\\n        >>> diff(sqrt, 1, method='quad')    # doctest:+ELLIPSIS\\n        (0.5 - 4.59...e-26j)\\n        >>> chop(_)\\n        0.5\\n\\n    Adding precision to obtain an accurate value::\\n\\n        >>> diff(cos, 1e-30)\\n        0.0\\n        >>> diff(cos, 1e-30, h=0.0001)\\n        -9.99999998328279e-31\\n        >>> diff(cos, 1e-30, addprec=100)\\n        -1.0e-30\\n\\n    \\\"\\\"\\\"\\n    partial = False\\n    try:\\n        orders = list(n)\\n        x = list(x)\\n        partial = True\\n    except TypeError:\\n        pass\\n    if partial:\\n        x = [ctx.convert(_) for _ in x]\\n        return _partial_diff(ctx, f, x, orders, options)\\n    method = options.get('method', 'step')\\n    if n == 0 and method != 'quad' and not options.get('singular'):\\n        return f(ctx.convert(x))\\n    prec = ctx.prec\\n    try:\\n        if method == 'step':\\n            values, norm, workprec = hsteps(ctx, f, x, n, prec, **options)\\n            ctx.prec = workprec\\n            v = ctx.difference(values, n) / norm**n\\n        elif method == 'quad':\\n            ctx.prec += 10\\n            radius = ctx.convert(options.get('radius', 0.25))\\n            def g(t):\\n                rei = radius*ctx.expj(t)\\n                z = x + rei\\n                return f(z) / rei**n\\n            d = ctx.quadts(g, [0, 2*ctx.pi])\\n            v = d * ctx.factorial(n) / (2*ctx.pi)\\n        else:\\n            raise ValueError(\\\"unknown method: %r\\\" % method)\\n    finally:\\n        ctx.prec = prec\\n    return +v\\n\\ndef _partial_diff(ctx, f, xs, orders, options):\\n    if not orders:\\n        return f()\\n    if not sum(orders):\\n        return f(*xs)\\n    i = 0\\n    for i in range(len(orders)):\\n        if orders[i]:\\n            break\\n    order = orders[i]\\n    def fdiff_inner(*f_args):\\n        def inner(t):\\n            return f(*(f_args[:i] + (t,) + f_args[i+1:]))\\n        return ctx.diff(inner, f_args[i], order, **options)\\n    orders[i] = 0\\n    return _partial_diff(ctx, fdiff_inner, xs, orders, options)\\n\\n@defun\\ndef diffs(ctx, f, x, n=None, **options):\\n    r\\\"\\\"\\\"\\n    Returns a generator that yields the sequence of derivatives\\n\\n    .. math ::\\n\\n        f(x), f'(x), f''(x), \\\\ldots, f^{(k)}(x), \\\\ldots\\n\\n    With ``method='step'``, :func:`~mpmath.diffs` uses only `O(k)`\\n    function evaluations to generate the first `k` derivatives,\\n    rather than the roughly `O(k^2)` evaluations\\n    required if one calls :func:`~mpmath.diff` `k` separate times.\\n\\n    With `n < \\\\infty`, the generator stops as soon as the\\n    `n`-th derivative has been generated. If the exact number of\\n    needed derivatives is known in advance, this is further\\n    slightly more efficient.\\n\\n    Options are the same as for :func:`~mpmath.diff`.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15\\n        >>> nprint(list(diffs(cos, 1, 5)))\\n        [0.540302, -0.841471, -0.540302, 0.841471, 0.540302, -0.841471]\\n        >>> for i, d in zip(range(6), diffs(cos, 1)):\\n        ...     print(\\\"%s %s\\\" % (i, d))\\n        ...\\n        0 0.54030230586814\\n        1 -0.841470984807897\\n        2 -0.54030230586814\\n        3 0.841470984807897\\n        4 0.54030230586814\\n        5 -0.841470984807897\\n\\n    \\\"\\\"\\\"\\n    if n is None:\\n        n = ctx.inf\\n    else:\\n        n = int(n)\\n    if options.get('method', 'step') != 'step':\\n        k = 0\\n        while k < n + 1:\\n            yield ctx.diff(f, x, k, **options)\\n            k += 1\\n        return\\n    singular = options.get('singular')\\n    if singular:\\n        yield ctx.diff(f, x, 0, singular=True)\\n    else:\\n        yield f(ctx.convert(x))\\n    if n < 1:\\n        return\\n    if n == ctx.inf:\\n        A, B = 1, 2\\n    else:\\n        A, B = 1, n+1\\n    while 1:\\n        callprec = ctx.prec\\n        y, norm, workprec = hsteps(ctx, f, x, B, callprec, **options)\\n        for k in xrange(A, B):\\n            try:\\n                ctx.prec = workprec\\n                d = ctx.difference(y, k) / norm**k\\n            finally:\\n                ctx.prec = callprec\\n            yield +d\\n            if k >= n:\\n                return\\n        A, B = B, int(A*1.4+1)\\n        B = min(B, n)\\n\\ndef iterable_to_function(gen):\\n    gen = iter(gen)\\n    data = []\\n    def f(k):\\n        for i in xrange(len(data), k+1):\\n            data.append(next(gen))\\n        return data[k]\\n    return f\\n\\n@defun\\ndef diffs_prod(ctx, factors):\\n    r\\\"\\\"\\\"\\n    Given a list of `N` iterables or generators yielding\\n    `f_k(x), f'_k(x), f''_k(x), \\\\ldots` for `k = 1, \\\\ldots, N`,\\n    generate `g(x), g'(x), g''(x), \\\\ldots` where\\n    `g(x) = f_1(x) f_2(x) \\\\cdots f_N(x)`.\\n\\n    At high precision and for large orders, this is typically more efficient\\n    than numerical differentiation if the derivatives of each `f_k(x)`\\n    admit direct computation.\\n\\n    Note: This function does not increase the working precision internally,\\n    so guard digits may have to be added externally for full accuracy.\\n\\n    **Examples**\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> f = lambda x: exp(x)*cos(x)*sin(x)\\n        >>> u = diffs(f, 1)\\n        >>> v = mp.diffs_prod([diffs(exp,1), diffs(cos,1), diffs(sin,1)])\\n        >>> next(u); next(v)\\n        1.23586333600241\\n        1.23586333600241\\n        >>> next(u); next(v)\\n        0.104658952245596\\n        0.104658952245596\\n        >>> next(u); next(v)\\n        -5.96999877552086\\n        -5.96999877552086\\n        >>> next(u); next(v)\\n        -12.4632923122697\\n        -12.4632923122697\\n\\n    \\\"\\\"\\\"\\n    N = len(factors)\\n    if N == 1:\\n        for c in factors[0]:\\n            yield c\\n    else:\\n        u = iterable_to_function(ctx.diffs_prod(factors[:N//2]))\\n        v = iterable_to_function(ctx.diffs_prod(factors[N//2:]))\\n        n = 0\\n        while 1:\\n            #yield sum(binomial(n,k)*u(n-k)*v(k) for k in xrange(n+1))\\n            s = u(n) * v(0)\\n            a = 1\\n            for k in xrange(1,n+1):\\n                a = a * (n-k+1) // k\\n                s += a * u(n-k) * v(k)\\n            yield s\\n            n += 1\\n\\ndef dpoly(n, _cache={}):\\n    \\\"\\\"\\\"\\n    nth differentiation polynomial for exp (Faa di Bruno's formula).\\n\\n    TODO: most exponents are zero, so maybe a sparse representation\\n    would be better.\\n    \\\"\\\"\\\"\\n    if n in _cache:\\n        return _cache[n]\\n    if not _cache:\\n        _cache[0] = {(0,):1}\\n    R = dpoly(n-1)\\n    R = dict((c+(0,),v) for (c,v) in iteritems(R))\\n    Ra = {}\\n    for powers, count in iteritems(R):\\n        powers1 = (powers[0]+1,) + powers[1:]\\n        if powers1 in Ra:\\n            Ra[powers1] += count\\n        else:\\n            Ra[powers1] = count\\n    for powers, count in iteritems(R):\\n        if not sum(powers):\\n            continue\\n        for k,p in enumerate(powers):\\n            if p:\\n                powers2 = powers[:k] + (p-1,powers[k+1]+1) + powers[k+2:]\\n                if powers2 in Ra:\\n                    Ra[powers2] += p*count\\n                else:\\n                    Ra[powers2] = p*count\\n    _cache[n] = Ra\\n    return _cache[n]\\n\\n@defun\\ndef diffs_exp(ctx, fdiffs):\\n    r\\\"\\\"\\\"\\n    Given an iterable or generator yielding `f(x), f'(x), f''(x), \\\\ldots`\\n    generate `g(x), g'(x), g''(x), \\\\ldots` where `g(x) = \\\\exp(f(x))`.\\n\\n    At high precision and for large orders, this is typically more efficient\\n    than numerical differentiation if the derivatives of `f(x)`\\n    admit direct computation.\\n\\n    Note: This function does not increase the working precision internally,\\n    so guard digits may have to be added externally for full accuracy.\\n\\n    **Examples**\\n\\n    The derivatives of the gamma function can be computed using\\n    logarithmic differentiation::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>>\\n        >>> def diffs_loggamma(x):\\n        ...     yield loggamma(x)\\n        ...     i = 0\\n        ...     while 1:\\n        ...         yield psi(i,x)\\n        ...         i += 1\\n        ...\\n        >>> u = diffs_exp(diffs_loggamma(3))\\n        >>> v = diffs(gamma, 3)\\n        >>> next(u); next(v)\\n        2.0\\n        2.0\\n        >>> next(u); next(v)\\n        1.84556867019693\\n        1.84556867019693\\n        >>> next(u); next(v)\\n        2.49292999190269\\n        2.49292999190269\\n        >>> next(u); next(v)\\n        3.44996501352367\\n        3.44996501352367\\n\\n    \\\"\\\"\\\"\\n    fn = iterable_to_function(fdiffs)\\n    f0 = ctx.exp(fn(0))\\n    yield f0\\n    i = 1\\n    while 1:\\n        s = ctx.mpf(0)\\n        for powers, c in iteritems(dpoly(i)):\\n            s += c*ctx.fprod(fn(k+1)**p for (k,p) in enumerate(powers) if p)\\n        yield s * f0\\n        i += 1\\n\\n@defun\\ndef differint(ctx, f, x, n=1, x0=0):\\n    r\\\"\\\"\\\"\\n    Calculates the Riemann-Liouville differintegral, or fractional\\n    derivative, defined by\\n\\n    .. math ::\\n\\n        \\\\,_{x_0}{\\\\mathbb{D}}^n_xf(x) = \\\\frac{1}{\\\\Gamma(m-n)} \\\\frac{d^m}{dx^m}\\n        \\\\int_{x_0}^{x}(x-t)^{m-n-1}f(t)dt\\n\\n    where `f` is a given (presumably well-behaved) function,\\n    `x` is the evaluation point, `n` is the order, and `x_0` is\\n    the reference point of integration (`m` is an arbitrary\\n    parameter selected automatically).\\n\\n    With `n = 1`, this is just the standard derivative `f'(x)`; with `n = 2`,\\n    the second derivative `f''(x)`, etc. With `n = -1`, it gives\\n    `\\\\int_{x_0}^x f(t) dt`, with `n = -2`\\n    it gives `\\\\int_{x_0}^x \\\\left( \\\\int_{x_0}^t f(u) du \\\\right) dt`, etc.\\n\\n    As `n` is permitted to be any number, this operator generalizes\\n    iterated differentiation and iterated integration to a single\\n    operator with a continuous order parameter.\\n\\n    **Examples**\\n\\n    There is an exact formula for the fractional derivative of a\\n    monomial `x^p`, which may be used as a reference. For example,\\n    the following gives a half-derivative (order 0.5)::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> x = mpf(3); p = 2; n = 0.5\\n        >>> differint(lambda t: t**p, x, n)\\n        7.81764019044672\\n        >>> gamma(p+1)/gamma(p-n+1) * x**(p-n)\\n        7.81764019044672\\n\\n    Another useful test function is the exponential function, whose\\n    integration / differentiation formula easy generalizes\\n    to arbitrary order. Here we first compute a third derivative,\\n    and then a triply nested integral. (The reference point `x_0`\\n    is set to `-\\\\infty` to avoid nonzero endpoint terms.)::\\n\\n        >>> differint(lambda x: exp(pi*x), -1.5, 3)\\n        0.278538406900792\\n        >>> exp(pi*-1.5) * pi**3\\n        0.278538406900792\\n        >>> differint(lambda x: exp(pi*x), 3.5, -3, -inf)\\n        1922.50563031149\\n        >>> exp(pi*3.5) / pi**3\\n        1922.50563031149\\n\\n    However, for noninteger `n`, the differentiation formula for the\\n    exponential function must be modified to give the same result as the\\n    Riemann-Liouville differintegral::\\n\\n        >>> x = mpf(3.5)\\n        >>> c = pi\\n        >>> n = 1+2*j\\n        >>> differint(lambda x: exp(c*x), x, n)\\n        (-123295.005390743 + 140955.117867654j)\\n        >>> x**(-n) * exp(c)**x * (x*c)**n * gammainc(-n, 0, x*c) / gamma(-n)\\n        (-123295.005390743 + 140955.117867654j)\\n\\n\\n    \\\"\\\"\\\"\\n    m = max(int(ctx.ceil(ctx.re(n)))+1, 1)\\n    r = m-n-1\\n    g = lambda x: ctx.quad(lambda t: (x-t)**r * f(t), [x0, x])\\n    return ctx.diff(g, x, m) / ctx.gamma(m-n)\\n\\n@defun\\ndef diffun(ctx, f, n=1, **options):\\n    r\\\"\\\"\\\"\\n    Given a function `f`, returns a function `g(x)` that evaluates the nth\\n    derivative `f^{(n)}(x)`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> cos2 = diffun(sin)\\n        >>> sin2 = diffun(sin, 4)\\n        >>> cos(1.3), cos2(1.3)\\n        (0.267498828624587, 0.267498828624587)\\n        >>> sin(1.3), sin2(1.3)\\n        (0.963558185417193, 0.963558185417193)\\n\\n    The function `f` must support arbitrary precision evaluation.\\n    See :func:`~mpmath.diff` for additional details and supported\\n    keyword options.\\n    \\\"\\\"\\\"\\n    if n == 0:\\n        return f\\n    def g(x):\\n        return ctx.diff(f, x, n, **options)\\n    return g\\n\\n@defun\\ndef taylor(ctx, f, x, n, **options):\\n    r\\\"\\\"\\\"\\n    Produces a degree-`n` Taylor polynomial around the point `x` of the\\n    given function `f`. The coefficients are returned as a list.\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> nprint(chop(taylor(sin, 0, 5)))\\n        [0.0, 1.0, 0.0, -0.166667, 0.0, 0.00833333]\\n\\n    The coefficients are computed using high-order numerical\\n    differentiation. The function must be possible to evaluate\\n    to arbitrary precision. See :func:`~mpmath.diff` for additional details\\n    and supported keyword options.\\n\\n    Note that to evaluate the Taylor polynomial as an approximation\\n    of `f`, e.g. with :func:`~mpmath.polyval`, the coefficients must be reversed,\\n    and the point of the Taylor expansion must be subtracted from\\n    the argument:\\n\\n        >>> p = taylor(exp, 2.0, 10)\\n        >>> polyval(p[::-1], 2.5 - 2.0)\\n        12.1824939606092\\n        >>> exp(2.5)\\n        12.1824939607035\\n\\n    \\\"\\\"\\\"\\n    gen = enumerate(ctx.diffs(f, x, n, **options))\\n    if options.get(\\\"chop\\\", True):\\n        return [ctx.chop(d)/ctx.factorial(i) for i, d in gen]\\n    else:\\n        return [d/ctx.factorial(i) for i, d in gen]\\n\\n@defun\\ndef pade(ctx, a, L, M):\\n    r\\\"\\\"\\\"\\n    Computes a Pade approximation of degree `(L, M)` to a function.\\n    Given at least `L+M+1` Taylor coefficients `a` approximating\\n    a function `A(x)`, :func:`~mpmath.pade` returns coefficients of\\n    polynomials `P, Q` satisfying\\n\\n    .. math ::\\n\\n        P = \\\\sum_{k=0}^L p_k x^k\\n\\n        Q = \\\\sum_{k=0}^M q_k x^k\\n\\n        Q_0 = 1\\n\\n        A(x) Q(x) = P(x) + O(x^{L+M+1})\\n\\n    `P(x)/Q(x)` can provide a good approximation to an analytic function\\n    beyond the radius of convergence of its Taylor series (example\\n    from G.A. Baker 'Essentials of Pade Approximants' Academic Press,\\n    Ch.1A)::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> one = mpf(1)\\n        >>> def f(x):\\n        ...     return sqrt((one + 2*x)/(one + x))\\n        ...\\n        >>> a = taylor(f, 0, 6)\\n        >>> p, q = pade(a, 3, 3)\\n        >>> x = 10\\n        >>> polyval(p[::-1], x)/polyval(q[::-1], x)\\n        1.38169105566806\\n        >>> f(x)\\n        1.38169855941551\\n\\n    \\\"\\\"\\\"\\n    # To determine L+1 coefficients of P and M coefficients of Q\\n    # L+M+1 coefficients of A must be provided\\n    if len(a) < L+M+1:\\n        raise ValueError(\\\"L+M+1 Coefficients should be provided\\\")\\n\\n    if M == 0:\\n        if L == 0:\\n            return [ctx.one], [ctx.one]\\n        else:\\n            return a[:L+1], [ctx.one]\\n\\n    # Solve first\\n    # a[L]*q[1] + ... + a[L-M+1]*q[M] = -a[L+1]\\n    # ...\\n    # a[L+M-1]*q[1] + ... + a[L]*q[M] = -a[L+M]\\n    A = ctx.matrix(M)\\n    for j in range(M):\\n        for i in range(min(M, L+j+1)):\\n            A[j, i] = a[L+j-i]\\n    v = -ctx.matrix(a[(L+1):(L+M+1)])\\n    x = ctx.lu_solve(A, v)\\n    q = [ctx.one] + list(x)\\n    # compute p\\n    p = [0]*(L+1)\\n    for i in range(L+1):\\n        s = a[i]\\n        for j in range(1, min(M,i) + 1):\\n            s += q[j]*a[i-j]\\n        p[i] = s\\n    return p, q\\n\\n\\nclass CalculusMethods(object):\\n    pass\\n\\ndef defun(f):\\n    setattr(CalculusMethods, f.__name__, f)\\n    return f\\n\\n\\ntry:\\n    from itertools import izip\\nexcept ImportError:\\n    izip = zip\\n\\nfrom ..libmp.backend import xrange\\nfrom .calculus import defun\\n\\ntry:\\n    next = next\\nexcept NameError:\\n    next = lambda _: _.next()\\n\\n@defun\\ndef richardson(ctx, seq):\\n    r\\\"\\\"\\\"\\n    Given a list ``seq`` of the first `N` elements of a slowly convergent\\n    infinite sequence, :func:`~mpmath.richardson` computes the `N`-term\\n    Richardson extrapolate for the limit.\\n\\n    :func:`~mpmath.richardson` returns `(v, c)` where `v` is the estimated\\n    limit and `c` is the magnitude of the largest weight used during the\\n    computation. The weight provides an estimate of the precision\\n    lost to cancellation. Due to cancellation effects, the sequence must\\n    be typically be computed at a much higher precision than the target\\n    accuracy of the extrapolation.\\n\\n    **Applicability and issues**\\n\\n    The `N`-step Richardson extrapolation algorithm used by\\n    :func:`~mpmath.richardson` is described in [1].\\n\\n    Richardson extrapolation only works for a specific type of sequence,\\n    namely one converging like partial sums of\\n    `P(1)/Q(1) + P(2)/Q(2) + \\\\ldots` where `P` and `Q` are polynomials.\\n    When the sequence does not convergence at such a rate\\n    :func:`~mpmath.richardson` generally produces garbage.\\n\\n    Richardson extrapolation has the advantage of being fast: the `N`-term\\n    extrapolate requires only `O(N)` arithmetic operations, and usually\\n    produces an estimate that is accurate to `O(N)` digits. Contrast with\\n    the Shanks transformation (see :func:`~mpmath.shanks`), which requires\\n    `O(N^2)` operations.\\n\\n    :func:`~mpmath.richardson` is unable to produce an estimate for the\\n    approximation error. One way to estimate the error is to perform\\n    two extrapolations with slightly different `N` and comparing the\\n    results.\\n\\n    Richardson extrapolation does not work for oscillating sequences.\\n    As a simple workaround, :func:`~mpmath.richardson` detects if the last\\n    three elements do not differ monotonically, and in that case\\n    applies extrapolation only to the even-index elements.\\n\\n    **Example**\\n\\n    Applying Richardson extrapolation to the Leibniz series for `\\\\pi`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 30; mp.pretty = True\\n        >>> S = [4*sum(mpf(-1)**n/(2*n+1) for n in range(m))\\n        ...     for m in range(1,30)]\\n        >>> v, c = richardson(S[:10])\\n        >>> v\\n        3.2126984126984126984126984127\\n        >>> nprint([v-pi, c])\\n        [0.0711058, 2.0]\\n\\n        >>> v, c = richardson(S[:30])\\n        >>> v\\n        3.14159265468624052829954206226\\n        >>> nprint([v-pi, c])\\n        [1.09645e-9, 20833.3]\\n\\n    **References**\\n\\n    1. [BenderOrszag]_ pp. 375-376\\n\\n    \\\"\\\"\\\"\\n    if len(seq) < 3:\\n        raise ValueError(\\\"seq should be of minimum length 3\\\")\\n    if ctx.sign(seq[-1]-seq[-2]) != ctx.sign(seq[-2]-seq[-3]):\\n        seq = seq[::2]\\n    N = len(seq)//2-1\\n    s = ctx.zero\\n    # The general weight is c[k] = (N+k)**N * (-1)**(k+N) / k! / (N-k)!\\n    # To avoid repeated factorials, we simplify the quotient\\n    # of successive weights to obtain a recurrence relation\\n    c = (-1)**N * N**N / ctx.mpf(ctx._ifac(N))\\n    maxc = 1\\n    for k in xrange(N+1):\\n        s += c * seq[N+k]\\n        maxc = max(abs(c), maxc)\\n        c *= (k-N)*ctx.mpf(k+N+1)**N\\n        c /= ((1+k)*ctx.mpf(k+N)**N)\\n    return s, maxc\\n\\n@defun\\ndef shanks(ctx, seq, table=None, randomized=False):\\n    r\\\"\\\"\\\"\\n    Given a list ``seq`` of the first `N` elements of a slowly\\n    convergent infinite sequence `(A_k)`, :func:`~mpmath.shanks` computes the iterated\\n    Shanks transformation `S(A), S(S(A)), \\\\ldots, S^{N/2}(A)`. The Shanks\\n    transformation often provides strong convergence acceleration,\\n    especially if the sequence is oscillating.\\n\\n    The iterated Shanks transformation is computed using the Wynn\\n    epsilon algorithm (see [1]). :func:`~mpmath.shanks` returns the full\\n    epsilon table generated by Wynn's algorithm, which can be read\\n    off as follows:\\n\\n    * The table is a list of lists forming a lower triangular matrix,\\n      where higher row and column indices correspond to more accurate\\n      values.\\n    * The columns with even index hold dummy entries (required for the\\n      computation) and the columns with odd index hold the actual\\n      extrapolates.\\n    * The last element in the last row is typically the most\\n      accurate estimate of the limit.\\n    * The difference to the third last element in the last row\\n      provides an estimate of the approximation error.\\n    * The magnitude of the second last element provides an estimate\\n      of the numerical accuracy lost to cancellation.\\n\\n    For convenience, so the extrapolation is stopped at an odd index\\n    so that ``shanks(seq)[-1][-1]`` always gives an estimate of the\\n    limit.\\n\\n    Optionally, an existing table can be passed to :func:`~mpmath.shanks`.\\n    This can be used to efficiently extend a previous computation after\\n    new elements have been appended to the sequence. The table will\\n    then be updated in-place.\\n\\n    **The Shanks transformation**\\n\\n    The Shanks transformation is defined as follows (see [2]): given\\n    the input sequence `(A_0, A_1, \\\\ldots)`, the transformed sequence is\\n    given by\\n\\n    .. math ::\\n\\n        S(A_k) = \\\\frac{A_{k+1}A_{k-1}-A_k^2}{A_{k+1}+A_{k-1}-2 A_k}\\n\\n    The Shanks transformation gives the exact limit `A_{\\\\infty}` in a\\n    single step if `A_k = A + a q^k`. Note in particular that it\\n    extrapolates the exact sum of a geometric series in a single step.\\n\\n    Applying the Shanks transformation once often improves convergence\\n    substantially for an arbitrary sequence, but the optimal effect is\\n    obtained by applying it iteratively:\\n    `S(S(A_k)), S(S(S(A_k))), \\\\ldots`.\\n\\n    Wynn's epsilon algorithm provides an efficient way to generate\\n    the table of iterated Shanks transformations. It reduces the\\n    computation of each element to essentially a single division, at\\n    the cost of requiring dummy elements in the table. See [1] for\\n    details.\\n\\n    **Precision issues**\\n\\n    Due to cancellation effects, the sequence must be typically be\\n    computed at a much higher precision than the target accuracy\\n    of the extrapolation.\\n\\n    If the Shanks transformation converges to the exact limit (such\\n    as if the sequence is a geometric series), then a division by\\n    zero occurs. By default, :func:`~mpmath.shanks` handles this case by\\n    terminating the iteration and returning the table it has\\n    generated so far. With *randomized=True*, it will instead\\n    replace the zero by a pseudorandom number close to zero.\\n    (TODO: find a better solution to this problem.)\\n\\n    **Examples**\\n\\n    We illustrate by applying Shanks transformation to the Leibniz\\n    series for `\\\\pi`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 50\\n        >>> S = [4*sum(mpf(-1)**n/(2*n+1) for n in range(m))\\n        ...     for m in range(1,30)]\\n        >>>\\n        >>> T = shanks(S[:7])\\n        >>> for row in T:\\n        ...     nprint(row)\\n        ...\\n        [-0.75]\\n        [1.25, 3.16667]\\n        [-1.75, 3.13333, -28.75]\\n        [2.25, 3.14524, 82.25, 3.14234]\\n        [-2.75, 3.13968, -177.75, 3.14139, -969.937]\\n        [3.25, 3.14271, 327.25, 3.14166, 3515.06, 3.14161]\\n\\n    The extrapolated accuracy is about 4 digits, and about 4 digits\\n    may have been lost due to cancellation::\\n\\n        >>> L = T[-1]\\n        >>> nprint([abs(L[-1] - pi), abs(L[-1] - L[-3]), abs(L[-2])])\\n        [2.22532e-5, 4.78309e-5, 3515.06]\\n\\n    Now we extend the computation::\\n\\n        >>> T = shanks(S[:25], T)\\n        >>> L = T[-1]\\n        >>> nprint([abs(L[-1] - pi), abs(L[-1] - L[-3]), abs(L[-2])])\\n        [3.75527e-19, 1.48478e-19, 2.96014e+17]\\n\\n    The value for pi is now accurate to 18 digits. About 18 digits may\\n    also have been lost to cancellation.\\n\\n    Here is an example with a geometric series, where the convergence\\n    is immediate (the sum is exactly 1)::\\n\\n        >>> mp.dps = 15\\n        >>> for row in shanks([0.5, 0.75, 0.875, 0.9375, 0.96875]):\\n        ...     nprint(row)\\n        [4.0]\\n        [8.0, 1.0]\\n\\n    **References**\\n\\n    1. [GravesMorris]_\\n\\n    2. [BenderOrszag]_ pp. 368-375\\n\\n    \\\"\\\"\\\"\\n    if len(seq) < 2:\\n        raise ValueError(\\\"seq should be of minimum length 2\\\")\\n    if table:\\n        START = len(table)\\n    else:\\n        START = 0\\n        table = []\\n    STOP = len(seq) - 1\\n    if STOP & 1:\\n        STOP -= 1\\n    one = ctx.one\\n    eps = +ctx.eps\\n    if randomized:\\n        from random import Random\\n        rnd = Random()\\n        rnd.seed(START)\\n    for i in xrange(START, STOP):\\n        row = []\\n        for j in xrange(i+1):\\n            if j == 0:\\n                a, b = 0, seq[i+1]-seq[i]\\n            else:\\n                if j == 1:\\n                    a = seq[i]\\n                else:\\n                    a = table[i-1][j-2]\\n                b = row[j-1] - table[i-1][j-1]\\n            if not b:\\n                if randomized:\\n                    b = (1 + rnd.getrandbits(10))*eps\\n                elif i & 1:\\n                    return table[:-1]\\n                else:\\n                    return table\\n            row.append(a + one/b)\\n        table.append(row)\\n    return table\\n\\n\\nclass levin_class:\\n    # levin: Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)\\n    r\\\"\\\"\\\"\\n    This interface implements Levin's (nonlinear) sequence transformation for\\n    convergence acceleration and summation of divergent series. It performs\\n    better than the Shanks/Wynn-epsilon algorithm for logarithmic convergent\\n    or alternating divergent series.\\n\\n    Let *A* be the series we want to sum:\\n\\n    .. math ::\\n\\n        A = \\\\sum_{k=0}^{\\\\infty} a_k\\n\\n    Attention: all `a_k` must be non-zero!\\n\\n    Let `s_n` be the partial sums of this series:\\n\\n    .. math ::\\n\\n        s_n = \\\\sum_{k=0}^n a_k.\\n\\n    **Methods**\\n\\n    Calling ``levin`` returns an object with the following methods.\\n\\n    ``update(...)`` works with the list of individual terms `a_k` of *A*, and\\n    ``update_step(...)`` works with the list of partial sums `s_k` of *A*:\\n\\n    .. code ::\\n\\n        v, e = ...update([a_0, a_1,..., a_k])\\n        v, e = ...update_psum([s_0, s_1,..., s_k])\\n\\n    ``step(...)`` works with the individual terms `a_k` and ``step_psum(...)``\\n    works with the partial sums `s_k`:\\n\\n    .. code ::\\n\\n        v, e = ...step(a_k)\\n        v, e = ...step_psum(s_k)\\n\\n    *v* is the current estimate for *A*, and *e* is an error estimate which is\\n    simply the difference between the current estimate and the last estimate.\\n    One should not mix ``update``, ``update_psum``, ``step`` and ``step_psum``.\\n\\n    **A word of caution**\\n\\n    One can only hope for good results (i.e. convergence acceleration or\\n    resummation) if the `s_n` have some well defind asymptotic behavior for\\n    large `n` and are not erratic or random. Furthermore one usually needs very\\n    high working precision because of the numerical cancellation. If the working\\n    precision is insufficient, levin may produce silently numerical garbage.\\n    Furthermore even if the Levin-transformation converges, in the general case\\n    there is no proof that the result is mathematically sound. Only for very\\n    special classes of problems one can prove that the Levin-transformation\\n    converges to the expected result (for example Stieltjes-type integrals).\\n    Furthermore the Levin-transform is quite expensive (i.e. slow) in comparison\\n    to Shanks/Wynn-epsilon, Richardson & co.\\n    In summary one can say that the Levin-transformation is powerful but\\n    unreliable and that it may need a copious amount of working precision.\\n\\n    The Levin transform has several variants differing in the choice of weights.\\n    Some variants are better suited for the possible flavours of convergence\\n    behaviour of *A* than other variants:\\n\\n    .. code ::\\n\\n       convergence behaviour   levin-u   levin-t   levin-v   shanks/wynn-epsilon\\n\\n       logarithmic               +         -         +           -\\n       linear                    +         +         +           +\\n       alternating divergent     +         +         +           +\\n\\n         \\\"+\\\" means the variant is suitable,\\\"-\\\" means the variant is not suitable;\\n         for comparison the Shanks/Wynn-epsilon transform is listed, too.\\n\\n    The variant is controlled though the variant keyword (i.e. ``variant=\\\"u\\\"``,\\n    ``variant=\\\"t\\\"`` or ``variant=\\\"v\\\"``). Overall \\\"u\\\" is probably the best choice.\\n\\n    Finally it is possible to use the Sidi-S transform instead of the Levin transform\\n    by using the keyword ``method='sidi'``. The Sidi-S transform works better than the\\n    Levin transformation for some divergent series (see the examples).\\n\\n    Parameters:\\n\\n    .. code ::\\n\\n       method      \\\"levin\\\" or \\\"sidi\\\" chooses either the Levin or the Sidi-S transformation\\n       variant     \\\"u\\\",\\\"t\\\" or \\\"v\\\" chooses the weight variant.\\n\\n    The Levin transform is also accessible through the nsum interface.\\n    ``method=\\\"l\\\"`` or ``method=\\\"levin\\\"`` select the normal Levin transform while\\n    ``method=\\\"sidi\\\"``\\n    selects the Sidi-S transform. The variant is in both cases selected through the\\n    levin_variant keyword. The stepsize in :func:`~mpmath.nsum` must not be chosen too large, otherwise\\n    it will miss the point where the Levin transform converges resulting in numerical\\n    overflow/garbage. For highly divergent series a copious amount of working precision\\n    must be chosen.\\n\\n    **Examples**\\n\\n    First we sum the zeta function::\\n\\n        >>> from mpmath import mp\\n        >>> mp.prec = 53\\n        >>> eps = mp.mpf(mp.eps)\\n        >>> with mp.extraprec(2 * mp.prec): # levin needs a high working precision\\n        ...     L = mp.levin(method = \\\"levin\\\", variant = \\\"u\\\")\\n        ...     S, s, n = [], 0, 1\\n        ...     while 1:\\n        ...         s += mp.one / (n * n)\\n        ...         n += 1\\n        ...         S.append(s)\\n        ...         v, e = L.update_psum(S)\\n        ...         if e < eps:\\n        ...             break\\n        ...         if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> print(mp.chop(v - mp.pi ** 2 / 6))\\n        0.0\\n        >>> w = mp.nsum(lambda n: 1 / (n*n), [1, mp.inf], method = \\\"levin\\\", levin_variant = \\\"u\\\")\\n        >>> print(mp.chop(v - w))\\n        0.0\\n\\n    Now we sum the zeta function outside its range of convergence\\n    (attention: This does not work at the negative integers!)::\\n\\n        >>> eps = mp.mpf(mp.eps)\\n        >>> with mp.extraprec(2 * mp.prec): # levin needs a high working precision\\n        ...     L = mp.levin(method = \\\"levin\\\", variant = \\\"v\\\")\\n        ...     A, n = [], 1\\n        ...     while 1:\\n        ...         s = mp.mpf(n) ** (2 + 3j)\\n        ...         n += 1\\n        ...         A.append(s)\\n        ...         v, e = L.update(A)\\n        ...         if e < eps:\\n        ...             break\\n        ...         if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> print(mp.chop(v - mp.zeta(-2-3j)))\\n        0.0\\n        >>> w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = \\\"levin\\\", levin_variant = \\\"v\\\")\\n        >>> print(mp.chop(v - w))\\n        0.0\\n\\n    Now we sum the divergent asymptotic expansion of an integral related to the\\n    exponential integral (see also [2] p.373). The Sidi-S transform works best here::\\n\\n        >>> z = mp.mpf(10)\\n        >>> exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf])\\n        >>> # exact = z * mp.exp(z) * mp.expint(1,z) # this is the symbolic expression for the integral\\n        >>> eps = mp.mpf(mp.eps)\\n        >>> with mp.extraprec(2 * mp.prec): # high working precisions are mandatory for divergent resummation\\n        ...     L = mp.levin(method = \\\"sidi\\\", variant = \\\"t\\\")\\n        ...     n = 0\\n        ...     while 1:\\n        ...         s = (-1)**n * mp.fac(n) * z ** (-n)\\n        ...         v, e = L.step(s)\\n        ...         n += 1\\n        ...         if e < eps:\\n        ...             break\\n        ...         if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> print(mp.chop(v - exact))\\n        0.0\\n        >>> w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = \\\"sidi\\\", levin_variant = \\\"t\\\")\\n        >>> print(mp.chop(v - w))\\n        0.0\\n\\n    Another highly divergent integral is also summable::\\n\\n        >>> z = mp.mpf(2)\\n        >>> eps = mp.mpf(mp.eps)\\n        >>> exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi)\\n        >>> # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) # this is the symbolic expression for the integral\\n        >>> with mp.extraprec(7 * mp.prec):  # we need copious amount of precision to sum this highly divergent series\\n        ...     L = mp.levin(method = \\\"levin\\\", variant = \\\"t\\\")\\n        ...     n, s = 0, 0\\n        ...     while 1:\\n        ...         s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n))\\n        ...         n += 1\\n        ...         v, e = L.step_psum(s)\\n        ...         if e < eps:\\n        ...             break\\n        ...         if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> print(mp.chop(v - exact))\\n        0.0\\n        >>> w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)),\\n        ...   [0, mp.inf], method = \\\"levin\\\", levin_variant = \\\"t\\\", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)])\\n        >>> print(mp.chop(v - w))\\n        0.0\\n\\n    These examples run with 15-20 decimal digits precision. For higher precision the\\n    working precision must be raised.\\n\\n    **Examples for nsum**\\n\\n    Here we calculate Euler's constant as the constant term in the Laurent\\n    expansion of `\\\\zeta(s)` at `s=1`. This sum converges extremly slowly because of\\n    the logarithmic convergence behaviour of the Dirichlet series for zeta::\\n\\n        >>> mp.dps = 30\\n        >>> z = mp.mpf(10) ** (-10)\\n        >>> a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = \\\"l\\\") - 1 / z\\n        >>> print(mp.chop(a - mp.euler, tol = 1e-10))\\n        0.0\\n\\n    The Sidi-S transform performs excellently for the alternating series of `\\\\log(2)`::\\n\\n        >>> a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = \\\"sidi\\\")\\n        >>> print(mp.chop(a - mp.log(2)))\\n        0.0\\n\\n    Hypergeometric series can also be summed outside their range of convergence.\\n    The stepsize in :func:`~mpmath.nsum` must not be chosen too large, otherwise it will miss the\\n    point where the Levin transform converges resulting in numerical overflow/garbage::\\n\\n        >>> z = 2 + 1j\\n        >>> exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z)\\n        >>> f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n))\\n        >>> v = mp.nsum(f, [0, mp.inf], method = \\\"levin\\\", steps = [10 for x in xrange(1000)])\\n        >>> print(mp.chop(exact-v))\\n        0.0\\n\\n    References:\\n\\n      [1] E.J. Weniger - \\\"Nonlinear Sequence Transformations for the Acceleration of\\n          Convergence and the Summation of Divergent Series\\\" arXiv:math/0306302\\n\\n      [2] A. Sidi - \\\"Pratical Extrapolation Methods\\\"\\n\\n      [3] H.H.H. Homeier - \\\"Scalar Levin-Type Sequence Transformations\\\" arXiv:math/0005209\\n\\n    \\\"\\\"\\\"\\n\\n    def __init__(self, method = \\\"levin\\\", variant = \\\"u\\\"):\\n        self.variant = variant\\n        self.n = 0\\n        self.a0 = 0\\n        self.theta = 1\\n        self.A = []\\n        self.B = []\\n        self.last = 0\\n        self.last_s = False\\n\\n        if method == \\\"levin\\\":\\n            self.factor = self.factor_levin\\n        elif method == \\\"sidi\\\":\\n            self.factor = self.factor_sidi\\n        else:\\n            raise ValueError(\\\"levin: unknown method \\\\\\\"%s\\\\\\\"\\\" % method)\\n\\n    def factor_levin(self, i):\\n        # original levin\\n        # [1] p.50,e.7.5-7 (with n-j replaced by i)\\n        return (self.theta + i) * (self.theta + self.n - 1) ** (self.n - i - 2) / self.ctx.mpf(self.theta + self.n) ** (self.n - i - 1)\\n\\n    def factor_sidi(self, i):\\n        # sidi analogon to levin (factorial series)\\n        # [1] p.59,e.8.3-16 (with n-j replaced by i)\\n        return (self.theta + self.n - 1) * (self.theta + self.n - 2) / self.ctx.mpf((self.theta + 2 * self.n - i - 2) * (self.theta + 2 * self.n - i - 3))\\n\\n    def run(self, s, a0, a1 = 0):\\n        if self.variant==\\\"t\\\":\\n            # levin t\\n            w=a0\\n        elif self.variant==\\\"u\\\":\\n            # levin u\\n            w=a0*(self.theta+self.n)\\n        elif self.variant==\\\"v\\\":\\n            # levin v\\n            w=a0*a1/(a0-a1)\\n        else:\\n            assert False, \\\"unknown variant\\\"\\n\\n        if w==0:\\n            raise ValueError(\\\"levin: zero weight\\\")\\n\\n        self.A.append(s/w)\\n        self.B.append(1/w)\\n\\n        for i in range(self.n-1,-1,-1):\\n            if i==self.n-1:\\n                f=1\\n            else:\\n                f=self.factor(i)\\n\\n            self.A[i]=self.A[i+1]-f*self.A[i]\\n            self.B[i]=self.B[i+1]-f*self.B[i]\\n\\n        self.n+=1\\n\\n    ###########################################################################\\n\\n    def update_psum(self,S):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the list of partial sums.\\n\\n        A   = sum(a_k, k = 0..infinity)\\n        s_n = sum(a_k, k = 0..n)\\n\\n        v, e = ...update_psum([s_0, s_1,..., s_k])\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        if self.variant!=\\\"v\\\":\\n            if self.n==0:\\n                self.run(S[0],S[0])\\n            while self.n<len(S):\\n                self.run(S[self.n],S[self.n]-S[self.n-1])\\n        else:\\n            if len(S)==1:\\n                self.last=0\\n                return S[0],abs(S[0])\\n\\n            if self.n==0:\\n                self.a1=S[1]-S[0]\\n                self.run(S[0],S[0],self.a1)\\n\\n            while self.n<len(S)-1:\\n                na1=S[self.n+1]-S[self.n]\\n                self.run(S[self.n],self.a1,na1)\\n                self.a1=na1\\n\\n        value=self.A[0]/self.B[0]\\n        err=abs(value-self.last)\\n        self.last=value\\n\\n        return value,err\\n\\n    def update(self,X):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the list of individual terms.\\n\\n        A = sum(a_k, k = 0..infinity)\\n\\n        v, e = ...update([a_0, a_1,..., a_k])\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        if self.variant!=\\\"v\\\":\\n            if self.n==0:\\n                self.s=X[0]\\n                self.run(self.s,X[0])\\n            while self.n<len(X):\\n                self.s+=X[self.n]\\n                self.run(self.s,X[self.n])\\n        else:\\n            if len(X)==1:\\n                self.last=0\\n                return X[0],abs(X[0])\\n\\n            if self.n==0:\\n                self.s=X[0]\\n                self.run(self.s,X[0],X[1])\\n\\n            while self.n<len(X)-1:\\n                self.s+=X[self.n]\\n                self.run(self.s,X[self.n],X[self.n+1])\\n\\n        value=self.A[0]/self.B[0]\\n        err=abs(value-self.last)\\n        self.last=value\\n\\n        return value,err\\n\\n    ###########################################################################\\n\\n    def step_psum(self,s):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the partial sums.\\n\\n        A   = sum(a_k, k = 0..infinity)\\n        s_n = sum(a_k, k = 0..n)\\n\\n        v, e = ...step_psum(s_k)\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        if self.variant!=\\\"v\\\":\\n            if self.n==0:\\n                self.last_s=s\\n                self.run(s,s)\\n            else:\\n                self.run(s,s-self.last_s)\\n                self.last_s=s\\n        else:\\n            if isinstance(self.last_s,bool):\\n                self.last_s=s\\n                self.last_w=s\\n                self.last=0\\n                return s,abs(s)\\n\\n            na1=s-self.last_s\\n            self.run(self.last_s,self.last_w,na1)\\n            self.last_w=na1\\n            self.last_s=s\\n\\n        value=self.A[0]/self.B[0]\\n        err=abs(value-self.last)\\n        self.last=value\\n\\n        return value,err\\n\\n    def step(self,x):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the individual terms.\\n\\n        A = sum(a_k, k = 0..infinity)\\n\\n        v, e = ...step(a_k)\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        if self.variant!=\\\"v\\\":\\n            if self.n==0:\\n                self.s=x\\n                self.run(self.s,x)\\n            else:\\n                self.s+=x\\n                self.run(self.s,x)\\n        else:\\n            if isinstance(self.last_s,bool):\\n                self.last_s=x\\n                self.s=0\\n                self.last=0\\n                return x,abs(x)\\n\\n            self.s+=self.last_s\\n            self.run(self.s,self.last_s,x)\\n            self.last_s=x\\n\\n        value=self.A[0]/self.B[0]\\n        err=abs(value-self.last)\\n        self.last=value\\n\\n        return value,err\\n\\ndef levin(ctx, method = \\\"levin\\\", variant = \\\"u\\\"):\\n    L = levin_class(method = method, variant = variant)\\n    L.ctx = ctx\\n    return L\\n\\nlevin.__doc__ = levin_class.__doc__\\ndefun(levin)\\n\\n\\nclass cohen_alt_class:\\n    # cohen_alt: Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)\\n    r\\\"\\\"\\\"\\n    This interface implements the convergence acceleration of alternating series\\n    as described in H. Cohen, F.R. Villegas, D. Zagier - \\\"Convergence Acceleration\\n    of Alternating Series\\\". This series transformation works only well if the\\n    individual terms of the series have an alternating sign. It belongs to the\\n    class of linear series transformations (in contrast to the Shanks/Wynn-epsilon\\n    or Levin transform). This series transformation is also able to sum some types\\n    of divergent series. See the paper under which conditions this resummation is\\n    mathematical sound.\\n\\n    Let *A* be the series we want to sum:\\n\\n    .. math ::\\n\\n        A = \\\\sum_{k=0}^{\\\\infty} a_k\\n\\n    Let `s_n` be the partial sums of this series:\\n\\n    .. math ::\\n\\n        s_n = \\\\sum_{k=0}^n a_k.\\n\\n\\n    **Interface**\\n\\n    Calling ``cohen_alt`` returns an object with the following methods.\\n\\n    Then ``update(...)`` works with the list of individual terms `a_k` and\\n    ``update_psum(...)`` works with the list of partial sums `s_k`:\\n\\n    .. code ::\\n\\n        v, e = ...update([a_0, a_1,..., a_k])\\n        v, e = ...update_psum([s_0, s_1,..., s_k])\\n\\n    *v* is the current estimate for *A*, and *e* is an error estimate which is\\n    simply the difference between the current estimate and the last estimate.\\n\\n    **Examples**\\n\\n    Here we compute the alternating zeta function using ``update_psum``::\\n\\n        >>> from mpmath import mp\\n        >>> AC = mp.cohen_alt()\\n        >>> S, s, n = [], 0, 1\\n        >>> while 1:\\n        ...     s += -((-1) ** n) * mp.one / (n * n)\\n        ...     n += 1\\n        ...     S.append(s)\\n        ...     v, e = AC.update_psum(S)\\n        ...     if e < mp.eps:\\n        ...         break\\n        ...     if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> print(mp.chop(v - mp.pi ** 2 / 12))\\n        0.0\\n\\n    Here we compute the product `\\\\prod_{n=1}^{\\\\infty} \\\\Gamma(1+1/(2n-1)) / \\\\Gamma(1+1/(2n))`::\\n\\n        >>> A = []\\n        >>> AC = mp.cohen_alt()\\n        >>> n = 1\\n        >>> while 1:\\n        ...     A.append( mp.loggamma(1 + mp.one / (2 * n - 1)))\\n        ...     A.append(-mp.loggamma(1 + mp.one / (2 * n)))\\n        ...     n += 1\\n        ...     v, e = AC.update(A)\\n        ...     if e < mp.eps:\\n        ...         break\\n        ...     if n > 1000: raise RuntimeError(\\\"iteration limit exceeded\\\")\\n        >>> v = mp.exp(v)\\n        >>> print(mp.chop(v - 1.06215090557106, tol = 1e-12))\\n        0.0\\n\\n    ``cohen_alt`` is also accessible through the :func:`~mpmath.nsum` interface::\\n\\n        >>> v = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = \\\"a\\\")\\n        >>> print(mp.chop(v - mp.log(2)))\\n        0.0\\n        >>> v = mp.nsum(lambda n: (-1)**n / (2 * n + 1), [0, mp.inf], method = \\\"a\\\")\\n        >>> print(mp.chop(v - mp.pi / 4))\\n        0.0\\n        >>> v = mp.nsum(lambda n: (-1)**n * mp.log(n) * n, [1, mp.inf], method = \\\"a\\\")\\n        >>> print(mp.chop(v - mp.diff(lambda s: mp.altzeta(s), -1)))\\n        0.0\\n\\n    \\\"\\\"\\\"\\n\\n    def __init__(self):\\n        self.last=0\\n\\n    def update(self, A):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the list of individual terms.\\n\\n        A    = sum(a_k, k = 0..infinity)\\n\\n        v, e = ...update([a_0, a_1,..., a_k])\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        n = len(A)\\n        d = (3 + self.ctx.sqrt(8)) ** n\\n        d = (d + 1 / d) / 2\\n        b = -self.ctx.one\\n        c = -d\\n        s = 0\\n\\n        for k in xrange(n):\\n            c = b - c\\n            if k % 2 == 0:\\n                s = s + c * A[k]\\n            else:\\n                s = s - c * A[k]\\n            b = 2 * (k + n) * (k - n) * b / ((2 * k + 1) * (k + self.ctx.one))\\n\\n        value = s / d\\n\\n        err = abs(value - self.last)\\n        self.last = value\\n\\n        return value, err\\n\\n    def update_psum(self, S):\\n        \\\"\\\"\\\"\\n        This routine applies the convergence acceleration to the list of partial sums.\\n\\n        A   = sum(a_k, k = 0..infinity)\\n        s_n = sum(a_k ,k = 0..n)\\n\\n        v, e = ...update_psum([s_0, s_1,..., s_k])\\n\\n        output:\\n          v      current estimate of the series A\\n          e      an error estimate which is simply the difference between the current\\n                 estimate and the last estimate.\\n        \\\"\\\"\\\"\\n\\n        n = len(S)\\n        d = (3 + self.ctx.sqrt(8)) ** n\\n        d = (d + 1 / d) / 2\\n        b = self.ctx.one\\n        s = 0\\n\\n        for k in xrange(n):\\n            b = 2 * (n + k) * (n - k) * b / ((2 * k + 1) * (k + self.ctx.one))\\n            s += b * S[k]\\n\\n        value = s / d\\n\\n        err = abs(value - self.last)\\n        self.last = value\\n\\n        return value, err\\n\\ndef cohen_alt(ctx):\\n    L = cohen_alt_class()\\n    L.ctx = ctx\\n    return L\\n\\ncohen_alt.__doc__ = cohen_alt_class.__doc__\\ndefun(cohen_alt)\\n\\n\\n@defun\\ndef sumap(ctx, f, interval, integral=None, error=False):\\n    r\\\"\\\"\\\"\\n    Evaluates an infinite series of an analytic summand *f* using the\\n    Abel-Plana formula\\n\\n    .. math ::\\n\\n        \\\\sum_{k=0}^{\\\\infty} f(k) = \\\\int_0^{\\\\infty} f(t) dt + \\\\frac{1}{2} f(0) +\\n            i \\\\int_0^{\\\\infty} \\\\frac{f(it)-f(-it)}{e^{2\\\\pi t}-1} dt.\\n\\n    Unlike the Euler-Maclaurin formula (see :func:`~mpmath.sumem`),\\n    the Abel-Plana formula does not require derivatives. However,\\n    it only works when `|f(it)-f(-it)|` does not\\n    increase too rapidly with `t`.\\n\\n    **Examples**\\n\\n    The Abel-Plana formula is particularly useful when the summand\\n    decreases like a power of `k`; for example when the sum is a pure\\n    zeta function::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> sumap(lambda k: 1/k**2.5, [1,inf])\\n        1.34148725725091717975677\\n        >>> zeta(2.5)\\n        1.34148725725091717975677\\n        >>> sumap(lambda k: 1/(k+1j)**(2.5+2.5j), [1,inf])\\n        (-3.385361068546473342286084 - 0.7432082105196321803869551j)\\n        >>> zeta(2.5+2.5j, 1+1j)\\n        (-3.385361068546473342286084 - 0.7432082105196321803869551j)\\n\\n    If the series is alternating, numerical quadrature along the real\\n    line is likely to give poor results, so it is better to evaluate\\n    the first term symbolically whenever possible:\\n\\n        >>> n=3; z=-0.75\\n        >>> I = expint(n,-log(z))\\n        >>> chop(sumap(lambda k: z**k / k**n, [1,inf], integral=I))\\n        -0.6917036036904594510141448\\n        >>> polylog(n,z)\\n        -0.6917036036904594510141448\\n\\n    \\\"\\\"\\\"\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 10\\n        a, b = interval\\n        if  b != ctx.inf:\\n            raise ValueError(\\\"b should be equal to ctx.inf\\\")\\n        g = lambda x: f(x+a)\\n        if integral is None:\\n            i1, err1 = ctx.quad(g, [0,ctx.inf], error=True)\\n        else:\\n            i1, err1 = integral, 0\\n        j = ctx.j\\n        p = ctx.pi * 2\\n        if ctx._is_real_type(i1):\\n            h = lambda t: -2 * ctx.im(g(j*t)) / ctx.expm1(p*t)\\n        else:\\n            h = lambda t: j*(g(j*t)-g(-j*t)) / ctx.expm1(p*t)\\n        i2, err2 = ctx.quad(h, [0,ctx.inf], error=True)\\n        err = err1+err2\\n        v = i1+i2+0.5*g(ctx.mpf(0))\\n    finally:\\n        ctx.prec = prec\\n    if error:\\n        return +v, err\\n    return +v\\n\\n\\n@defun\\ndef sumem(ctx, f, interval, tol=None, reject=10, integral=None,\\n    adiffs=None, bdiffs=None, verbose=False, error=False,\\n    _fast_abort=False):\\n    r\\\"\\\"\\\"\\n    Uses the Euler-Maclaurin formula to compute an approximation accurate\\n    to within ``tol`` (which defaults to the present epsilon) of the sum\\n\\n    .. math ::\\n\\n        S = \\\\sum_{k=a}^b f(k)\\n\\n    where `(a,b)` are given by ``interval`` and `a` or `b` may be\\n    infinite. The approximation is\\n\\n    .. math ::\\n\\n        S \\\\sim \\\\int_a^b f(x) \\\\,dx + \\\\frac{f(a)+f(b)}{2} +\\n        \\\\sum_{k=1}^{\\\\infty} \\\\frac{B_{2k}}{(2k)!}\\n        \\\\left(f^{(2k-1)}(b)-f^{(2k-1)}(a)\\\\right).\\n\\n    The last sum in the Euler-Maclaurin formula is not generally\\n    convergent (a notable exception is if `f` is a polynomial, in\\n    which case Euler-Maclaurin actually gives an exact result).\\n\\n    The summation is stopped as soon as the quotient between two\\n    consecutive terms falls below *reject*. That is, by default\\n    (*reject* = 10), the summation is continued as long as each\\n    term adds at least one decimal.\\n\\n    Although not convergent, convergence to a given tolerance can\\n    often be \\\"forced\\\" if `b = \\\\infty` by summing up to `a+N` and then\\n    applying the Euler-Maclaurin formula to the sum over the range\\n    `(a+N+1, \\\\ldots, \\\\infty)`. This procedure is implemented by\\n    :func:`~mpmath.nsum`.\\n\\n    By default numerical quadrature and differentiation is used.\\n    If the symbolic values of the integral and endpoint derivatives\\n    are known, it is more efficient to pass the value of the\\n    integral explicitly as ``integral`` and the derivatives\\n    explicitly as ``adiffs`` and ``bdiffs``. The derivatives\\n    should be given as iterables that yield\\n    `f(a), f'(a), f''(a), \\\\ldots` (and the equivalent for `b`).\\n\\n    **Examples**\\n\\n    Summation of an infinite series, with automatic and symbolic\\n    integral and derivative values (the second should be much faster)::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 50; mp.pretty = True\\n        >>> sumem(lambda n: 1/n**2, [32, inf])\\n        0.03174336652030209012658168043874142714132886413417\\n        >>> I = mpf(1)/32\\n        >>> D = adiffs=((-1)**n*fac(n+1)*32**(-2-n) for n in range(999))\\n        >>> sumem(lambda n: 1/n**2, [32, inf], integral=I, adiffs=D)\\n        0.03174336652030209012658168043874142714132886413417\\n\\n    An exact evaluation of a finite polynomial sum::\\n\\n        >>> sumem(lambda n: n**5-12*n**2+3*n, [-100000, 200000])\\n        10500155000624963999742499550000.0\\n        >>> print(sum(n**5-12*n**2+3*n for n in range(-100000, 200001)))\\n        10500155000624963999742499550000\\n\\n    \\\"\\\"\\\"\\n    tol = tol or +ctx.eps\\n    interval = ctx._as_points(interval)\\n    a = ctx.convert(interval[0])\\n    b = ctx.convert(interval[-1])\\n    err = ctx.zero\\n    prev = 0\\n    M = 10000\\n    if a == ctx.ninf: adiffs = (0 for n in xrange(M))\\n    else:             adiffs = adiffs or ctx.diffs(f, a)\\n    if b == ctx.inf:  bdiffs = (0 for n in xrange(M))\\n    else:             bdiffs = bdiffs or ctx.diffs(f, b)\\n    orig = ctx.prec\\n    #verbose = 1\\n    try:\\n        ctx.prec += 10\\n        s = ctx.zero\\n        for k, (da, db) in enumerate(izip(adiffs, bdiffs)):\\n            if k & 1:\\n                term = (db-da) * ctx.bernoulli(k+1) / ctx.factorial(k+1)\\n                mag = abs(term)\\n                if verbose:\\n                    print(\\\"term\\\", k, \\\"magnitude =\\\", ctx.nstr(mag))\\n                if k > 4 and mag < tol:\\n                    s += term\\n                    break\\n                elif k > 4 and abs(prev) / mag < reject:\\n                    err += mag\\n                    if _fast_abort:\\n                        return [s, (s, err)][error]\\n                    if verbose:\\n                        print(\\\"Failed to converge\\\")\\n                    break\\n                else:\\n                    s += term\\n                prev = term\\n        # Endpoint correction\\n        if a != ctx.ninf: s += f(a)/2\\n        if b != ctx.inf: s += f(b)/2\\n        # Tail integral\\n        if verbose:\\n            print(\\\"Integrating f(x) from x = %s to %s\\\" % (ctx.nstr(a), ctx.nstr(b)))\\n        if integral:\\n            s += integral\\n        else:\\n            integral, ierr = ctx.quad(f, interval, error=True)\\n            if verbose:\\n                print(\\\"Integration error:\\\", ierr)\\n            s += integral\\n            err += ierr\\n    finally:\\n        ctx.prec = orig\\n    if error:\\n        return s, err\\n    else:\\n        return s\\n\\n@defun\\ndef adaptive_extrapolation(ctx, update, emfun, kwargs):\\n    option = kwargs.get\\n    if ctx._fixed_precision:\\n        tol = option('tol', ctx.eps*2**10)\\n    else:\\n        tol = option('tol', ctx.eps/2**10)\\n    verbose = option('verbose', False)\\n    maxterms = option('maxterms', ctx.dps*10)\\n    method = set(option('method', 'r+s').split('+'))\\n    skip = option('skip', 0)\\n    steps = iter(option('steps', xrange(10, 10**9, 10)))\\n    strict = option('strict')\\n    #steps = (10 for i in xrange(1000))\\n    summer=[]\\n    if 'd' in method or 'direct' in method:\\n        TRY_RICHARDSON = TRY_SHANKS = TRY_EULER_MACLAURIN = False\\n    else:\\n        TRY_RICHARDSON = ('r' in method) or ('richardson' in method)\\n        TRY_SHANKS = ('s' in method) or ('shanks' in method)\\n        TRY_EULER_MACLAURIN = ('e' in method) or \\\\\\n            ('euler-maclaurin' in method)\\n\\n        def init_levin(m):\\n            variant = kwargs.get(\\\"levin_variant\\\", \\\"u\\\")\\n            if isinstance(variant, str):\\n                if variant == \\\"all\\\":\\n                    variant = [\\\"u\\\", \\\"v\\\", \\\"t\\\"]\\n                else:\\n                    variant = [variant]\\n            for s in variant:\\n                L = levin_class(method = m, variant = s)\\n                L.ctx = ctx\\n                L.name = m + \\\"(\\\" + s + \\\")\\\"\\n                summer.append(L)\\n\\n        if ('l' in method) or ('levin' in method):\\n            init_levin(\\\"levin\\\")\\n\\n        if ('sidi' in method):\\n            init_levin(\\\"sidi\\\")\\n\\n        if ('a' in method) or ('alternating' in method):\\n            L = cohen_alt_class()\\n            L.ctx = ctx\\n            L.name = \\\"alternating\\\"\\n            summer.append(L)\\n\\n    last_richardson_value = 0\\n    shanks_table = []\\n    index = 0\\n    step = 10\\n    partial = []\\n    best = ctx.zero\\n    orig = ctx.prec\\n    try:\\n        if 'workprec' in kwargs:\\n            ctx.prec = kwargs['workprec']\\n        elif TRY_RICHARDSON or TRY_SHANKS or len(summer)!=0:\\n            ctx.prec = (ctx.prec+10) * 4\\n        else:\\n            ctx.prec += 30\\n        while 1:\\n            if index >= maxterms:\\n                break\\n\\n            # Get new batch of terms\\n            try:\\n                step = next(steps)\\n            except StopIteration:\\n                pass\\n            if verbose:\\n                print(\\\"-\\\"*70)\\n                print(\\\"Adding terms #%i-#%i\\\" % (index, index+step))\\n            update(partial, xrange(index, index+step))\\n            index += step\\n\\n            # Check direct error\\n            best = partial[-1]\\n            error = abs(best - partial[-2])\\n            if verbose:\\n                print(\\\"Direct error: %s\\\" % ctx.nstr(error))\\n            if error <= tol:\\n                return best\\n\\n            # Check each extrapolation method\\n            if TRY_RICHARDSON:\\n                value, maxc = ctx.richardson(partial)\\n                # Convergence\\n                richardson_error = abs(value - last_richardson_value)\\n                if verbose:\\n                    print(\\\"Richardson error: %s\\\" % ctx.nstr(richardson_error))\\n                # Convergence\\n                if richardson_error <= tol:\\n                    return value\\n                last_richardson_value = value\\n                # Unreliable due to cancellation\\n                if ctx.eps*maxc > tol:\\n                    if verbose:\\n                        print(\\\"Ran out of precision for Richardson\\\")\\n                    TRY_RICHARDSON = False\\n                if richardson_error < error:\\n                    error = richardson_error\\n                    best = value\\n            if TRY_SHANKS:\\n                shanks_table = ctx.shanks(partial, shanks_table, randomized=True)\\n                row = shanks_table[-1]\\n                if len(row) == 2:\\n                    est1 = row[-1]\\n                    shanks_error = 0\\n                else:\\n                    est1, maxc, est2 = row[-1], abs(row[-2]), row[-3]\\n                    shanks_error = abs(est1-est2)\\n                if verbose:\\n                    print(\\\"Shanks error: %s\\\" % ctx.nstr(shanks_error))\\n                if shanks_error <= tol:\\n                    return est1\\n                if ctx.eps*maxc > tol:\\n                    if verbose:\\n                        print(\\\"Ran out of precision for Shanks\\\")\\n                    TRY_SHANKS = False\\n                if shanks_error < error:\\n                    error = shanks_error\\n                    best = est1\\n            for L in summer:\\n                est, lerror = L.update_psum(partial)\\n                if verbose:\\n                    print(\\\"%s error: %s\\\" % (L.name, ctx.nstr(lerror)))\\n                if lerror <= tol:\\n                    return est\\n                if lerror < error:\\n                    error = lerror\\n                    best = est\\n            if TRY_EULER_MACLAURIN:\\n                if ctx.almosteq(ctx.mpc(ctx.sign(partial[-1]) / ctx.sign(partial[-2])), -1):\\n                    if verbose:\\n                        print (\\\"NOT using Euler-Maclaurin: the series appears\\\"\\n                            \\\" to be alternating, so numerical\\\\n quadrature\\\"\\n                            \\\" will most likely fail\\\")\\n                    TRY_EULER_MACLAURIN = False\\n                else:\\n                    value, em_error = emfun(index, tol)\\n                    value += partial[-1]\\n                    if verbose:\\n                        print(\\\"Euler-Maclaurin error: %s\\\" % ctx.nstr(em_error))\\n                    if em_error <= tol:\\n                        return value\\n                    if em_error < error:\\n                        best = value\\n    finally:\\n        ctx.prec = orig\\n    if strict:\\n        raise ctx.NoConvergence\\n    if verbose:\\n        print(\\\"Warning: failed to converge to target accuracy\\\")\\n    return best\\n\\n@defun\\ndef nsum(ctx, f, *intervals, **options):\\n    r\\\"\\\"\\\"\\n    Computes the sum\\n\\n    .. math :: S = \\\\sum_{k=a}^b f(k)\\n\\n    where `(a, b)` = *interval*, and where `a = -\\\\infty` and/or\\n    `b = \\\\infty` are allowed, or more generally\\n\\n    .. math :: S = \\\\sum_{k_1=a_1}^{b_1} \\\\cdots\\n                   \\\\sum_{k_n=a_n}^{b_n} f(k_1,\\\\ldots,k_n)\\n\\n    if multiple intervals are given.\\n\\n    Two examples of infinite series that can be summed by :func:`~mpmath.nsum`,\\n    where the first converges rapidly and the second converges slowly,\\n    are::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> nsum(lambda n: 1/fac(n), [0, inf])\\n        2.71828182845905\\n        >>> nsum(lambda n: 1/n**2, [1, inf])\\n        1.64493406684823\\n\\n    When appropriate, :func:`~mpmath.nsum` applies convergence acceleration to\\n    accurately estimate the sums of slowly convergent series. If the series is\\n    finite, :func:`~mpmath.nsum` currently does not attempt to perform any\\n    extrapolation, and simply calls :func:`~mpmath.fsum`.\\n\\n    Multidimensional infinite series are reduced to a single-dimensional\\n    series over expanding hypercubes; if both infinite and finite dimensions\\n    are present, the finite ranges are moved innermost. For more advanced\\n    control over the summation order, use nested calls to :func:`~mpmath.nsum`,\\n    or manually rewrite the sum as a single-dimensional series.\\n\\n    **Options**\\n\\n    *tol*\\n        Desired maximum final error. Defaults roughly to the\\n        epsilon of the working precision.\\n\\n    *method*\\n        Which summation algorithm to use (described below).\\n        Default: ``'richardson+shanks'``.\\n\\n    *maxterms*\\n        Cancel after at most this many terms. Default: 10*dps.\\n\\n    *steps*\\n        An iterable giving the number of terms to add between\\n        each extrapolation attempt. The default sequence is\\n        [10, 20, 30, 40, ...]. For example, if you know that\\n        approximately 100 terms will be required, efficiency might be\\n        improved by setting this to [100, 10]. Then the first\\n        extrapolation will be performed after 100 terms, the second\\n        after 110, etc.\\n\\n    *verbose*\\n        Print details about progress.\\n\\n    *ignore*\\n        If enabled, any term that raises ``ArithmeticError``\\n        or ``ValueError`` (e.g. through division by zero) is replaced\\n        by a zero. This is convenient for lattice sums with\\n        a singular term near the origin.\\n\\n    **Methods**\\n\\n    Unfortunately, an algorithm that can efficiently sum any infinite\\n    series does not exist. :func:`~mpmath.nsum` implements several different\\n    algorithms that each work well in different cases. The *method*\\n    keyword argument selects a method.\\n\\n    The default method is ``'r+s'``, i.e. both Richardson extrapolation\\n    and Shanks transformation is attempted. A slower method that\\n    handles more cases is ``'r+s+e'``. For very high precision\\n    summation, or if the summation needs to be fast (for example if\\n    multiple sums need to be evaluated), it is a good idea to\\n    investigate which one method works best and only use that.\\n\\n    ``'richardson'`` / ``'r'``:\\n        Uses Richardson extrapolation. Provides useful extrapolation\\n        when `f(k) \\\\sim P(k)/Q(k)` or when `f(k) \\\\sim (-1)^k P(k)/Q(k)`\\n        for polynomials `P` and `Q`. See :func:`~mpmath.richardson` for\\n        additional information.\\n\\n    ``'shanks'`` / ``'s'``:\\n        Uses Shanks transformation. Typically provides useful\\n        extrapolation when `f(k) \\\\sim c^k` or when successive terms\\n        alternate signs. Is able to sum some divergent series.\\n        See :func:`~mpmath.shanks` for additional information.\\n\\n    ``'levin'`` / ``'l'``:\\n        Uses the Levin transformation. It performs better than the Shanks\\n        transformation for logarithmic convergent or alternating divergent\\n        series. The ``'levin_variant'``-keyword selects the variant. Valid\\n        choices are \\\"u\\\", \\\"t\\\", \\\"v\\\" and \\\"all\\\" whereby \\\"all\\\" uses all three\\n        u,t and v simultanously (This is good for performance comparison in\\n        conjunction with \\\"verbose=True\\\"). Instead of the Levin transform one can\\n        also use the Sidi-S transform by selecting the method ``'sidi'``.\\n        See :func:`~mpmath.levin` for additional details.\\n\\n    ``'alternating'`` / ``'a'``:\\n        This is the convergence acceleration of alternating series developped\\n        by Cohen, Villegras and Zagier.\\n        See :func:`~mpmath.cohen_alt` for additional details.\\n\\n    ``'euler-maclaurin'`` / ``'e'``:\\n        Uses the Euler-Maclaurin summation formula to approximate\\n        the remainder sum by an integral. This requires high-order\\n        numerical derivatives and numerical integration. The advantage\\n        of this algorithm is that it works regardless of the\\n        decay rate of `f`, as long as `f` is sufficiently smooth.\\n        See :func:`~mpmath.sumem` for additional information.\\n\\n    ``'direct'`` / ``'d'``:\\n        Does not perform any extrapolation. This can be used\\n        (and should only be used for) rapidly convergent series.\\n        The summation automatically stops when the terms\\n        decrease below the target tolerance.\\n\\n    **Basic examples**\\n\\n    A finite sum::\\n\\n        >>> nsum(lambda k: 1/k, [1, 6])\\n        2.45\\n\\n    Summation of a series going to negative infinity and a doubly\\n    infinite series::\\n\\n        >>> nsum(lambda k: 1/k**2, [-inf, -1])\\n        1.64493406684823\\n        >>> nsum(lambda k: 1/(1+k**2), [-inf, inf])\\n        3.15334809493716\\n\\n    :func:`~mpmath.nsum` handles sums of complex numbers::\\n\\n        >>> nsum(lambda k: (0.5+0.25j)**k, [0, inf])\\n        (1.6 + 0.8j)\\n\\n    The following sum converges very rapidly, so it is most\\n    efficient to sum it by disabling convergence acceleration::\\n\\n        >>> mp.dps = 1000\\n        >>> a = nsum(lambda k: -(-1)**k * k**2 / fac(2*k), [1, inf],\\n        ...     method='direct')\\n        >>> b = (cos(1)+sin(1))/4\\n        >>> abs(a-b) < mpf('1e-998')\\n        True\\n\\n    **Examples with Richardson extrapolation**\\n\\n    Richardson extrapolation works well for sums over rational\\n    functions, as well as their alternating counterparts::\\n\\n        >>> mp.dps = 50\\n        >>> nsum(lambda k: 1 / k**3, [1, inf],\\n        ...     method='richardson')\\n        1.2020569031595942853997381615114499907649862923405\\n        >>> zeta(3)\\n        1.2020569031595942853997381615114499907649862923405\\n\\n        >>> nsum(lambda n: (n + 3)/(n**3 + n**2), [1, inf],\\n        ...     method='richardson')\\n        2.9348022005446793094172454999380755676568497036204\\n        >>> pi**2/2-2\\n        2.9348022005446793094172454999380755676568497036204\\n\\n        >>> nsum(lambda k: (-1)**k / k**3, [1, inf],\\n        ...     method='richardson')\\n        -0.90154267736969571404980362113358749307373971925537\\n        >>> -3*zeta(3)/4\\n        -0.90154267736969571404980362113358749307373971925538\\n\\n    **Examples with Shanks transformation**\\n\\n    The Shanks transformation works well for geometric series\\n    and typically provides excellent acceleration for Taylor\\n    series near the border of their disk of convergence.\\n    Here we apply it to a series for `\\\\log(2)`, which can be\\n    seen as the Taylor series for `\\\\log(1+x)` with `x = 1`::\\n\\n        >>> nsum(lambda k: -(-1)**k/k, [1, inf],\\n        ...     method='shanks')\\n        0.69314718055994530941723212145817656807550013436025\\n        >>> log(2)\\n        0.69314718055994530941723212145817656807550013436025\\n\\n    Here we apply it to a slowly convergent geometric series::\\n\\n        >>> nsum(lambda k: mpf('0.995')**k, [0, inf],\\n        ...     method='shanks')\\n        200.0\\n\\n    Finally, Shanks' method works very well for alternating series\\n    where `f(k) = (-1)^k g(k)`, and often does so regardless of\\n    the exact decay rate of `g(k)`::\\n\\n        >>> mp.dps = 15\\n        >>> nsum(lambda k: (-1)**(k+1) / k**1.5, [1, inf],\\n        ...     method='shanks')\\n        0.765147024625408\\n        >>> (2-sqrt(2))*zeta(1.5)/2\\n        0.765147024625408\\n\\n    The following slowly convergent alternating series has no known\\n    closed-form value. Evaluating the sum a second time at higher\\n    precision indicates that the value is probably correct::\\n\\n        >>> nsum(lambda k: (-1)**k / log(k), [2, inf],\\n        ...     method='shanks')\\n        0.924299897222939\\n        >>> mp.dps = 30\\n        >>> nsum(lambda k: (-1)**k / log(k), [2, inf],\\n        ...     method='shanks')\\n        0.92429989722293885595957018136\\n\\n    **Examples with Levin transformation**\\n\\n    The following example calculates Euler's constant as the constant term in\\n    the Laurent expansion of zeta(s) at s=1. This sum converges extremly slow\\n    because of the logarithmic convergence behaviour of the Dirichlet series\\n    for zeta.\\n\\n      >>> mp.dps = 30\\n      >>> z = mp.mpf(10) ** (-10)\\n      >>> a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = \\\"levin\\\") - 1 / z\\n      >>> print(mp.chop(a - mp.euler, tol = 1e-10))\\n      0.0\\n\\n    Now we sum the zeta function outside its range of convergence\\n    (attention: This does not work at the negative integers!):\\n\\n      >>> mp.dps = 15\\n      >>> w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = \\\"levin\\\", levin_variant = \\\"v\\\")\\n      >>> print(mp.chop(w - mp.zeta(-2-3j)))\\n      0.0\\n\\n    The next example resummates an asymptotic series expansion of an integral\\n    related to the exponential integral.\\n\\n      >>> mp.dps = 15\\n      >>> z = mp.mpf(10)\\n      >>> # exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf])\\n      >>> exact = z * mp.exp(z) * mp.expint(1,z) # this is the symbolic expression for the integral\\n      >>> w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = \\\"sidi\\\", levin_variant = \\\"t\\\")\\n      >>> print(mp.chop(w - exact))\\n      0.0\\n\\n    Following highly divergent asymptotic expansion needs some care. Firstly we\\n    need copious amount of working precision. Secondly the stepsize must not be\\n    chosen to large, otherwise nsum may miss the point where the Levin transform\\n    converges and reach the point where only numerical garbage is produced due to\\n    numerical cancellation.\\n\\n      >>> mp.dps = 15\\n      >>> z = mp.mpf(2)\\n      >>> # exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi)\\n      >>> exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) # this is the symbolic expression for the integral\\n      >>> w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)),\\n      ...   [0, mp.inf], method = \\\"levin\\\", levin_variant = \\\"t\\\", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)])\\n      >>> print(mp.chop(w - exact))\\n      0.0\\n\\n    The hypergeoemtric function can also be summed outside its range of convergence:\\n\\n      >>> mp.dps = 15\\n      >>> z = 2 + 1j\\n      >>> exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z)\\n      >>> f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n))\\n      >>> v = mp.nsum(f, [0, mp.inf], method = \\\"levin\\\", steps = [10 for x in xrange(1000)])\\n      >>> print(mp.chop(exact-v))\\n      0.0\\n\\n    **Examples with Cohen's alternating series resummation**\\n\\n      The next example sums the alternating zeta function:\\n\\n      >>> v = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = \\\"a\\\")\\n      >>> print(mp.chop(v - mp.log(2)))\\n      0.0\\n\\n      The derivate of the alternating zeta function outside its range of\\n      convergence:\\n\\n      >>> v = mp.nsum(lambda n: (-1)**n * mp.log(n) * n, [1, mp.inf], method = \\\"a\\\")\\n      >>> print(mp.chop(v - mp.diff(lambda s: mp.altzeta(s), -1)))\\n      0.0\\n\\n    **Examples with Euler-Maclaurin summation**\\n\\n    The sum in the following example has the wrong rate of convergence\\n    for either Richardson or Shanks to be effective.\\n\\n        >>> f = lambda k: log(k)/k**2.5\\n        >>> mp.dps = 15\\n        >>> nsum(f, [1, inf], method='euler-maclaurin')\\n        0.38734195032621\\n        >>> -diff(zeta, 2.5)\\n        0.38734195032621\\n\\n    Increasing ``steps`` improves speed at higher precision::\\n\\n        >>> mp.dps = 50\\n        >>> nsum(f, [1, inf], method='euler-maclaurin', steps=[250])\\n        0.38734195032620997271199237593105101319948228874688\\n        >>> -diff(zeta, 2.5)\\n        0.38734195032620997271199237593105101319948228874688\\n\\n    **Divergent series**\\n\\n    The Shanks transformation is able to sum some *divergent*\\n    series. In particular, it is often able to sum Taylor series\\n    beyond their radius of convergence (this is due to a relation\\n    between the Shanks transformation and Pade approximations;\\n    see :func:`~mpmath.pade` for an alternative way to evaluate divergent\\n    Taylor series). Furthermore the Levin-transform examples above\\n    contain some divergent series resummation.\\n\\n    Here we apply it to `\\\\log(1+x)` far outside the region of\\n    convergence::\\n\\n        >>> mp.dps = 50\\n        >>> nsum(lambda k: -(-9)**k/k, [1, inf],\\n        ...     method='shanks')\\n        2.3025850929940456840179914546843642076011014886288\\n        >>> log(10)\\n        2.3025850929940456840179914546843642076011014886288\\n\\n    A particular type of divergent series that can be summed\\n    using the Shanks transformation is geometric series.\\n    The result is the same as using the closed-form formula\\n    for an infinite geometric series::\\n\\n        >>> mp.dps = 15\\n        >>> for n in range(-8, 8):\\n        ...     if n == 1:\\n        ...         continue\\n        ...     print(\\\"%s %s %s\\\" % (mpf(n), mpf(1)/(1-n),\\n        ...         nsum(lambda k: n**k, [0, inf], method='shanks')))\\n        ...\\n        -8.0 0.111111111111111 0.111111111111111\\n        -7.0 0.125 0.125\\n        -6.0 0.142857142857143 0.142857142857143\\n        -5.0 0.166666666666667 0.166666666666667\\n        -4.0 0.2 0.2\\n        -3.0 0.25 0.25\\n        -2.0 0.333333333333333 0.333333333333333\\n        -1.0 0.5 0.5\\n        0.0 1.0 1.0\\n        2.0 -1.0 -1.0\\n        3.0 -0.5 -0.5\\n        4.0 -0.333333333333333 -0.333333333333333\\n        5.0 -0.25 -0.25\\n        6.0 -0.2 -0.2\\n        7.0 -0.166666666666667 -0.166666666666667\\n\\n    **Multidimensional sums**\\n\\n    Any combination of finite and infinite ranges is allowed for the\\n    summation indices::\\n\\n        >>> mp.dps = 15\\n        >>> nsum(lambda x,y: x+y, [2,3], [4,5])\\n        28.0\\n        >>> nsum(lambda x,y: x/2**y, [1,3], [1,inf])\\n        6.0\\n        >>> nsum(lambda x,y: y/2**x, [1,inf], [1,3])\\n        6.0\\n        >>> nsum(lambda x,y,z: z/(2**x*2**y), [1,inf], [1,inf], [3,4])\\n        7.0\\n        >>> nsum(lambda x,y,z: y/(2**x*2**z), [1,inf], [3,4], [1,inf])\\n        7.0\\n        >>> nsum(lambda x,y,z: x/(2**z*2**y), [3,4], [1,inf], [1,inf])\\n        7.0\\n\\n    Some nice examples of double series with analytic solutions or\\n    reductions to single-dimensional series (see [1])::\\n\\n        >>> nsum(lambda m, n: 1/2**(m*n), [1,inf], [1,inf])\\n        1.60669515241529\\n        >>> nsum(lambda n: 1/(2**n-1), [1,inf])\\n        1.60669515241529\\n\\n        >>> nsum(lambda i,j: (-1)**(i+j)/(i**2+j**2), [1,inf], [1,inf])\\n        0.278070510848213\\n        >>> pi*(pi-3*ln2)/12\\n        0.278070510848213\\n\\n        >>> nsum(lambda i,j: (-1)**(i+j)/(i+j)**2, [1,inf], [1,inf])\\n        0.129319852864168\\n        >>> altzeta(2) - altzeta(1)\\n        0.129319852864168\\n\\n        >>> nsum(lambda i,j: (-1)**(i+j)/(i+j)**3, [1,inf], [1,inf])\\n        0.0790756439455825\\n        >>> altzeta(3) - altzeta(2)\\n        0.0790756439455825\\n\\n        >>> nsum(lambda m,n: m**2*n/(3**m*(n*3**m+m*3**n)),\\n        ...     [1,inf], [1,inf])\\n        0.28125\\n        >>> mpf(9)/32\\n        0.28125\\n\\n        >>> nsum(lambda i,j: fac(i-1)*fac(j-1)/fac(i+j),\\n        ...     [1,inf], [1,inf], workprec=400)\\n        1.64493406684823\\n        >>> zeta(2)\\n        1.64493406684823\\n\\n    A hard example of a multidimensional sum is the Madelung constant\\n    in three dimensions (see [2]). The defining sum converges very\\n    slowly and only conditionally, so :func:`~mpmath.nsum` is lucky to\\n    obtain an accurate value through convergence acceleration. The\\n    second evaluation below uses a much more efficient, rapidly\\n    convergent 2D sum::\\n\\n        >>> nsum(lambda x,y,z: (-1)**(x+y+z)/(x*x+y*y+z*z)**0.5,\\n        ...     [-inf,inf], [-inf,inf], [-inf,inf], ignore=True)\\n        -1.74756459463318\\n        >>> nsum(lambda x,y: -12*pi*sech(0.5*pi * \\\\\\n        ...     sqrt((2*x+1)**2+(2*y+1)**2))**2, [0,inf], [0,inf])\\n        -1.74756459463318\\n\\n    Another example of a lattice sum in 2D::\\n\\n        >>> nsum(lambda x,y: (-1)**(x+y) / (x**2+y**2), [-inf,inf],\\n        ...     [-inf,inf], ignore=True)\\n        -2.1775860903036\\n        >>> -pi*ln2\\n        -2.1775860903036\\n\\n    An example of an Eisenstein series::\\n\\n        >>> nsum(lambda m,n: (m+n*1j)**(-4), [-inf,inf], [-inf,inf],\\n        ...     ignore=True)\\n        (3.1512120021539 + 0.0j)\\n\\n    **References**\\n\\n    1. [Weisstein]_ http://mathworld.wolfram.com/DoubleSeries.html,\\n    2. [Weisstein]_ http://mathworld.wolfram.com/MadelungConstants.html\\n\\n    \\\"\\\"\\\"\\n    infinite, g = standardize(ctx, f, intervals, options)\\n    if not infinite:\\n        return +g()\\n\\n    def update(partial_sums, indices):\\n        if partial_sums:\\n            psum = partial_sums[-1]\\n        else:\\n            psum = ctx.zero\\n        for k in indices:\\n            psum = psum + g(ctx.mpf(k))\\n            partial_sums.append(psum)\\n\\n    prec = ctx.prec\\n\\n    def emfun(point, tol):\\n        workprec = ctx.prec\\n        ctx.prec = prec + 10\\n        v = ctx.sumem(g, [point, ctx.inf], tol, error=1)\\n        ctx.prec = workprec\\n        return v\\n\\n    return +ctx.adaptive_extrapolation(update, emfun, options)\\n\\n\\ndef wrapsafe(f):\\n    def g(*args):\\n        try:\\n            return f(*args)\\n        except (ArithmeticError, ValueError):\\n            return 0\\n    return g\\n\\ndef standardize(ctx, f, intervals, options):\\n    if options.get(\\\"ignore\\\"):\\n        f = wrapsafe(f)\\n    finite = []\\n    infinite = []\\n    for k, points in enumerate(intervals):\\n        a, b = ctx._as_points(points)\\n        if b < a:\\n            return False, (lambda: ctx.zero)\\n        if a == ctx.ninf or b == ctx.inf:\\n            infinite.append((k, (a,b)))\\n        else:\\n            finite.append((k, (int(a), int(b))))\\n    if finite:\\n        f = fold_finite(ctx, f, finite)\\n        if not infinite:\\n            return False, lambda: f(*([0]*len(intervals)))\\n    if infinite:\\n        f = standardize_infinite(ctx, f, infinite)\\n        f = fold_infinite(ctx, f, infinite)\\n        args = [0] * len(intervals)\\n        d = infinite[0][0]\\n        def g(k):\\n            args[d] = k\\n            return f(*args)\\n        return True, g\\n\\n# backwards compatible itertools.product\\ndef cartesian_product(args):\\n    pools = map(tuple, args)\\n    result = [[]]\\n    for pool in pools:\\n        result = [x+[y] for x in result for y in pool]\\n    for prod in result:\\n        yield tuple(prod)\\n\\ndef fold_finite(ctx, f, intervals):\\n    if not intervals:\\n        return f\\n    indices = [v[0] for v in intervals]\\n    points = [v[1] for v in intervals]\\n    ranges = [xrange(a, b+1) for (a,b) in points]\\n    def g(*args):\\n        args = list(args)\\n        s = ctx.zero\\n        for xs in cartesian_product(ranges):\\n            for dim, x in zip(indices, xs):\\n                args[dim] = ctx.mpf(x)\\n            s += f(*args)\\n        return s\\n    #print \\\"Folded finite\\\", indices\\n    return g\\n\\n# Standardize each interval to [0,inf]\\ndef standardize_infinite(ctx, f, intervals):\\n    if not intervals:\\n        return f\\n    dim, [a,b] = intervals[-1]\\n    if a == ctx.ninf:\\n        if b == ctx.inf:\\n            def g(*args):\\n                args = list(args)\\n                k = args[dim]\\n                if k:\\n                    s = f(*args)\\n                    args[dim] = -k\\n                    s += f(*args)\\n                    return s\\n                else:\\n                    return f(*args)\\n        else:\\n            def g(*args):\\n                args = list(args)\\n                args[dim] = b - args[dim]\\n                return f(*args)\\n    else:\\n        def g(*args):\\n            args = list(args)\\n            args[dim] += a\\n            return f(*args)\\n    #print \\\"Standardized infinity along dimension\\\", dim, a, b\\n    return standardize_infinite(ctx, g, intervals[:-1])\\n\\ndef fold_infinite(ctx, f, intervals):\\n    if len(intervals) < 2:\\n        return f\\n    dim1 = intervals[-2][0]\\n    dim2 = intervals[-1][0]\\n    # Assume intervals are [0,inf] x [0,inf] x ...\\n    def g(*args):\\n        args = list(args)\\n        #args.insert(dim2, None)\\n        n = int(args[dim1])\\n        s = ctx.zero\\n        #y = ctx.mpf(n)\\n        args[dim2] = ctx.mpf(n) #y\\n        for x in xrange(n+1):\\n            args[dim1] = ctx.mpf(x)\\n            s += f(*args)\\n        args[dim1] = ctx.mpf(n) #ctx.mpf(n)\\n        for y in xrange(n):\\n            args[dim2] = ctx.mpf(y)\\n            s += f(*args)\\n        return s\\n    #print \\\"Folded infinite from\\\", len(intervals), \\\"to\\\", (len(intervals)-1)\\n    return fold_infinite(ctx, g, intervals[:-1])\\n\\n@defun\\ndef nprod(ctx, f, interval, nsum=False, **kwargs):\\n    r\\\"\\\"\\\"\\n    Computes the product\\n\\n    .. math ::\\n\\n        P = \\\\prod_{k=a}^b f(k)\\n\\n    where `(a, b)` = *interval*, and where `a = -\\\\infty` and/or\\n    `b = \\\\infty` are allowed.\\n\\n    By default, :func:`~mpmath.nprod` uses the same extrapolation methods as\\n    :func:`~mpmath.nsum`, except applied to the partial products rather than\\n    partial sums, and the same keyword options as for :func:`~mpmath.nsum` are\\n    supported. If ``nsum=True``, the product is instead computed via\\n    :func:`~mpmath.nsum` as\\n\\n    .. math ::\\n\\n        P = \\\\exp\\\\left( \\\\sum_{k=a}^b \\\\log(f(k)) \\\\right).\\n\\n    This is slower, but can sometimes yield better results. It is\\n    also required (and used automatically) when Euler-Maclaurin\\n    summation is requested.\\n\\n    **Examples**\\n\\n    A simple finite product::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 25; mp.pretty = True\\n        >>> nprod(lambda k: k, [1, 4])\\n        24.0\\n\\n    A large number of infinite products have known exact values,\\n    and can therefore be used as a reference. Most of the following\\n    examples are taken from MathWorld [1].\\n\\n    A few infinite products with simple values are::\\n\\n        >>> 2*nprod(lambda k: (4*k**2)/(4*k**2-1), [1, inf])\\n        3.141592653589793238462643\\n        >>> nprod(lambda k: (1+1/k)**2/(1+2/k), [1, inf])\\n        2.0\\n        >>> nprod(lambda k: (k**3-1)/(k**3+1), [2, inf])\\n        0.6666666666666666666666667\\n        >>> nprod(lambda k: (1-1/k**2), [2, inf])\\n        0.5\\n\\n    Next, several more infinite products with more complicated\\n    values::\\n\\n        >>> nprod(lambda k: exp(1/k**2), [1, inf]); exp(pi**2/6)\\n        5.180668317897115748416626\\n        5.180668317897115748416626\\n\\n        >>> nprod(lambda k: (k**2-1)/(k**2+1), [2, inf]); pi*csch(pi)\\n        0.2720290549821331629502366\\n        0.2720290549821331629502366\\n\\n        >>> nprod(lambda k: (k**4-1)/(k**4+1), [2, inf])\\n        0.8480540493529003921296502\\n        >>> pi*sinh(pi)/(cosh(sqrt(2)*pi)-cos(sqrt(2)*pi))\\n        0.8480540493529003921296502\\n\\n        >>> nprod(lambda k: (1+1/k+1/k**2)**2/(1+2/k+3/k**2), [1, inf])\\n        1.848936182858244485224927\\n        >>> 3*sqrt(2)*cosh(pi*sqrt(3)/2)**2*csch(pi*sqrt(2))/pi\\n        1.848936182858244485224927\\n\\n        >>> nprod(lambda k: (1-1/k**4), [2, inf]); sinh(pi)/(4*pi)\\n        0.9190194775937444301739244\\n        0.9190194775937444301739244\\n\\n        >>> nprod(lambda k: (1-1/k**6), [2, inf])\\n        0.9826842777421925183244759\\n        >>> (1+cosh(pi*sqrt(3)))/(12*pi**2)\\n        0.9826842777421925183244759\\n\\n        >>> nprod(lambda k: (1+1/k**2), [2, inf]); sinh(pi)/(2*pi)\\n        1.838038955187488860347849\\n        1.838038955187488860347849\\n\\n        >>> nprod(lambda n: (1+1/n)**n * exp(1/(2*n)-1), [1, inf])\\n        1.447255926890365298959138\\n        >>> exp(1+euler/2)/sqrt(2*pi)\\n        1.447255926890365298959138\\n\\n    The following two products are equivalent and can be evaluated in\\n    terms of a Jacobi theta function. Pi can be replaced by any value\\n    (as long as convergence is preserved)::\\n\\n        >>> nprod(lambda k: (1-pi**-k)/(1+pi**-k), [1, inf])\\n        0.3838451207481672404778686\\n        >>> nprod(lambda k: tanh(k*log(pi)/2), [1, inf])\\n        0.3838451207481672404778686\\n        >>> jtheta(4,0,1/pi)\\n        0.3838451207481672404778686\\n\\n    This product does not have a known closed form value::\\n\\n        >>> nprod(lambda k: (1-1/2**k), [1, inf])\\n        0.2887880950866024212788997\\n\\n    A product taken from `-\\\\infty`::\\n\\n        >>> nprod(lambda k: 1-k**(-3), [-inf,-2])\\n        0.8093965973662901095786805\\n        >>> cosh(pi*sqrt(3)/2)/(3*pi)\\n        0.8093965973662901095786805\\n\\n    A doubly infinite product::\\n\\n        >>> nprod(lambda k: exp(1/(1+k**2)), [-inf, inf])\\n        23.41432688231864337420035\\n        >>> exp(pi/tanh(pi))\\n        23.41432688231864337420035\\n\\n    A product requiring the use of Euler-Maclaurin summation to compute\\n    an accurate value::\\n\\n        >>> nprod(lambda k: (1-1/k**2.5), [2, inf], method='e')\\n        0.696155111336231052898125\\n\\n    **References**\\n\\n    1. [Weisstein]_ http://mathworld.wolfram.com/InfiniteProduct.html\\n\\n    \\\"\\\"\\\"\\n    if nsum or ('e' in kwargs.get('method', '')):\\n        orig = ctx.prec\\n        try:\\n            # TODO: we are evaluating log(1+eps) -> eps, which is\\n            # inaccurate. This currently works because nsum greatly\\n            # increases the working precision. But we should be\\n            # more intelligent and handle the precision here.\\n            ctx.prec += 10\\n            v = ctx.nsum(lambda n: ctx.ln(f(n)), interval, **kwargs)\\n        finally:\\n            ctx.prec = orig\\n        return +ctx.exp(v)\\n\\n    a, b = ctx._as_points(interval)\\n    if a == ctx.ninf:\\n        if b == ctx.inf:\\n            return f(0) * ctx.nprod(lambda k: f(-k) * f(k), [1, ctx.inf], **kwargs)\\n        return ctx.nprod(f, [-b, ctx.inf], **kwargs)\\n    elif b != ctx.inf:\\n        return ctx.fprod(f(ctx.mpf(k)) for k in xrange(int(a), int(b)+1))\\n\\n    a = int(a)\\n\\n    def update(partial_products, indices):\\n        if partial_products:\\n            pprod = partial_products[-1]\\n        else:\\n            pprod = ctx.one\\n        for k in indices:\\n            pprod = pprod * f(a + ctx.mpf(k))\\n            partial_products.append(pprod)\\n\\n    return +ctx.adaptive_extrapolation(update, None, kwargs)\\n\\n\\n@defun\\ndef limit(ctx, f, x, direction=1, exp=False, **kwargs):\\n    r\\\"\\\"\\\"\\n    Computes an estimate of the limit\\n\\n    .. math ::\\n\\n        \\\\lim_{t \\\\to x} f(t)\\n\\n    where `x` may be finite or infinite.\\n\\n    For finite `x`, :func:`~mpmath.limit` evaluates `f(x + d/n)` for\\n    consecutive integer values of `n`, where the approach direction\\n    `d` may be specified using the *direction* keyword argument.\\n    For infinite `x`, :func:`~mpmath.limit` evaluates values of\\n    `f(\\\\mathrm{sign}(x) \\\\cdot n)`.\\n\\n    If the approach to the limit is not sufficiently fast to give\\n    an accurate estimate directly, :func:`~mpmath.limit` attempts to find\\n    the limit using Richardson extrapolation or the Shanks\\n    transformation. You can select between these methods using\\n    the *method* keyword (see documentation of :func:`~mpmath.nsum` for\\n    more information).\\n\\n    **Options**\\n\\n    The following options are available with essentially the\\n    same meaning as for :func:`~mpmath.nsum`: *tol*, *method*, *maxterms*,\\n    *steps*, *verbose*.\\n\\n    If the option *exp=True* is set, `f` will be\\n    sampled at exponentially spaced points `n = 2^1, 2^2, 2^3, \\\\ldots`\\n    instead of the linearly spaced points `n = 1, 2, 3, \\\\ldots`.\\n    This can sometimes improve the rate of convergence so that\\n    :func:`~mpmath.limit` may return a more accurate answer (and faster).\\n    However, do note that this can only be used if `f`\\n    supports fast and accurate evaluation for arguments that\\n    are extremely close to the limit point (or if infinite,\\n    very large arguments).\\n\\n    **Examples**\\n\\n    A basic evaluation of a removable singularity::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 30; mp.pretty = True\\n        >>> limit(lambda x: (x-sin(x))/x**3, 0)\\n        0.166666666666666666666666666667\\n\\n    Computing the exponential function using its limit definition::\\n\\n        >>> limit(lambda n: (1+3/n)**n, inf)\\n        20.0855369231876677409285296546\\n        >>> exp(3)\\n        20.0855369231876677409285296546\\n\\n    A limit for `\\\\pi`::\\n\\n        >>> f = lambda n: 2**(4*n+1)*fac(n)**4/(2*n+1)/fac(2*n)**2\\n        >>> limit(f, inf)\\n        3.14159265358979323846264338328\\n\\n    Calculating the coefficient in Stirling's formula::\\n\\n        >>> limit(lambda n: fac(n) / (sqrt(n)*(n/e)**n), inf)\\n        2.50662827463100050241576528481\\n        >>> sqrt(2*pi)\\n        2.50662827463100050241576528481\\n\\n    Evaluating Euler's constant `\\\\gamma` using the limit representation\\n\\n    .. math ::\\n\\n        \\\\gamma = \\\\lim_{n \\\\rightarrow \\\\infty } \\\\left[ \\\\left(\\n        \\\\sum_{k=1}^n \\\\frac{1}{k} \\\\right) - \\\\log(n) \\\\right]\\n\\n    (which converges notoriously slowly)::\\n\\n        >>> f = lambda n: sum([mpf(1)/k for k in range(1,int(n)+1)]) - log(n)\\n        >>> limit(f, inf)\\n        0.577215664901532860606512090082\\n        >>> +euler\\n        0.577215664901532860606512090082\\n\\n    With default settings, the following limit converges too slowly\\n    to be evaluated accurately. Changing to exponential sampling\\n    however gives a perfect result::\\n\\n        >>> f = lambda x: sqrt(x**3+x**2)/(sqrt(x**3)+x)\\n        >>> limit(f, inf)\\n        0.992831158558330281129249686491\\n        >>> limit(f, inf, exp=True)\\n        1.0\\n\\n    \\\"\\\"\\\"\\n\\n    if ctx.isinf(x):\\n        direction = ctx.sign(x)\\n        g = lambda k: f(ctx.mpf(k+1)*direction)\\n    else:\\n        direction *= ctx.one\\n        g = lambda k: f(x + direction/(k+1))\\n    if exp:\\n        h = g\\n        g = lambda k: h(2**k)\\n\\n    def update(values, indices):\\n        for k in indices:\\n            values.append(g(k+1))\\n\\n    # XXX: steps used by nsum don't work well\\n    if not 'steps' in kwargs:\\n        kwargs['steps'] = [10]\\n\\n    return +ctx.adaptive_extrapolation(update, None, kwargs)\\n\\n\\nfrom ..libmp.backend import xrange\\nfrom .calculus import defun\\n\\n#----------------------------------------------------------------------------#\\n#                                Polynomials                                 #\\n#----------------------------------------------------------------------------#\\n\\n# XXX: extra precision\\n@defun\\ndef polyval(ctx, coeffs, x, derivative=False):\\n    r\\\"\\\"\\\"\\n    Given coefficients `[c_n, \\\\ldots, c_2, c_1, c_0]` and a number `x`,\\n    :func:`~mpmath.polyval` evaluates the polynomial\\n\\n    .. math ::\\n\\n        P(x) = c_n x^n + \\\\ldots + c_2 x^2 + c_1 x + c_0.\\n\\n    If *derivative=True* is set, :func:`~mpmath.polyval` simultaneously\\n    evaluates `P(x)` with the derivative, `P'(x)`, and returns the\\n    tuple `(P(x), P'(x))`.\\n\\n        >>> from mpmath import *\\n        >>> mp.pretty = True\\n        >>> polyval([3, 0, 2], 0.5)\\n        2.75\\n        >>> polyval([3, 0, 2], 0.5, derivative=True)\\n        (2.75, 3.0)\\n\\n    The coefficients and the evaluation point may be any combination\\n    of real or complex numbers.\\n    \\\"\\\"\\\"\\n    if not coeffs:\\n        return ctx.zero\\n    p = ctx.convert(coeffs[0])\\n    q = ctx.zero\\n    for c in coeffs[1:]:\\n        if derivative:\\n            q = p + x*q\\n        p = c + x*p\\n    if derivative:\\n        return p, q\\n    else:\\n        return p\\n\\n@defun\\ndef polyroots(ctx, coeffs, maxsteps=50, cleanup=True, extraprec=10,\\n        error=False, roots_init=None):\\n    \\\"\\\"\\\"\\n    Computes all roots (real or complex) of a given polynomial.\\n\\n    The roots are returned as a sorted list, where real roots appear first\\n    followed by complex conjugate roots as adjacent elements. The polynomial\\n    should be given as a list of coefficients, in the format used by\\n    :func:`~mpmath.polyval`. The leading coefficient must be nonzero.\\n\\n    With *error=True*, :func:`~mpmath.polyroots` returns a tuple *(roots, err)*\\n    where *err* is an estimate of the maximum error among the computed roots.\\n\\n    **Examples**\\n\\n    Finding the three real roots of `x^3 - x^2 - 14x + 24`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 15; mp.pretty = True\\n        >>> nprint(polyroots([1,-1,-14,24]), 4)\\n        [-4.0, 2.0, 3.0]\\n\\n    Finding the two complex conjugate roots of `4x^2 + 3x + 2`, with an\\n    error estimate::\\n\\n        >>> roots, err = polyroots([4,3,2], error=True)\\n        >>> for r in roots:\\n        ...     print(r)\\n        ...\\n        (-0.375 + 0.59947894041409j)\\n        (-0.375 - 0.59947894041409j)\\n        >>>\\n        >>> err\\n        2.22044604925031e-16\\n        >>>\\n        >>> polyval([4,3,2], roots[0])\\n        (2.22044604925031e-16 + 0.0j)\\n        >>> polyval([4,3,2], roots[1])\\n        (2.22044604925031e-16 + 0.0j)\\n\\n    The following example computes all the 5th roots of unity; that is,\\n    the roots of `x^5 - 1`::\\n\\n        >>> mp.dps = 20\\n        >>> for r in polyroots([1, 0, 0, 0, 0, -1]):\\n        ...     print(r)\\n        ...\\n        1.0\\n        (-0.8090169943749474241 + 0.58778525229247312917j)\\n        (-0.8090169943749474241 - 0.58778525229247312917j)\\n        (0.3090169943749474241 + 0.95105651629515357212j)\\n        (0.3090169943749474241 - 0.95105651629515357212j)\\n\\n    **Precision and conditioning**\\n\\n    The roots are computed to the current working precision accuracy. If this\\n    accuracy cannot be achieved in ``maxsteps`` steps, then a\\n    ``NoConvergence`` exception is raised. The algorithm internally is using\\n    the current working precision extended by ``extraprec``. If\\n    ``NoConvergence`` was raised, that is caused either by not having enough\\n    extra precision to achieve convergence (in which case increasing\\n    ``extraprec`` should fix the problem) or too low ``maxsteps`` (in which\\n    case increasing ``maxsteps`` should fix the problem), or a combination of\\n    both.\\n\\n    The user should always do a convergence study with regards to\\n    ``extraprec`` to ensure accurate results. It is possible to get\\n    convergence to a wrong answer with too low ``extraprec``.\\n\\n    Provided there are no repeated roots, :func:`~mpmath.polyroots` can\\n    typically compute all roots of an arbitrary polynomial to high precision::\\n\\n        >>> mp.dps = 60\\n        >>> for r in polyroots([1, 0, -10, 0, 1]):\\n        ...     print(r)\\n        ...\\n        -3.14626436994197234232913506571557044551247712918732870123249\\n        -0.317837245195782244725757617296174288373133378433432554879127\\n        0.317837245195782244725757617296174288373133378433432554879127\\n        3.14626436994197234232913506571557044551247712918732870123249\\n        >>>\\n        >>> sqrt(3) + sqrt(2)\\n        3.14626436994197234232913506571557044551247712918732870123249\\n        >>> sqrt(3) - sqrt(2)\\n        0.317837245195782244725757617296174288373133378433432554879127\\n\\n    **Algorithm**\\n\\n    :func:`~mpmath.polyroots` implements the Durand-Kerner method [1], which\\n    uses complex arithmetic to locate all roots simultaneously.\\n    The Durand-Kerner method can be viewed as approximately performing\\n    simultaneous Newton iteration for all the roots. In particular,\\n    the convergence to simple roots is quadratic, just like Newton's\\n    method.\\n\\n    Although all roots are internally calculated using complex arithmetic, any\\n    root found to have an imaginary part smaller than the estimated numerical\\n    error is truncated to a real number (small real parts are also chopped).\\n    Real roots are placed first in the returned list, sorted by value. The\\n    remaining complex roots are sorted by their real parts so that conjugate\\n    roots end up next to each other.\\n\\n    **References**\\n\\n    1. http://en.wikipedia.org/wiki/Durand-Kerner_method\\n\\n    \\\"\\\"\\\"\\n    if len(coeffs) <= 1:\\n        if not coeffs or not coeffs[0]:\\n            raise ValueError(\\\"Input to polyroots must not be the zero polynomial\\\")\\n        # Constant polynomial with no roots\\n        return []\\n\\n    orig = ctx.prec\\n    tol = +ctx.eps\\n    with ctx.extraprec(extraprec):\\n        deg = len(coeffs) - 1\\n        # Must be monic\\n        lead = ctx.convert(coeffs[0])\\n        if lead == 1:\\n            coeffs = [ctx.convert(c) for c in coeffs]\\n        else:\\n            coeffs = [c/lead for c in coeffs]\\n        f = lambda x: ctx.polyval(coeffs, x)\\n        if roots_init is None:\\n            roots = [ctx.mpc((0.4+0.9j)**n) for n in xrange(deg)]\\n        else:\\n            roots = [None]*deg;\\n            deg_init = min(deg, len(roots_init))\\n            roots[:deg_init] = list(roots_init[:deg_init])\\n            roots[deg_init:] = [ctx.mpc((0.4+0.9j)**n) for n\\n                                in xrange(deg_init,deg)]\\n        err = [ctx.one for n in xrange(deg)]\\n        # Durand-Kerner iteration until convergence\\n        for step in xrange(maxsteps):\\n            if abs(max(err)) < tol:\\n                break\\n            for i in xrange(deg):\\n                p = roots[i]\\n                x = f(p)\\n                for j in range(deg):\\n                    if i != j:\\n                        try:\\n                            x /= (p-roots[j])\\n                        except ZeroDivisionError:\\n                            continue\\n                roots[i] = p - x\\n                err[i] = abs(x)\\n        if abs(max(err)) >= tol:\\n            raise ctx.NoConvergence(\\\"Didn't converge in maxsteps=%d steps.\\\" \\\\\\n                    % maxsteps)\\n        # Remove small real or imaginary parts\\n        if cleanup:\\n            for i in xrange(deg):\\n                if abs(roots[i]) < tol:\\n                    roots[i] = ctx.zero\\n                elif abs(ctx._im(roots[i])) < tol:\\n                    roots[i] = roots[i].real\\n                elif abs(ctx._re(roots[i])) < tol:\\n                    roots[i] = roots[i].imag * 1j\\n        roots.sort(key=lambda x: (abs(ctx._im(x)), ctx._re(x)))\\n    if error:\\n        err = max(err)\\n        err = max(err, ctx.ldexp(1, -orig+1))\\n        return [+r for r in roots], +err\\n    else:\\n        return [+r for r in roots]\\n\\n\\nimport math\\n\\nfrom ..libmp.backend import xrange\\n\\nclass QuadratureRule(object):\\n    \\\"\\\"\\\"\\n    Quadrature rules are implemented using this class, in order to\\n    simplify the code and provide a common infrastructure\\n    for tasks such as error estimation and node caching.\\n\\n    You can implement a custom quadrature rule by subclassing\\n    :class:`QuadratureRule` and implementing the appropriate\\n    methods. The subclass can then be used by :func:`~mpmath.quad` by\\n    passing it as the *method* argument.\\n\\n    :class:`QuadratureRule` instances are supposed to be singletons.\\n    :class:`QuadratureRule` therefore implements instance caching\\n    in :func:`~mpmath.__new__`.\\n    \\\"\\\"\\\"\\n\\n    def __init__(self, ctx):\\n        self.ctx = ctx\\n        self.standard_cache = {}\\n        self.transformed_cache = {}\\n        self.interval_count = {}\\n\\n    def clear(self):\\n        \\\"\\\"\\\"\\n        Delete cached node data.\\n        \\\"\\\"\\\"\\n        self.standard_cache = {}\\n        self.transformed_cache = {}\\n        self.interval_count = {}\\n\\n    def calc_nodes(self, degree, prec, verbose=False):\\n        r\\\"\\\"\\\"\\n        Compute nodes for the standard interval `[-1, 1]`. Subclasses\\n        should probably implement only this method, and use\\n        :func:`~mpmath.get_nodes` method to retrieve the nodes.\\n        \\\"\\\"\\\"\\n        raise NotImplementedError\\n\\n    def get_nodes(self, a, b, degree, prec, verbose=False):\\n        \\\"\\\"\\\"\\n        Return nodes for given interval, degree and precision. The\\n        nodes are retrieved from a cache if already computed;\\n        otherwise they are computed by calling :func:`~mpmath.calc_nodes`\\n        and are then cached.\\n\\n        Subclasses should probably not implement this method,\\n        but just implement :func:`~mpmath.calc_nodes` for the actual\\n        node computation.\\n        \\\"\\\"\\\"\\n        key = (a, b, degree, prec)\\n        if key in self.transformed_cache:\\n            return self.transformed_cache[key]\\n        orig = self.ctx.prec\\n        try:\\n            self.ctx.prec = prec+20\\n            # Get nodes on standard interval\\n            if (degree, prec) in self.standard_cache:\\n                nodes = self.standard_cache[degree, prec]\\n            else:\\n                nodes = self.calc_nodes(degree, prec, verbose)\\n                self.standard_cache[degree, prec] = nodes\\n            # Transform to general interval\\n            nodes = self.transform_nodes(nodes, a, b, verbose)\\n            if key in self.interval_count:\\n                self.transformed_cache[key] = nodes\\n            else:\\n                self.interval_count[key] = True\\n        finally:\\n            self.ctx.prec = orig\\n        return nodes\\n\\n    def transform_nodes(self, nodes, a, b, verbose=False):\\n        r\\\"\\\"\\\"\\n        Rescale standardized nodes (for `[-1, 1]`) to a general\\n        interval `[a, b]`. For a finite interval, a simple linear\\n        change of variables is used. Otherwise, the following\\n        transformations are used:\\n\\n        .. math ::\\n\\n            \\\\lbrack a, \\\\infty \\\\rbrack : t = \\\\frac{1}{x} + (a-1)\\n\\n            \\\\lbrack -\\\\infty, b \\\\rbrack : t = (b+1) - \\\\frac{1}{x}\\n\\n            \\\\lbrack -\\\\infty, \\\\infty \\\\rbrack : t = \\\\frac{x}{\\\\sqrt{1-x^2}}\\n\\n        \\\"\\\"\\\"\\n        ctx = self.ctx\\n        a = ctx.convert(a)\\n        b = ctx.convert(b)\\n        one = ctx.one\\n        if (a, b) == (-one, one):\\n            return nodes\\n        half = ctx.mpf(0.5)\\n        new_nodes = []\\n        if ctx.isinf(a) or ctx.isinf(b):\\n            if (a, b) == (ctx.ninf, ctx.inf):\\n                p05 = -half\\n                for x, w in nodes:\\n                    x2 = x*x\\n                    px1 = one-x2\\n                    spx1 = px1**p05\\n                    x = x*spx1\\n                    w *= spx1/px1\\n                    new_nodes.append((x, w))\\n            elif a == ctx.ninf:\\n                b1 = b+1\\n                for x, w in nodes:\\n                    u = 2/(x+one)\\n                    x = b1-u\\n                    w *= half*u**2\\n                    new_nodes.append((x, w))\\n            elif b == ctx.inf:\\n                a1 = a-1\\n                for x, w in nodes:\\n                    u = 2/(x+one)\\n                    x = a1+u\\n                    w *= half*u**2\\n                    new_nodes.append((x, w))\\n            elif a == ctx.inf or b == ctx.ninf:\\n                return [(x,-w) for (x,w) in self.transform_nodes(nodes, b, a, verbose)]\\n            else:\\n                raise NotImplementedError\\n        else:\\n            # Simple linear change of variables\\n            C = (b-a)/2\\n            D = (b+a)/2\\n            for x, w in nodes:\\n                new_nodes.append((D+C*x, C*w))\\n        return new_nodes\\n\\n    def guess_degree(self, prec):\\n        \\\"\\\"\\\"\\n        Given a desired precision `p` in bits, estimate the degree `m`\\n        of the quadrature required to accomplish full accuracy for\\n        typical integrals. By default, :func:`~mpmath.quad` will perform up\\n        to `m` iterations. The value of `m` should be a slight\\n        overestimate, so that \\\"slightly bad\\\" integrals can be dealt\\n        with automatically using a few extra iterations. On the\\n        other hand, it should not be too big, so :func:`~mpmath.quad` can\\n        quit within a reasonable amount of time when it is given\\n        an \\\"unsolvable\\\" integral.\\n\\n        The default formula used by :func:`~mpmath.guess_degree` is tuned\\n        for both :class:`TanhSinh` and :class:`GaussLegendre`.\\n        The output is roughly as follows:\\n\\n            +---------+---------+\\n            | `p`     | `m`     |\\n            +=========+=========+\\n            | 50      | 6       |\\n            +---------+---------+\\n            | 100     | 7       |\\n            +---------+---------+\\n            | 500     | 10      |\\n            +---------+---------+\\n            | 3000    | 12      |\\n            +---------+---------+\\n\\n        This formula is based purely on a limited amount of\\n        experimentation and will sometimes be wrong.\\n        \\\"\\\"\\\"\\n        # Expected degree\\n        # XXX: use mag\\n        g = int(4 + max(0, self.ctx.log(prec/30.0, 2)))\\n        # Reasonable \\\"worst case\\\"\\n        g += 2\\n        return g\\n\\n    def estimate_error(self, results, prec, epsilon):\\n        r\\\"\\\"\\\"\\n        Given results from integrations `[I_1, I_2, \\\\ldots, I_k]` done\\n        with a quadrature of rule of degree `1, 2, \\\\ldots, k`, estimate\\n        the error of `I_k`.\\n\\n        For `k = 2`, we estimate  `|I_{\\\\infty}-I_2|` as `|I_2-I_1|`.\\n\\n        For `k > 2`, we extrapolate `|I_{\\\\infty}-I_k| \\\\approx |I_{k+1}-I_k|`\\n        from `|I_k-I_{k-1}|` and `|I_k-I_{k-2}|` under the assumption\\n        that each degree increment roughly doubles the accuracy of\\n        the quadrature rule (this is true for both :class:`TanhSinh`\\n        and :class:`GaussLegendre`). The extrapolation formula is given\\n        by Borwein, Bailey & Girgensohn. Although not very conservative,\\n        this method seems to be very robust in practice.\\n        \\\"\\\"\\\"\\n        if len(results) == 2:\\n            return abs(results[0]-results[1])\\n        try:\\n            if results[-1] == results[-2] == results[-3]:\\n                return self.ctx.zero\\n            D1 = self.ctx.log(abs(results[-1]-results[-2]), 10)\\n            D2 = self.ctx.log(abs(results[-1]-results[-3]), 10)\\n        except ValueError:\\n            return epsilon\\n        D3 = -prec\\n        D4 = min(0, max(D1**2/D2, 2*D1, D3))\\n        return self.ctx.mpf(10) ** int(D4)\\n\\n    def summation(self, f, points, prec, epsilon, max_degree, verbose=False):\\n        \\\"\\\"\\\"\\n        Main integration function. Computes the 1D integral over\\n        the interval specified by *points*. For each subinterval,\\n        performs quadrature of degree from 1 up to *max_degree*\\n        until :func:`~mpmath.estimate_error` signals convergence.\\n\\n        :func:`~mpmath.summation` transforms each subintegration to\\n        the standard interval and then calls :func:`~mpmath.sum_next`.\\n        \\\"\\\"\\\"\\n        ctx = self.ctx\\n        I = total_err = ctx.zero\\n        for i in xrange(len(points)-1):\\n            a, b = points[i], points[i+1]\\n            if a == b:\\n                continue\\n            # XXX: we could use a single variable transformation,\\n            # but this is not good in practice. We get better accuracy\\n            # by having 0 as an endpoint.\\n            if (a, b) == (ctx.ninf, ctx.inf):\\n                _f = f\\n                f = lambda x: _f(-x) + _f(x)\\n                a, b = (ctx.zero, ctx.inf)\\n            results = []\\n            err = ctx.zero\\n            for degree in xrange(1, max_degree+1):\\n                nodes = self.get_nodes(a, b, degree, prec, verbose)\\n                if verbose:\\n                    print(\\\"Integrating from %s to %s (degree %s of %s)\\\" % \\\\\\n                        (ctx.nstr(a), ctx.nstr(b), degree, max_degree))\\n                result = self.sum_next(f, nodes, degree, prec, results, verbose)\\n                results.append(result)\\n                if degree > 1:\\n                    err = self.estimate_error(results, prec, epsilon)\\n                    if verbose:\\n                        print(\\\"Estimated error:\\\", ctx.nstr(err), \\\" epsilon:\\\", ctx.nstr(epsilon), \\\" result: \\\", ctx.nstr(result))\\n                    if err <= epsilon:\\n                        break\\n            I += results[-1]\\n            total_err += err\\n        if total_err > epsilon:\\n            if verbose:\\n                print(\\\"Failed to reach full accuracy. Estimated error:\\\", ctx.nstr(total_err))\\n        return I, total_err\\n\\n    def sum_next(self, f, nodes, degree, prec, previous, verbose=False):\\n        r\\\"\\\"\\\"\\n        Evaluates the step sum `\\\\sum w_k f(x_k)` where the *nodes* list\\n        contains the `(w_k, x_k)` pairs.\\n\\n        :func:`~mpmath.summation` will supply the list *results* of\\n        values computed by :func:`~mpmath.sum_next` at previous degrees, in\\n        case the quadrature rule is able to reuse them.\\n        \\\"\\\"\\\"\\n        return self.ctx.fdot((w, f(x)) for (x,w) in nodes)\\n\\n\\nclass TanhSinh(QuadratureRule):\\n    r\\\"\\\"\\\"\\n    This class implements \\\"tanh-sinh\\\" or \\\"doubly exponential\\\"\\n    quadrature. This quadrature rule is based on the Euler-Maclaurin\\n    integral formula. By performing a change of variables involving\\n    nested exponentials / hyperbolic functions (hence the name), the\\n    derivatives at the endpoints vanish rapidly. Since the error term\\n    in the Euler-Maclaurin formula depends on the derivatives at the\\n    endpoints, a simple step sum becomes extremely accurate. In\\n    practice, this means that doubling the number of evaluation\\n    points roughly doubles the number of accurate digits.\\n\\n    Comparison to Gauss-Legendre:\\n      * Initial computation of nodes is usually faster\\n      * Handles endpoint singularities better\\n      * Handles infinite integration intervals better\\n      * Is slower for smooth integrands once nodes have been computed\\n\\n    The implementation of the tanh-sinh algorithm is based on the\\n    description given in Borwein, Bailey & Girgensohn, \\\"Experimentation\\n    in Mathematics - Computational Paths to Discovery\\\", A K Peters,\\n    2003, pages 312-313. In the present implementation, a few\\n    improvements have been made:\\n\\n      * A more efficient scheme is used to compute nodes (exploiting\\n        recurrence for the exponential function)\\n      * The nodes are computed successively instead of all at once\\n\\n    **References**\\n\\n    * [Bailey]_\\n    * http://users.cs.dal.ca/~jborwein/tanh-sinh.pdf\\n\\n    \\\"\\\"\\\"\\n\\n    def sum_next(self, f, nodes, degree, prec, previous, verbose=False):\\n        \\\"\\\"\\\"\\n        Step sum for tanh-sinh quadrature of degree `m`. We exploit the\\n        fact that half of the abscissas at degree `m` are precisely the\\n        abscissas from degree `m-1`. Thus reusing the result from\\n        the previous level allows a 2x speedup.\\n        \\\"\\\"\\\"\\n        h = self.ctx.mpf(2)**(-degree)\\n        # Abscissas overlap, so reusing saves half of the time\\n        if previous:\\n            S = previous[-1]/(h*2)\\n        else:\\n            S = self.ctx.zero\\n        S += self.ctx.fdot((w,f(x)) for (x,w) in nodes)\\n        return h*S\\n\\n    def calc_nodes(self, degree, prec, verbose=False):\\n        r\\\"\\\"\\\"\\n        The abscissas and weights for tanh-sinh quadrature of degree\\n        `m` are given by\\n\\n        .. math::\\n\\n            x_k = \\\\tanh(\\\\pi/2 \\\\sinh(t_k))\\n\\n            w_k = \\\\pi/2 \\\\cosh(t_k) / \\\\cosh(\\\\pi/2 \\\\sinh(t_k))^2\\n\\n        where `t_k = t_0 + hk` for a step length `h \\\\sim 2^{-m}`. The\\n        list of nodes is actually infinite, but the weights die off so\\n        rapidly that only a few are needed.\\n        \\\"\\\"\\\"\\n        ctx = self.ctx\\n        nodes = []\\n\\n        extra = 20\\n        ctx.prec += extra\\n        tol = ctx.ldexp(1, -prec-10)\\n        pi4 = ctx.pi/4\\n\\n        # For simplicity, we work in steps h = 1/2^n, with the first point\\n        # offset so that we can reuse the sum from the previous degree\\n\\n        # We define degree 1 to include the \\\"degree 0\\\" steps, including\\n        # the point x = 0. (It doesn't work well otherwise; not sure why.)\\n        t0 = ctx.ldexp(1, -degree)\\n        if degree == 1:\\n            #nodes.append((mpf(0), pi4))\\n            #nodes.append((-mpf(0), pi4))\\n            nodes.append((ctx.zero, ctx.pi/2))\\n            h = t0\\n        else:\\n            h = t0*2\\n\\n        # Since h is fixed, we can compute the next exponential\\n        # by simply multiplying by exp(h)\\n        expt0 = ctx.exp(t0)\\n        a = pi4 * expt0\\n        b = pi4 / expt0\\n        udelta = ctx.exp(h)\\n        urdelta = 1/udelta\\n\\n        for k in xrange(0, 20*2**degree+1):\\n            # Reference implementation:\\n            # t = t0 + k*h\\n            # x = tanh(pi/2 * sinh(t))\\n            # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2\\n\\n            # Fast implementation. Note that c = exp(pi/2 * sinh(t))\\n            c = ctx.exp(a-b)\\n            d = 1/c\\n            co = (c+d)/2\\n            si = (c-d)/2\\n            x = si / co\\n            w = (a+b) / co**2\\n            diff = abs(x-1)\\n            if diff <= tol:\\n                break\\n\\n            nodes.append((x, w))\\n            nodes.append((-x, w))\\n\\n            a *= udelta\\n            b *= urdelta\\n\\n            if verbose and k % 300 == 150:\\n                # Note: the number displayed is rather arbitrary. Should\\n                # figure out how to print something that looks more like a\\n                # percentage\\n                print(\\\"Calculating nodes:\\\", ctx.nstr(-ctx.log(diff, 10) / prec))\\n\\n        ctx.prec -= extra\\n        return nodes\\n\\n\\nclass GaussLegendre(QuadratureRule):\\n    r\\\"\\\"\\\"\\n    This class implements Gauss-Legendre quadrature, which is\\n    exceptionally efficient for polynomials and polynomial-like (i.e.\\n    very smooth) integrands.\\n\\n    The abscissas and weights are given by roots and values of\\n    Legendre polynomials, which are the orthogonal polynomials\\n    on `[-1, 1]` with respect to the unit weight\\n    (see :func:`~mpmath.legendre`).\\n\\n    In this implementation, we take the \\\"degree\\\" `m` of the quadrature\\n    to denote a Gauss-Legendre rule of degree `3 \\\\cdot 2^m` (following\\n    Borwein, Bailey & Girgensohn). This way we get quadratic, rather\\n    than linear, convergence as the degree is incremented.\\n\\n    Comparison to tanh-sinh quadrature:\\n      * Is faster for smooth integrands once nodes have been computed\\n      * Initial computation of nodes is usually slower\\n      * Handles endpoint singularities worse\\n      * Handles infinite integration intervals worse\\n\\n    \\\"\\\"\\\"\\n\\n    def calc_nodes(self, degree, prec, verbose=False):\\n        r\\\"\\\"\\\"\\n        Calculates the abscissas and weights for Gauss-Legendre\\n        quadrature of degree of given degree (actually `3 \\\\cdot 2^m`).\\n        \\\"\\\"\\\"\\n        ctx = self.ctx\\n        # It is important that the epsilon is set lower than the\\n        # \\\"real\\\" epsilon\\n        epsilon = ctx.ldexp(1, -prec-8)\\n        # Fairly high precision might be required for accurate\\n        # evaluation of the roots\\n        orig = ctx.prec\\n        ctx.prec = int(prec*1.5)\\n        if degree == 1:\\n            x = ctx.sqrt(ctx.mpf(3)/5)\\n            w = ctx.mpf(5)/9\\n            nodes = [(-x,w),(ctx.zero,ctx.mpf(8)/9),(x,w)]\\n            ctx.prec = orig\\n            return nodes\\n        nodes = []\\n        n = 3*2**(degree-1)\\n        upto = n//2 + 1\\n        for j in xrange(1, upto):\\n            # Asymptotic formula for the roots\\n            r = ctx.mpf(math.cos(math.pi*(j-0.25)/(n+0.5)))\\n            # Newton iteration\\n            while 1:\\n                t1, t2 = 1, 0\\n                # Evaluates the Legendre polynomial using its defining\\n                # recurrence relation\\n                for j1 in xrange(1,n+1):\\n                    t3, t2, t1 = t2, t1, ((2*j1-1)*r*t1 - (j1-1)*t2)/j1\\n                t4 = n*(r*t1-t2)/(r**2-1)\\n                a = t1/t4\\n                r = r - a\\n                if abs(a) < epsilon:\\n                    break\\n            x = r\\n            w = 2/((1-r**2)*t4**2)\\n            if verbose  and j % 30 == 15:\\n                print(\\\"Computing nodes (%i of %i)\\\" % (j, upto))\\n            nodes.append((x, w))\\n            nodes.append((-x, w))\\n        ctx.prec = orig\\n        return nodes\\n\\nclass QuadratureMethods(object):\\n\\n    def __init__(ctx, *args, **kwargs):\\n        ctx._gauss_legendre = GaussLegendre(ctx)\\n        ctx._tanh_sinh = TanhSinh(ctx)\\n\\n    def quad(ctx, f, *points, **kwargs):\\n        r\\\"\\\"\\\"\\n        Computes a single, double or triple integral over a given\\n        1D interval, 2D rectangle, or 3D cuboid. A basic example::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> quad(sin, [0, pi])\\n            2.0\\n\\n        A basic 2D integral::\\n\\n            >>> f = lambda x, y: cos(x+y/2)\\n            >>> quad(f, [-pi/2, pi/2], [0, pi])\\n            4.0\\n\\n        **Interval format**\\n\\n        The integration range for each dimension may be specified\\n        using a list or tuple. Arguments are interpreted as follows:\\n\\n        ``quad(f, [x1, x2])`` -- calculates\\n        `\\\\int_{x_1}^{x_2} f(x) \\\\, dx`\\n\\n        ``quad(f, [x1, x2], [y1, y2])`` -- calculates\\n        `\\\\int_{x_1}^{x_2} \\\\int_{y_1}^{y_2} f(x,y) \\\\, dy \\\\, dx`\\n\\n        ``quad(f, [x1, x2], [y1, y2], [z1, z2])`` -- calculates\\n        `\\\\int_{x_1}^{x_2} \\\\int_{y_1}^{y_2} \\\\int_{z_1}^{z_2} f(x,y,z)\\n        \\\\, dz \\\\, dy \\\\, dx`\\n\\n        Endpoints may be finite or infinite. An interval descriptor\\n        may also contain more than two points. In this\\n        case, the integration is split into subintervals, between\\n        each pair of consecutive points. This is useful for\\n        dealing with mid-interval discontinuities, or integrating\\n        over large intervals where the function is irregular or\\n        oscillates.\\n\\n        **Options**\\n\\n        :func:`~mpmath.quad` recognizes the following keyword arguments:\\n\\n        *method*\\n            Chooses integration algorithm (described below).\\n        *error*\\n            If set to true, :func:`~mpmath.quad` returns `(v, e)` where `v` is the\\n            integral and `e` is the estimated error.\\n        *maxdegree*\\n            Maximum degree of the quadrature rule to try before\\n            quitting.\\n        *verbose*\\n            Print details about progress.\\n\\n        **Algorithms**\\n\\n        Mpmath presently implements two integration algorithms: tanh-sinh\\n        quadrature and Gauss-Legendre quadrature. These can be selected\\n        using *method='tanh-sinh'* or *method='gauss-legendre'* or by\\n        passing the classes *method=TanhSinh*, *method=GaussLegendre*.\\n        The functions :func:`~mpmath.quadts` and :func:`~mpmath.quadgl` are also available\\n        as shortcuts.\\n\\n        Both algorithms have the property that doubling the number of\\n        evaluation points roughly doubles the accuracy, so both are ideal\\n        for high precision quadrature (hundreds or thousands of digits).\\n\\n        At high precision, computing the nodes and weights for the\\n        integration can be expensive (more expensive than computing the\\n        function values). To make repeated integrations fast, nodes\\n        are automatically cached.\\n\\n        The advantages of the tanh-sinh algorithm are that it tends to\\n        handle endpoint singularities well, and that the nodes are cheap\\n        to compute on the first run. For these reasons, it is used by\\n        :func:`~mpmath.quad` as the default algorithm.\\n\\n        Gauss-Legendre quadrature often requires fewer function\\n        evaluations, and is therefore often faster for repeated use, but\\n        the algorithm does not handle endpoint singularities as well and\\n        the nodes are more expensive to compute. Gauss-Legendre quadrature\\n        can be a better choice if the integrand is smooth and repeated\\n        integrations are required (e.g. for multiple integrals).\\n\\n        See the documentation for :class:`TanhSinh` and\\n        :class:`GaussLegendre` for additional details.\\n\\n        **Examples of 1D integrals**\\n\\n        Intervals may be infinite or half-infinite. The following two\\n        examples evaluate the limits of the inverse tangent function\\n        (`\\\\int 1/(1+x^2) = \\\\tan^{-1} x`), and the Gaussian integral\\n        `\\\\int_{\\\\infty}^{\\\\infty} \\\\exp(-x^2)\\\\,dx = \\\\sqrt{\\\\pi}`::\\n\\n            >>> mp.dps = 15\\n            >>> quad(lambda x: 2/(x**2+1), [0, inf])\\n            3.14159265358979\\n            >>> quad(lambda x: exp(-x**2), [-inf, inf])**2\\n            3.14159265358979\\n\\n        Integrals can typically be resolved to high precision.\\n        The following computes 50 digits of `\\\\pi` by integrating the\\n        area of the half-circle defined by `x^2 + y^2 \\\\le 1`,\\n        `-1 \\\\le x \\\\le 1`, `y \\\\ge 0`::\\n\\n            >>> mp.dps = 50\\n            >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1])\\n            3.1415926535897932384626433832795028841971693993751\\n\\n        One can just as well compute 1000 digits (output truncated)::\\n\\n            >>> mp.dps = 1000\\n            >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1])  #doctest:+ELLIPSIS\\n            3.141592653589793238462643383279502884...216420199\\n\\n        Complex integrals are supported. The following computes\\n        a residue at `z = 0` by integrating counterclockwise along the\\n        diamond-shaped path from `1` to `+i` to `-1` to `-i` to `1`::\\n\\n            >>> mp.dps = 15\\n            >>> chop(quad(lambda z: 1/z, [1,j,-1,-j,1]))\\n            (0.0 + 6.28318530717959j)\\n\\n        **Examples of 2D and 3D integrals**\\n\\n        Here are several nice examples of analytically solvable\\n        2D integrals (taken from MathWorld [1]) that can be evaluated\\n        to high precision fairly rapidly by :func:`~mpmath.quad`::\\n\\n            >>> mp.dps = 30\\n            >>> f = lambda x, y: (x-1)/((1-x*y)*log(x*y))\\n            >>> quad(f, [0, 1], [0, 1])\\n            0.577215664901532860606512090082\\n            >>> +euler\\n            0.577215664901532860606512090082\\n\\n            >>> f = lambda x, y: 1/sqrt(1+x**2+y**2)\\n            >>> quad(f, [-1, 1], [-1, 1])\\n            3.17343648530607134219175646705\\n            >>> 4*log(2+sqrt(3))-2*pi/3\\n            3.17343648530607134219175646705\\n\\n            >>> f = lambda x, y: 1/(1-x**2 * y**2)\\n            >>> quad(f, [0, 1], [0, 1])\\n            1.23370055013616982735431137498\\n            >>> pi**2 / 8\\n            1.23370055013616982735431137498\\n\\n            >>> quad(lambda x, y: 1/(1-x*y), [0, 1], [0, 1])\\n            1.64493406684822643647241516665\\n            >>> pi**2 / 6\\n            1.64493406684822643647241516665\\n\\n        Multiple integrals may be done over infinite ranges::\\n\\n            >>> mp.dps = 15\\n            >>> print(quad(lambda x,y: exp(-x-y), [0, inf], [1, inf]))\\n            0.367879441171442\\n            >>> print(1/e)\\n            0.367879441171442\\n\\n        For nonrectangular areas, one can call :func:`~mpmath.quad` recursively.\\n        For example, we can replicate the earlier example of calculating\\n        `\\\\pi` by integrating over the unit-circle, and actually use double\\n        quadrature to actually measure the area circle::\\n\\n            >>> f = lambda x: quad(lambda y: 1, [-sqrt(1-x**2), sqrt(1-x**2)])\\n            >>> quad(f, [-1, 1])\\n            3.14159265358979\\n\\n        Here is a simple triple integral::\\n\\n            >>> mp.dps = 15\\n            >>> f = lambda x,y,z: x*y/(1+z)\\n            >>> quad(f, [0,1], [0,1], [1,2], method='gauss-legendre')\\n            0.101366277027041\\n            >>> (log(3)-log(2))/4\\n            0.101366277027041\\n\\n        **Singularities**\\n\\n        Both tanh-sinh and Gauss-Legendre quadrature are designed to\\n        integrate smooth (infinitely differentiable) functions. Neither\\n        algorithm copes well with mid-interval singularities (such as\\n        mid-interval discontinuities in `f(x)` or `f'(x)`).\\n        The best solution is to split the integral into parts::\\n\\n            >>> mp.dps = 15\\n            >>> quad(lambda x: abs(sin(x)), [0, 2*pi])   # Bad\\n            3.99900894176779\\n            >>> quad(lambda x: abs(sin(x)), [0, pi, 2*pi])  # Good\\n            4.0\\n\\n        The tanh-sinh rule often works well for integrands having a\\n        singularity at one or both endpoints::\\n\\n            >>> mp.dps = 15\\n            >>> quad(log, [0, 1], method='tanh-sinh')  # Good\\n            -1.0\\n            >>> quad(log, [0, 1], method='gauss-legendre')  # Bad\\n            -0.999932197413801\\n\\n        However, the result may still be inaccurate for some functions::\\n\\n            >>> quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh')\\n            1.99999999946942\\n\\n        This problem is not due to the quadrature rule per se, but to\\n        numerical amplification of errors in the nodes. The problem can be\\n        circumvented by temporarily increasing the precision::\\n\\n            >>> mp.dps = 30\\n            >>> a = quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh')\\n            >>> mp.dps = 15\\n            >>> +a\\n            2.0\\n\\n        **Highly variable functions**\\n\\n        For functions that are smooth (in the sense of being infinitely\\n        differentiable) but contain sharp mid-interval peaks or many\\n        \\\"bumps\\\", :func:`~mpmath.quad` may fail to provide full accuracy. For\\n        example, with default settings, :func:`~mpmath.quad` is able to integrate\\n        `\\\\sin(x)` accurately over an interval of length 100 but not over\\n        length 1000::\\n\\n            >>> quad(sin, [0, 100]); 1-cos(100)   # Good\\n            0.137681127712316\\n            0.137681127712316\\n            >>> quad(sin, [0, 1000]); 1-cos(1000)   # Bad\\n            -37.8587612408485\\n            0.437620923709297\\n\\n        One solution is to break the integration into 10 intervals of\\n        length 100::\\n\\n            >>> quad(sin, linspace(0, 1000, 10))   # Good\\n            0.437620923709297\\n\\n        Another is to increase the degree of the quadrature::\\n\\n            >>> quad(sin, [0, 1000], maxdegree=10)   # Also good\\n            0.437620923709297\\n\\n        Whether splitting the interval or increasing the degree is\\n        more efficient differs from case to case. Another example is the\\n        function `1/(1+x^2)`, which has a sharp peak centered around\\n        `x = 0`::\\n\\n            >>> f = lambda x: 1/(1+x**2)\\n            >>> quad(f, [-100, 100])   # Bad\\n            3.64804647105268\\n            >>> quad(f, [-100, 100], maxdegree=10)   # Good\\n            3.12159332021646\\n            >>> quad(f, [-100, 0, 100])   # Also good\\n            3.12159332021646\\n\\n        **References**\\n\\n        1. http://mathworld.wolfram.com/DoubleIntegral.html\\n\\n        \\\"\\\"\\\"\\n        rule = kwargs.get('method', 'tanh-sinh')\\n        if type(rule) is str:\\n            if rule == 'tanh-sinh':\\n                rule = ctx._tanh_sinh\\n            elif rule == 'gauss-legendre':\\n                rule = ctx._gauss_legendre\\n            else:\\n                raise ValueError(\\\"unknown quadrature rule: %s\\\" % rule)\\n        else:\\n            rule = rule(ctx)\\n        verbose = kwargs.get('verbose')\\n        dim = len(points)\\n        orig = prec = ctx.prec\\n        epsilon = ctx.eps/8\\n        m = kwargs.get('maxdegree') or rule.guess_degree(prec)\\n        points = [ctx._as_points(p) for p in points]\\n        try:\\n            ctx.prec += 20\\n            if dim == 1:\\n                v, err = rule.summation(f, points[0], prec, epsilon, m, verbose)\\n            elif dim == 2:\\n                v, err = rule.summation(lambda x: \\\\\\n                        rule.summation(lambda y: f(x,y), \\\\\\n                        points[1], prec, epsilon, m)[0],\\n                    points[0], prec, epsilon, m, verbose)\\n            elif dim == 3:\\n                v, err = rule.summation(lambda x: \\\\\\n                        rule.summation(lambda y: \\\\\\n                            rule.summation(lambda z: f(x,y,z), \\\\\\n                            points[2], prec, epsilon, m)[0],\\n                        points[1], prec, epsilon, m)[0],\\n                    points[0], prec, epsilon, m, verbose)\\n            else:\\n                raise NotImplementedError(\\\"quadrature must have dim 1, 2 or 3\\\")\\n        finally:\\n            ctx.prec = orig\\n        if kwargs.get(\\\"error\\\"):\\n            return +v, err\\n        return +v\\n\\n    def quadts(ctx, *args, **kwargs):\\n        \\\"\\\"\\\"\\n        Performs tanh-sinh quadrature. The call\\n\\n            quadts(func, *points, ...)\\n\\n        is simply a shortcut for:\\n\\n            quad(func, *points, ..., method=TanhSinh)\\n\\n        For example, a single integral and a double integral:\\n\\n            quadts(lambda x: exp(cos(x)), [0, 1])\\n            quadts(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1])\\n\\n        See the documentation for quad for information about how points\\n        arguments and keyword arguments are parsed.\\n\\n        See documentation for TanhSinh for algorithmic information about\\n        tanh-sinh quadrature.\\n        \\\"\\\"\\\"\\n        kwargs['method'] = 'tanh-sinh'\\n        return ctx.quad(*args, **kwargs)\\n\\n    def quadgl(ctx, *args, **kwargs):\\n        \\\"\\\"\\\"\\n        Performs Gauss-Legendre quadrature. The call\\n\\n            quadgl(func, *points, ...)\\n\\n        is simply a shortcut for:\\n\\n            quad(func, *points, ..., method=GaussLegendre)\\n\\n        For example, a single integral and a double integral:\\n\\n            quadgl(lambda x: exp(cos(x)), [0, 1])\\n            quadgl(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1])\\n\\n        See the documentation for quad for information about how points\\n        arguments and keyword arguments are parsed.\\n\\n        See documentation for TanhSinh for algorithmic information about\\n        tanh-sinh quadrature.\\n        \\\"\\\"\\\"\\n        kwargs['method'] = 'gauss-legendre'\\n        return ctx.quad(*args, **kwargs)\\n\\n    def quadosc(ctx, f, interval, omega=None, period=None, zeros=None):\\n        r\\\"\\\"\\\"\\n        Calculates\\n\\n        .. math ::\\n\\n            I = \\\\int_a^b f(x) dx\\n\\n        where at least one of `a` and `b` is infinite and where\\n        `f(x) = g(x) \\\\cos(\\\\omega x  + \\\\phi)` for some slowly\\n        decreasing function `g(x)`. With proper input, :func:`~mpmath.quadosc`\\n        can also handle oscillatory integrals where the oscillation\\n        rate is different from a pure sine or cosine wave.\\n\\n        In the standard case when `|a| < \\\\infty, b = \\\\infty`,\\n        :func:`~mpmath.quadosc` works by evaluating the infinite series\\n\\n        .. math ::\\n\\n            I = \\\\int_a^{x_1} f(x) dx +\\n            \\\\sum_{k=1}^{\\\\infty} \\\\int_{x_k}^{x_{k+1}} f(x) dx\\n\\n        where `x_k` are consecutive zeros (alternatively\\n        some other periodic reference point) of `f(x)`.\\n        Accordingly, :func:`~mpmath.quadosc` requires information about the\\n        zeros of `f(x)`. For a periodic function, you can specify\\n        the zeros by either providing the angular frequency `\\\\omega`\\n        (*omega*) or the *period* `2 \\\\pi/\\\\omega`. In general, you can\\n        specify the `n`-th zero by providing the *zeros* arguments.\\n        Below is an example of each::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> f = lambda x: sin(3*x)/(x**2+1)\\n            >>> quadosc(f, [0,inf], omega=3)\\n            0.37833007080198\\n            >>> quadosc(f, [0,inf], period=2*pi/3)\\n            0.37833007080198\\n            >>> quadosc(f, [0,inf], zeros=lambda n: pi*n/3)\\n            0.37833007080198\\n            >>> (ei(3)*exp(-3)-exp(3)*ei(-3))/2  # Computed by Mathematica\\n            0.37833007080198\\n\\n        Note that *zeros* was specified to multiply `n` by the\\n        *half-period*, not the full period. In theory, it does not matter\\n        whether each partial integral is done over a half period or a full\\n        period. However, if done over half-periods, the infinite series\\n        passed to :func:`~mpmath.nsum` becomes an *alternating series* and this\\n        typically makes the extrapolation much more efficient.\\n\\n        Here is an example of an integration over the entire real line,\\n        and a half-infinite integration starting at `-\\\\infty`::\\n\\n            >>> quadosc(lambda x: cos(x)/(1+x**2), [-inf, inf], omega=1)\\n            1.15572734979092\\n            >>> pi/e\\n            1.15572734979092\\n            >>> quadosc(lambda x: cos(x)/x**2, [-inf, -1], period=2*pi)\\n            -0.0844109505595739\\n            >>> cos(1)+si(1)-pi/2\\n            -0.0844109505595738\\n\\n        Of course, the integrand may contain a complex exponential just as\\n        well as a real sine or cosine::\\n\\n            >>> quadosc(lambda x: exp(3*j*x)/(1+x**2), [-inf,inf], omega=3)\\n            (0.156410688228254 + 0.0j)\\n            >>> pi/e**3\\n            0.156410688228254\\n            >>> quadosc(lambda x: exp(3*j*x)/(2+x+x**2), [-inf,inf], omega=3)\\n            (0.00317486988463794 - 0.0447701735209082j)\\n            >>> 2*pi/sqrt(7)/exp(3*(j+sqrt(7))/2)\\n            (0.00317486988463794 - 0.0447701735209082j)\\n\\n        **Non-periodic functions**\\n\\n        If `f(x) = g(x) h(x)` for some function `h(x)` that is not\\n        strictly periodic, *omega* or *period* might not work, and it might\\n        be necessary to use *zeros*.\\n\\n        A notable exception can be made for Bessel functions which, though not\\n        periodic, are \\\"asymptotically periodic\\\" in a sufficiently strong sense\\n        that the sum extrapolation will work out::\\n\\n            >>> quadosc(j0, [0, inf], period=2*pi)\\n            1.0\\n            >>> quadosc(j1, [0, inf], period=2*pi)\\n            1.0\\n\\n        More properly, one should provide the exact Bessel function zeros::\\n\\n            >>> j0zero = lambda n: findroot(j0, pi*(n-0.25))\\n            >>> quadosc(j0, [0, inf], zeros=j0zero)\\n            1.0\\n\\n        For an example where *zeros* becomes necessary, consider the\\n        complete Fresnel integrals\\n\\n        .. math ::\\n\\n            \\\\int_0^{\\\\infty} \\\\cos x^2\\\\,dx = \\\\int_0^{\\\\infty} \\\\sin x^2\\\\,dx\\n            = \\\\sqrt{\\\\frac{\\\\pi}{8}}.\\n\\n        Although the integrands do not decrease in magnitude as\\n        `x \\\\to \\\\infty`, the integrals are convergent since the oscillation\\n        rate increases (causing consecutive periods to asymptotically\\n        cancel out). These integrals are virtually impossible to calculate\\n        to any kind of accuracy using standard quadrature rules. However,\\n        if one provides the correct asymptotic distribution of zeros\\n        (`x_n \\\\sim \\\\sqrt{n}`), :func:`~mpmath.quadosc` works::\\n\\n            >>> mp.dps = 30\\n            >>> f = lambda x: cos(x**2)\\n            >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n))\\n            0.626657068657750125603941321203\\n            >>> f = lambda x: sin(x**2)\\n            >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n))\\n            0.626657068657750125603941321203\\n            >>> sqrt(pi/8)\\n            0.626657068657750125603941321203\\n\\n        (Interestingly, these integrals can still be evaluated if one\\n        places some other constant than `\\\\pi` in the square root sign.)\\n\\n        In general, if `f(x) \\\\sim g(x) \\\\cos(h(x))`, the zeros follow\\n        the inverse-function distribution `h^{-1}(x)`::\\n\\n            >>> mp.dps = 15\\n            >>> f = lambda x: sin(exp(x))\\n            >>> quadosc(f, [1,inf], zeros=lambda n: log(n))\\n            -0.25024394235267\\n            >>> pi/2-si(e)\\n            -0.250243942352671\\n\\n        **Non-alternating functions**\\n\\n        If the integrand oscillates around a positive value, without\\n        alternating signs, the extrapolation might fail. A simple trick\\n        that sometimes works is to multiply or divide the frequency by 2::\\n\\n            >>> f = lambda x: 1/x**2+sin(x)/x**4\\n            >>> quadosc(f, [1,inf], omega=1)  # Bad\\n            1.28642190869861\\n            >>> quadosc(f, [1,inf], omega=0.5)  # Perfect\\n            1.28652953559617\\n            >>> 1+(cos(1)+ci(1)+sin(1))/6\\n            1.28652953559617\\n\\n        **Fast decay**\\n\\n        :func:`~mpmath.quadosc` is primarily useful for slowly decaying\\n        integrands. If the integrand decreases exponentially or faster,\\n        :func:`~mpmath.quad` will likely handle it without trouble (and generally be\\n        much faster than :func:`~mpmath.quadosc`)::\\n\\n            >>> quadosc(lambda x: cos(x)/exp(x), [0, inf], omega=1)\\n            0.5\\n            >>> quad(lambda x: cos(x)/exp(x), [0, inf])\\n            0.5\\n\\n        \\\"\\\"\\\"\\n        a, b = ctx._as_points(interval)\\n        a = ctx.convert(a)\\n        b = ctx.convert(b)\\n        if [omega, period, zeros].count(None) != 2:\\n            raise ValueError( \\\\\\n                \\\"must specify exactly one of omega, period, zeros\\\")\\n        if a == ctx.ninf and b == ctx.inf:\\n            s1 = ctx.quadosc(f, [a, 0], omega=omega, zeros=zeros, period=period)\\n            s2 = ctx.quadosc(f, [0, b], omega=omega, zeros=zeros, period=period)\\n            return s1 + s2\\n        if a == ctx.ninf:\\n            if zeros:\\n                return ctx.quadosc(lambda x:f(-x), [-b,-a], lambda n: zeros(-n))\\n            else:\\n                return ctx.quadosc(lambda x:f(-x), [-b,-a], omega=omega, period=period)\\n        if b != ctx.inf:\\n            raise ValueError(\\\"quadosc requires an infinite integration interval\\\")\\n        if not zeros:\\n            if omega:\\n                period = 2*ctx.pi/omega\\n            zeros = lambda n: n*period/2\\n        #for n in range(1,10):\\n        #    p = zeros(n)\\n        #    if p > a:\\n        #        break\\n        #if n >= 9:\\n        #    raise ValueError(\\\"zeros do not appear to be correctly indexed\\\")\\n        n = 1\\n        s = ctx.quadgl(f, [a, zeros(n)])\\n        def term(k):\\n            return ctx.quadgl(f, [zeros(k), zeros(k+1)])\\n        s += ctx.nsum(term, [n, ctx.inf])\\n        return s\\n\\n    def quadsubdiv(ctx, f, interval, tol=None, maxintervals=None, **kwargs):\\n        \\\"\\\"\\\"\\n        Computes the integral of *f* over the interval or path specified\\n        by *interval*, using :func:`~mpmath.quad` together with adaptive\\n        subdivision of the interval.\\n\\n        This function gives an accurate answer for some integrals where\\n        :func:`~mpmath.quad` fails::\\n\\n            >>> from mpmath import *\\n            >>> mp.dps = 15; mp.pretty = True\\n            >>> quad(lambda x: abs(sin(x)), [0, 2*pi])\\n            3.99900894176779\\n            >>> quadsubdiv(lambda x: abs(sin(x)), [0, 2*pi])\\n            4.0\\n            >>> quadsubdiv(sin, [0, 1000])\\n            0.437620923709297\\n            >>> quadsubdiv(lambda x: 1/(1+x**2), [-100, 100])\\n            3.12159332021646\\n            >>> quadsubdiv(lambda x: ceil(x), [0, 100])\\n            5050.0\\n            >>> quadsubdiv(lambda x: sin(x+exp(x)), [0,8])\\n            0.347400172657248\\n\\n        The argument *maxintervals* can be set to limit the permissible\\n        subdivision::\\n\\n            >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=5, error=True)\\n            (-5.40487904307774, 5.011)\\n            >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=100, error=True)\\n            (0.631417921866934, 1.10101120134116e-17)\\n\\n        Subdivision does not guarantee a correct answer since, the error\\n        estimate on subintervals may be inaccurate::\\n\\n            >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True)\\n            (0.210802735500549, 1.0001111101e-17)\\n            >>> mp.dps = 20\\n            >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True)\\n            (0.21080273550054927738, 2.200000001e-24)\\n\\n        The second answer is correct. We can get an accurate result at lower\\n        precision by forcing a finer initial subdivision::\\n\\n            >>> mp.dps = 15\\n            >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, linspace(0,1,5))\\n            0.210802735500549\\n\\n        The following integral is too oscillatory for convergence, but we can get a\\n        reasonable estimate::\\n\\n            >>> v, err = fp.quadsubdiv(lambda x: fp.sin(1/x), [0,1], error=True)\\n            >>> round(v, 6), round(err, 6)\\n            (0.504067, 1e-06)\\n            >>> sin(1) - ci(1)\\n            0.504067061906928\\n\\n        \\\"\\\"\\\"\\n        queue = []\\n        for i in range(len(interval)-1):\\n            queue.append((interval[i], interval[i+1]))\\n        total = ctx.zero\\n        total_error = ctx.zero\\n        if maxintervals is None:\\n            maxintervals = 10 * ctx.prec\\n        count = 0\\n        quad_args = kwargs.copy()\\n        quad_args[\\\"verbose\\\"] = False\\n        quad_args[\\\"error\\\"] = True\\n        if tol is None:\\n            tol = +ctx.eps\\n        orig = ctx.prec\\n        try:\\n            ctx.prec += 5\\n            while queue:\\n                a, b = queue.pop()\\n                s, err = ctx.quad(f, [a, b], **quad_args)\\n                if kwargs.get(\\\"verbose\\\"):\\n                    print(\\\"subinterval\\\", count, a, b, err)\\n                if err < tol or count > maxintervals:\\n                    total += s\\n                    total_error += err\\n                else:\\n                    count += 1\\n                    if count == maxintervals and kwargs.get(\\\"verbose\\\"):\\n                        print(\\\"warning: number of intervals exceeded maxintervals\\\")\\n                    if a == -ctx.inf and b == ctx.inf:\\n                        m = 0\\n                    elif a == -ctx.inf:\\n                        m = min(b-1, 2*b)\\n                    elif b == ctx.inf:\\n                        m = max(a+1, 2*a)\\n                    else:\\n                        m = a + (b - a) / 2\\n                    queue.append((a, m))\\n                    queue.append((m, b))\\n        finally:\\n            ctx.prec = orig\\n        if kwargs.get(\\\"error\\\"):\\n            return +total, +total_error\\n        else:\\n            return +total\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\nfrom __future__ import print_function\\n\\nfrom copy import copy\\n\\nfrom ..libmp.backend import xrange\\n\\nclass OptimizationMethods(object):\\n    def __init__(ctx):\\n        pass\\n\\n##############\\n# 1D-SOLVERS #\\n##############\\n\\nclass Newton:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Needs starting points x0 close to the root.\\n\\n    Pro:\\n\\n    * converges fast\\n    * sometimes more robust than secant with bad second starting point\\n\\n    Contra:\\n\\n    * converges slowly for multiple roots\\n    * needs first derivative\\n    * 2 function evaluations per iteration\\n    \\\"\\\"\\\"\\n    maxsteps = 20\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if len(x0) == 1:\\n            self.x0 = x0[0]\\n        else:\\n            raise ValueError('expected 1 starting point, got %i' % len(x0))\\n        self.f = f\\n        if not 'df' in kwargs:\\n            def df(x):\\n                return self.ctx.diff(f, x)\\n        else:\\n            df = kwargs['df']\\n        self.df = df\\n\\n    def __iter__(self):\\n        f = self.f\\n        df = self.df\\n        x0 = self.x0\\n        while True:\\n            x1 = x0 - f(x0) / df(x0)\\n            error = abs(x1 - x0)\\n            x0 = x1\\n            yield (x1, error)\\n\\nclass Secant:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Needs starting points x0 and x1 close to the root.\\n    x1 defaults to x0 + 0.25.\\n\\n    Pro:\\n\\n    * converges fast\\n\\n    Contra:\\n\\n    * converges slowly for multiple roots\\n    \\\"\\\"\\\"\\n    maxsteps = 30\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if len(x0) == 1:\\n            self.x0 = x0[0]\\n            self.x1 = self.x0 + 0.25\\n        elif len(x0) == 2:\\n            self.x0 = x0[0]\\n            self.x1 = x0[1]\\n        else:\\n            raise ValueError('expected 1 or 2 starting points, got %i' % len(x0))\\n        self.f = f\\n\\n    def __iter__(self):\\n        f = self.f\\n        x0 = self.x0\\n        x1 = self.x1\\n        f0 = f(x0)\\n        while True:\\n            f1 = f(x1)\\n            l = x1 - x0\\n            if not l:\\n                break\\n            s = (f1 - f0) / l\\n            if not s:\\n                break\\n            x0, x1 = x1, x1 - f1/s\\n            f0 = f1\\n            yield x1, abs(l)\\n\\nclass MNewton:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Needs starting point x0 close to the root.\\n    Uses modified Newton's method that converges fast regardless of the\\n    multiplicity of the root.\\n\\n    Pro:\\n\\n    * converges fast for multiple roots\\n\\n    Contra:\\n\\n    * needs first and second derivative of f\\n    * 3 function evaluations per iteration\\n    \\\"\\\"\\\"\\n    maxsteps = 20\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if not len(x0) == 1:\\n            raise ValueError('expected 1 starting point, got %i' % len(x0))\\n        self.x0 = x0[0]\\n        self.f = f\\n        if not 'df' in kwargs:\\n            def df(x):\\n                return self.ctx.diff(f, x)\\n        else:\\n            df = kwargs['df']\\n        self.df = df\\n        if not 'd2f' in kwargs:\\n            def d2f(x):\\n                return self.ctx.diff(df, x)\\n        else:\\n            d2f = kwargs['df']\\n        self.d2f = d2f\\n\\n    def __iter__(self):\\n        x = self.x0\\n        f = self.f\\n        df = self.df\\n        d2f = self.d2f\\n        while True:\\n            prevx = x\\n            fx = f(x)\\n            if fx == 0:\\n                break\\n            dfx = df(x)\\n            d2fx = d2f(x)\\n            # x = x - F(x)/F'(x) with F(x) = f(x)/f'(x)\\n            x -= fx / (dfx - fx * d2fx / dfx)\\n            error = abs(x - prevx)\\n            yield x, error\\n\\nclass Halley:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Needs a starting point x0 close to the root.\\n    Uses Halley's method with cubic convergence rate.\\n\\n    Pro:\\n\\n    * converges even faster the Newton's method\\n    * useful when computing with *many* digits\\n\\n    Contra:\\n\\n    * needs first and second derivative of f\\n    * 3 function evaluations per iteration\\n    * converges slowly for multiple roots\\n    \\\"\\\"\\\"\\n\\n    maxsteps = 20\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if not len(x0) == 1:\\n            raise ValueError('expected 1 starting point, got %i' % len(x0))\\n        self.x0 = x0[0]\\n        self.f = f\\n        if not 'df' in kwargs:\\n            def df(x):\\n                return self.ctx.diff(f, x)\\n        else:\\n            df = kwargs['df']\\n        self.df = df\\n        if not 'd2f' in kwargs:\\n            def d2f(x):\\n                return self.ctx.diff(df, x)\\n        else:\\n            d2f = kwargs['df']\\n        self.d2f = d2f\\n\\n    def __iter__(self):\\n        x = self.x0\\n        f = self.f\\n        df = self.df\\n        d2f = self.d2f\\n        while True:\\n            prevx = x\\n            fx = f(x)\\n            dfx = df(x)\\n            d2fx = d2f(x)\\n            x -=  2*fx*dfx / (2*dfx**2 - fx*d2fx)\\n            error = abs(x - prevx)\\n            yield x, error\\n\\nclass Muller:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Needs starting points x0, x1 and x2 close to the root.\\n    x1 defaults to x0 + 0.25; x2 to x1 + 0.25.\\n    Uses Muller's method that converges towards complex roots.\\n\\n    Pro:\\n\\n    * converges fast (somewhat faster than secant)\\n    * can find complex roots\\n\\n    Contra:\\n\\n    * converges slowly for multiple roots\\n    * may have complex values for real starting points and real roots\\n\\n    http://en.wikipedia.org/wiki/Muller's_method\\n    \\\"\\\"\\\"\\n    maxsteps = 30\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if len(x0) == 1:\\n            self.x0 = x0[0]\\n            self.x1 = self.x0 + 0.25\\n            self.x2 = self.x1 + 0.25\\n        elif len(x0) == 2:\\n            self.x0 = x0[0]\\n            self.x1 = x0[1]\\n            self.x2 = self.x1 + 0.25\\n        elif len(x0) == 3:\\n            self.x0 = x0[0]\\n            self.x1 = x0[1]\\n            self.x2 = x0[2]\\n        else:\\n            raise ValueError('expected 1, 2 or 3 starting points, got %i'\\n                             % len(x0))\\n        self.f = f\\n        self.verbose = kwargs['verbose']\\n\\n    def __iter__(self):\\n        f = self.f\\n        x0 = self.x0\\n        x1 = self.x1\\n        x2 = self.x2\\n        fx0 = f(x0)\\n        fx1 = f(x1)\\n        fx2 = f(x2)\\n        while True:\\n            # TODO: maybe refactoring with function for divided differences\\n            # calculate divided differences\\n            fx2x1 = (fx1 - fx2) / (x1 - x2)\\n            fx2x0 = (fx0 - fx2) / (x0 - x2)\\n            fx1x0 = (fx0 - fx1) / (x0 - x1)\\n            w = fx2x1 + fx2x0 - fx1x0\\n            fx2x1x0 = (fx1x0 - fx2x1) / (x0 - x2)\\n            if w == 0 and fx2x1x0 == 0:\\n                if self.verbose:\\n                    print('canceled with')\\n                    print('x0 =', x0, ', x1 =', x1, 'and x2 =', x2)\\n                break\\n            x0 = x1\\n            fx0 = fx1\\n            x1 = x2\\n            fx1 = fx2\\n            # denominator should be as large as possible => choose sign\\n            r = self.ctx.sqrt(w**2 - 4*fx2*fx2x1x0)\\n            if abs(w - r) > abs(w + r):\\n                r = -r\\n            x2 -= 2*fx2 / (w + r)\\n            fx2 = f(x2)\\n            error = abs(x2 - x1)\\n            yield x2, error\\n\\n# TODO: consider raising a ValueError when there's no sign change in a and b\\nclass Bisection:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Uses bisection method to find a root of f in [a, b].\\n    Might fail for multiple roots (needs sign change).\\n\\n    Pro:\\n\\n    * robust and reliable\\n\\n    Contra:\\n\\n    * converges slowly\\n    * needs sign change\\n    \\\"\\\"\\\"\\n    maxsteps = 100\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if len(x0) != 2:\\n            raise ValueError('expected interval of 2 points, got %i' % len(x0))\\n        self.f = f\\n        self.a = x0[0]\\n        self.b = x0[1]\\n\\n    def __iter__(self):\\n        f = self.f\\n        a = self.a\\n        b = self.b\\n        l = b - a\\n        fb = f(b)\\n        while True:\\n            m = self.ctx.ldexp(a + b, -1)\\n            fm = f(m)\\n            sign = fm * fb\\n            if sign < 0:\\n                a = m\\n            elif sign > 0:\\n                b = m\\n                fb = fm\\n            else:\\n                yield m, self.ctx.zero\\n            l /= 2\\n            yield (a + b)/2, abs(l)\\n\\ndef _getm(method):\\n    \\\"\\\"\\\"\\n    Return a function to calculate m for Illinois-like methods.\\n    \\\"\\\"\\\"\\n    if method == 'illinois':\\n        def getm(fz, fb):\\n            return 0.5\\n    elif method == 'pegasus':\\n        def getm(fz, fb):\\n            return fb/(fb + fz)\\n    elif method == 'anderson':\\n        def getm(fz, fb):\\n            m = 1 - fz/fb\\n            if m > 0:\\n                return m\\n            else:\\n                return 0.5\\n    else:\\n        raise ValueError(\\\"method '%s' not recognized\\\" % method)\\n    return getm\\n\\nclass Illinois:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Uses Illinois method or similar to find a root of f in [a, b].\\n    Might fail for multiple roots (needs sign change).\\n    Combines bisect with secant (improved regula falsi).\\n\\n    The only difference between the methods is the scaling factor m, which is\\n    used to ensure convergence (you can choose one using the 'method' keyword):\\n\\n    Illinois method ('illinois'):\\n        m = 0.5\\n\\n    Pegasus method ('pegasus'):\\n        m = fb/(fb + fz)\\n\\n    Anderson-Bjoerk method ('anderson'):\\n        m = 1 - fz/fb if positive else 0.5\\n\\n    Pro:\\n\\n    * converges very fast\\n\\n    Contra:\\n\\n    * has problems with multiple roots\\n    * needs sign change\\n    \\\"\\\"\\\"\\n    maxsteps = 30\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if len(x0) != 2:\\n            raise ValueError('expected interval of 2 points, got %i' % len(x0))\\n        self.a = x0[0]\\n        self.b = x0[1]\\n        self.f = f\\n        self.tol = kwargs['tol']\\n        self.verbose = kwargs['verbose']\\n        self.method = kwargs.get('method', 'illinois')\\n        self.getm = _getm(self.method)\\n        if self.verbose:\\n            print('using %s method' % self.method)\\n\\n    def __iter__(self):\\n        method = self.method\\n        f = self.f\\n        a = self.a\\n        b = self.b\\n        fa = f(a)\\n        fb = f(b)\\n        m = None\\n        while True:\\n            l = b - a\\n            if l == 0:\\n                break\\n            s = (fb - fa) / l\\n            z = a - fa/s\\n            fz = f(z)\\n            if abs(fz) < self.tol:\\n                # TODO: better condition (when f is very flat)\\n                if self.verbose:\\n                    print('canceled with z =', z)\\n                yield z, l\\n                break\\n            if fz * fb < 0: # root in [z, b]\\n                a = b\\n                fa = fb\\n                b = z\\n                fb = fz\\n            else: # root in [a, z]\\n                m = self.getm(fz, fb)\\n                b = z\\n                fb = fz\\n                fa = m*fa # scale down to ensure convergence\\n            if self.verbose and m and not method == 'illinois':\\n                print('m:', m)\\n            yield (a + b)/2, abs(l)\\n\\ndef Pegasus(*args, **kwargs):\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Uses Pegasus method to find a root of f in [a, b].\\n    Wrapper for illinois to use method='pegasus'.\\n    \\\"\\\"\\\"\\n    kwargs['method'] = 'pegasus'\\n    return Illinois(*args, **kwargs)\\n\\ndef Anderson(*args, **kwargs):\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Uses Anderson-Bjoerk method to find a root of f in [a, b].\\n    Wrapper for illinois to use method='pegasus'.\\n    \\\"\\\"\\\"\\n    kwargs['method'] = 'anderson'\\n    return Illinois(*args, **kwargs)\\n\\n# TODO: check whether it's possible to combine it with Illinois stuff\\nclass Ridder:\\n    \\\"\\\"\\\"\\n    1d-solver generating pairs of approximative root and error.\\n\\n    Ridders' method to find a root of f in [a, b].\\n    Is told to perform as well as Brent's method while being simpler.\\n\\n    Pro:\\n\\n    * very fast\\n    * simpler than Brent's method\\n\\n    Contra:\\n\\n    * two function evaluations per step\\n    * has problems with multiple roots\\n    * needs sign change\\n\\n    http://en.wikipedia.org/wiki/Ridders'_method\\n    \\\"\\\"\\\"\\n    maxsteps = 30\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        self.f = f\\n        if len(x0) != 2:\\n            raise ValueError('expected interval of 2 points, got %i' % len(x0))\\n        self.x1 = x0[0]\\n        self.x2 = x0[1]\\n        self.verbose = kwargs['verbose']\\n        self.tol = kwargs['tol']\\n\\n    def __iter__(self):\\n        ctx = self.ctx\\n        f = self.f\\n        x1 = self.x1\\n        fx1 = f(x1)\\n        x2 = self.x2\\n        fx2 = f(x2)\\n        while True:\\n            x3 = 0.5*(x1 + x2)\\n            fx3 = f(x3)\\n            x4 = x3 + (x3 - x1) * ctx.sign(fx1 - fx2) * fx3 / ctx.sqrt(fx3**2 - fx1*fx2)\\n            fx4 = f(x4)\\n            if abs(fx4) < self.tol:\\n                # TODO: better condition (when f is very flat)\\n                if self.verbose:\\n                    print('canceled with f(x4) =', fx4)\\n                yield x4, abs(x1 - x2)\\n                break\\n            if fx4 * fx2 < 0: # root in [x4, x2]\\n                x1 = x4\\n                fx1 = fx4\\n            else: # root in [x1, x4]\\n                x2 = x4\\n                fx2 = fx4\\n            error = abs(x1 - x2)\\n            yield (x1 + x2)/2, error\\n\\nclass ANewton:\\n    \\\"\\\"\\\"\\n    EXPERIMENTAL 1d-solver generating pairs of approximative root and error.\\n\\n    Uses Newton's method modified to use Steffensens method when convergence is\\n    slow. (I.e. for multiple roots.)\\n    \\\"\\\"\\\"\\n    maxsteps = 20\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        if not len(x0) == 1:\\n            raise ValueError('expected 1 starting point, got %i' % len(x0))\\n        self.x0 = x0[0]\\n        self.f = f\\n        if not 'df' in kwargs:\\n            def df(x):\\n                return self.ctx.diff(f, x)\\n        else:\\n            df = kwargs['df']\\n        self.df = df\\n        def phi(x):\\n            return x - f(x) / df(x)\\n        self.phi = phi\\n        self.verbose = kwargs['verbose']\\n\\n    def __iter__(self):\\n        x0 = self.x0\\n        f = self.f\\n        df = self.df\\n        phi = self.phi\\n        error = 0\\n        counter = 0\\n        while True:\\n            prevx = x0\\n            try:\\n                x0 = phi(x0)\\n            except ZeroDivisionError:\\n                if self.verbose:\\n                    print('ZeroDivisionError: canceled with x =', x0)\\n                break\\n            preverror = error\\n            error = abs(prevx - x0)\\n            # TODO: decide not to use convergence acceleration\\n            if error and abs(error - preverror) / error < 1:\\n                if self.verbose:\\n                    print('converging slowly')\\n                counter += 1\\n            if counter >= 3:\\n                # accelerate convergence\\n                phi = steffensen(phi)\\n                counter = 0\\n                if self.verbose:\\n                    print('accelerating convergence')\\n            yield x0, error\\n\\n# TODO: add Brent\\n\\n############################\\n# MULTIDIMENSIONAL SOLVERS #\\n############################\\n\\ndef jacobian(ctx, f, x):\\n    \\\"\\\"\\\"\\n    Calculate the Jacobian matrix of a function at the point x0.\\n\\n    This is the first derivative of a vectorial function:\\n\\n        f : R^m -> R^n with m >= n\\n    \\\"\\\"\\\"\\n    x = ctx.matrix(x)\\n    h = ctx.sqrt(ctx.eps)\\n    fx = ctx.matrix(f(*x))\\n    m = len(fx)\\n    n = len(x)\\n    J = ctx.matrix(m, n)\\n    for j in xrange(n):\\n        xj = x.copy()\\n        xj[j] += h\\n        Jj = (ctx.matrix(f(*xj)) - fx) / h\\n        for i in xrange(m):\\n            J[i,j] = Jj[i]\\n    return J\\n\\n# TODO: test with user-specified jacobian matrix\\nclass MDNewton:\\n    \\\"\\\"\\\"\\n    Find the root of a vector function numerically using Newton's method.\\n\\n    f is a vector function representing a nonlinear equation system.\\n\\n    x0 is the starting point close to the root.\\n\\n    J is a function returning the Jacobian matrix for a point.\\n\\n    Supports overdetermined systems.\\n\\n    Use the 'norm' keyword to specify which norm to use. Defaults to max-norm.\\n    The function to calculate the Jacobian matrix can be given using the\\n    keyword 'J'. Otherwise it will be calculated numerically.\\n\\n    Please note that this method converges only locally. Especially for high-\\n    dimensional systems it is not trivial to find a good starting point being\\n    close enough to the root.\\n\\n    It is recommended to use a faster, low-precision solver from SciPy [1] or\\n    OpenOpt [2] to get an initial guess. Afterwards you can use this method for\\n    root-polishing to any precision.\\n\\n    [1] http://scipy.org\\n\\n    [2] http://openopt.org/Welcome\\n    \\\"\\\"\\\"\\n    maxsteps = 10\\n\\n    def __init__(self, ctx, f, x0, **kwargs):\\n        self.ctx = ctx\\n        self.f = f\\n        if isinstance(x0, (tuple, list)):\\n            x0 = ctx.matrix(x0)\\n        assert x0.cols == 1, 'need a vector'\\n        self.x0 = x0\\n        if 'J' in kwargs:\\n            self.J = kwargs['J']\\n        else:\\n            def J(*x):\\n                return ctx.jacobian(f, x)\\n            self.J = J\\n        self.norm = kwargs['norm']\\n        self.verbose = kwargs['verbose']\\n\\n    def __iter__(self):\\n        f = self.f\\n        x0 = self.x0\\n        norm = self.norm\\n        J = self.J\\n        fx = self.ctx.matrix(f(*x0))\\n        fxnorm = norm(fx)\\n        cancel = False\\n        while not cancel:\\n            # get direction of descent\\n            fxn = -fx\\n            Jx = J(*x0)\\n            s = self.ctx.lu_solve(Jx, fxn)\\n            if self.verbose:\\n                print('Jx:')\\n                print(Jx)\\n                print('s:', s)\\n            # damping step size TODO: better strategy (hard task)\\n            l = self.ctx.one\\n            x1 = x0 + s\\n            while True:\\n                if x1 == x0:\\n                    if self.verbose:\\n                        print(\\\"canceled, won't get more excact\\\")\\n                    cancel = True\\n                    break\\n                fx = self.ctx.matrix(f(*x1))\\n                newnorm = norm(fx)\\n                if newnorm < fxnorm:\\n                    # new x accepted\\n                    fxnorm = newnorm\\n                    x0 = x1\\n                    break\\n                l /= 2\\n                x1 = x0 + l*s\\n            yield (x0, fxnorm)\\n\\n#############\\n# UTILITIES #\\n#############\\n\\nstr2solver = {'newton':Newton, 'secant':Secant, 'mnewton':MNewton,\\n              'halley':Halley, 'muller':Muller, 'bisect':Bisection,\\n              'illinois':Illinois, 'pegasus':Pegasus, 'anderson':Anderson,\\n              'ridder':Ridder, 'anewton':ANewton, 'mdnewton':MDNewton}\\n\\ndef findroot(ctx, f, x0, solver='secant', tol=None, verbose=False, verify=True, **kwargs):\\n    r\\\"\\\"\\\"\\n    Find an approximate solution to `f(x) = 0`, using *x0* as starting point or\\n    interval for *x*.\\n\\n    Multidimensional overdetermined systems are supported.\\n    You can specify them using a function or a list of functions.\\n\\n    Mathematically speaking, this function returns `x` such that\\n    `|f(x)|^2 \\\\leq \\\\mathrm{tol}` is true within the current working precision.\\n    If the computed value does not meet this criterion, an exception is raised.\\n    This exception can be disabled with *verify=False*.\\n\\n    For interval arithmetic (``iv.findroot()``), please note that\\n    the returned interval ``x`` is not guaranteed to contain `f(x)=0`!\\n    It is only some `x` for which `|f(x)|^2 \\\\leq \\\\mathrm{tol}` certainly holds\\n    regardless of numerical error. This may be improved in the future.\\n\\n    **Arguments**\\n\\n    *f*\\n        one dimensional function\\n    *x0*\\n        starting point, several starting points or interval (depends on solver)\\n    *tol*\\n        the returned solution has an error smaller than this\\n    *verbose*\\n        print additional information for each iteration if true\\n    *verify*\\n        verify the solution and raise a ValueError if `|f(x)|^2 > \\\\mathrm{tol}`\\n    *solver*\\n        a generator for *f* and *x0* returning approximative solution and error\\n    *maxsteps*\\n        after how many steps the solver will cancel\\n    *df*\\n        first derivative of *f* (used by some solvers)\\n    *d2f*\\n        second derivative of *f* (used by some solvers)\\n    *multidimensional*\\n        force multidimensional solving\\n    *J*\\n        Jacobian matrix of *f* (used by multidimensional solvers)\\n    *norm*\\n        used vector norm (used by multidimensional solvers)\\n\\n    solver has to be callable with ``(f, x0, **kwargs)`` and return an generator\\n    yielding pairs of approximative solution and estimated error (which is\\n    expected to be positive).\\n    You can use the following string aliases:\\n    'secant', 'mnewton', 'halley', 'muller', 'illinois', 'pegasus', 'anderson',\\n    'ridder', 'anewton', 'bisect'\\n\\n    See mpmath.calculus.optimization for their documentation.\\n\\n    **Examples**\\n\\n    The function :func:`~mpmath.findroot` locates a root of a given function using the\\n    secant method by default. A simple example use of the secant method is to\\n    compute `\\\\pi` as the root of `\\\\sin x` closest to `x_0 = 3`::\\n\\n        >>> from mpmath import *\\n        >>> mp.dps = 30; mp.pretty = True\\n        >>> findroot(sin, 3)\\n        3.14159265358979323846264338328\\n\\n    The secant method can be used to find complex roots of analytic functions,\\n    although it must in that case generally be given a nonreal starting value\\n    (or else it will never leave the real line)::\\n\\n        >>> mp.dps = 15\\n        >>> findroot(lambda x: x**3 + 2*x + 1, j)\\n        (0.226698825758202 + 1.46771150871022j)\\n\\n    A nice application is to compute nontrivial roots of the Riemann zeta\\n    function with many digits (good initial values are needed for convergence)::\\n\\n        >>> mp.dps = 30\\n        >>> findroot(zeta, 0.5+14j)\\n        (0.5 + 14.1347251417346937904572519836j)\\n\\n    The secant method can also be used as an optimization algorithm, by passing\\n    it a derivative of a function. The following example locates the positive\\n    minimum of the gamma function::\\n\\n        >>> mp.dps = 20\\n        >>> findroot(lambda x: diff(gamma, x), 1)\\n        1.4616321449683623413\\n\\n    Finally, a useful application is to compute inverse functions, such as the\\n    Lambert W function which is the inverse of `w e^w`, given the first\\n    term of the solution's asymptotic expansion as the initial value. In basic\\n    cases, this gives identical results to mpmath's built-in ``lambertw``\\n    function::\\n\\n        >>> def lambert(x):\\n        ...     return findroot(lambda w: w*exp(w) - x, log(1+x))\\n        ...\\n        >>> mp.dps = 15\\n        >>> lambert(1); lambertw(1)\\n        0.567143290409784\\n        0.567143290409784\\n        >>> lambert(1000); lambert(1000)\\n        5.2496028524016\\n        5.2496028524016\\n\\n    Multidimensional functions are also supported::\\n\\n        >>> f = [lambda x1, x2: x1**2 + x2,\\n        ...      lambda x1, x2: 5*x1**2 - 3*x1 + 2*x2 - 3]\\n        >>> findroot(f, (0, 0))\\n        [-0.618033988749895]\\n        [-0.381966011250105]\\n        >>> findroot(f, (10, 10))\\n        [ 1.61803398874989]\\n        [-2.61803398874989]\\n\\n    You can verify this by solving the system manually.\\n\\n    Please note that the following (more general) syntax also works::\\n\\n        >>> def f(x1, x2):\\n        ...     return x1**2 + x2, 5*x1**2 - 3*x1 + 2*x2 - 3\\n        ...\\n        >>> findroot(f, (0, 0))\\n        [-0.618033988749895]\\n        [-0.381966011250105]\\n\\n\\n    **Multiple roots**\\n\\n    For multiple roots all methods of the Newtonian family (including secant)\\n    converge slowly. Consider this example::\\n\\n        >>> f = lambda x: (x - 1)**99\\n        >>> findroot(f, 0.9, verify=False)\\n        0.918073542444929\\n\\n    Even for a very close starting point the secant method converges very\\n    slowly. Use ``verbose=True`` to illustrate this.\\n\\n    It is possible to modify Newton's method to make it converge regardless of\\n    the root's multiplicity::\\n\\n        >>> findroot(f, -10, solver='mnewton')\\n        1.0\\n\\n    This variant uses the first and second derivative of the function, which is\\n    not very efficient.\\n\\n    Alternatively you can use an experimental Newtonian solver that keeps track\\n    of the speed of convergence and accelerates it using Steffensen's method if\\n    necessary::\\n\\n        >>> findroot(f, -10, solver='anewton', verbose=True)\\n        x:     -9.88888888888888888889\\n        error: 0.111111111111111111111\\n        converging slowly\\n        x:     -9.77890011223344556678\\n        error: 0.10998877665544332211\\n        converging slowly\\n        x:     -9.67002233332199662166\\n        error: 0.108877778911448945119\\n        converging slowly\\n        accelerating convergence\\n        x:     -9.5622443299551077669\\n        error: 0.107778003366888854764\\n        converging slowly\\n        x:     0.99999999999999999214\\n        error: 10.562244329955107759\\n        x:     1.0\\n        error: 7.8598304758094664213e-18\\n        ZeroDivisionError: canceled with x = 1.0\\n        1.0\\n\\n    **Complex roots**\\n\\n    For complex roots it's recommended to use Muller's method as it converges\\n    even for real starting points very fast::\\n\\n        >>> findroot(lambda x: x**4 + x + 1, (0, 1, 2), solver='muller')\\n        (0.727136084491197 + 0.934099289460529j)\\n\\n\\n    **Intersection methods**\\n\\n    When you need to find a root in a known interval, it's highly recommended to\\n    use an intersection-based solver like ``'anderson'`` or ``'ridder'``.\\n    Usually they converge faster and more reliable. They have however problems\\n    with multiple roots and usually need a sign change to find a root::\\n\\n        >>> findroot(lambda x: x**3, (-1, 1), solver='anderson')\\n        0.0\\n\\n    Be careful with symmetric functions::\\n\\n        >>> findroot(lambda x: x**2, (-1, 1), solver='anderson') #doctest:+ELLIPSIS\\n        Traceback (most recent call last):\\n          ...\\n        ZeroDivisionError\\n\\n    It fails even for better starting points, because there is no sign change::\\n\\n        >>> findroot(lambda x: x**2, (-1, .5), solver='anderson')\\n        Traceback (most recent call last):\\n          ...\\n        ValueError: Could not find root within given tolerance. (1.0 > 2.16840434497100886801e-19)\\n        Try another starting point or tweak arguments.\\n\\n    \\\"\\\"\\\"\\n    prec = ctx.prec\\n    try:\\n        ctx.prec += 20\\n\\n        # initialize arguments\\n        if tol is None:\\n            tol = ctx.eps * 2**10\\n\\n        kwargs['verbose'] = kwargs.get('verbose', verbose)\\n\\n        if 'd1f' in kwargs:\\n            kwargs['df'] = kwargs['d1f']\\n\\n        kwargs['tol'] = tol\\n        if isinstance(x0, (list, tuple)):\\n            x0 = [ctx.convert(x) for x in x0]\\n        else:\\n            x0 = [ctx.convert(x0)]\\n\\n        if isinstance(solver, str):\\n            try:\\n                solver = str2solver[solver]\\n            except KeyError:\\n                raise ValueError('could not recognize solver')\\n\\n        # accept list of functions\\n        if isinstance(f, (list, tuple)):\\n            f2 = copy(f)\\n            def tmp(*args):\\n                return [fn(*args) for fn in f2]\\n            f = tmp\\n\\n        # detect multidimensional functions\\n        try:\\n            fx = f(*x0)\\n            multidimensional = isinstance(fx, (list, tuple, ctx.matrix))\\n        except TypeError:\\n            fx = f(x0[0])\\n            multidimensional = False\\n        if 'multidimensional' in kwargs:\\n            multidimensional = kwargs['multidimensional']\\n        if multidimensional:\\n            # only one multidimensional solver available at the moment\\n            solver = MDNewton\\n            if not 'norm' in kwargs:\\n                norm = lambda x: ctx.norm(x, 'inf')\\n                kwargs['norm'] = norm\\n            else:\\n                norm = kwargs['norm']\\n        else:\\n            norm = abs\\n\\n        # happily return starting point if it's a root\\n        if norm(fx) == 0:\\n            if multidimensional:\\n                return ctx.matrix(x0)\\n            else:\\n                return x0[0]\\n\\n        # use solver\\n        iterations = solver(ctx, f, x0, **kwargs)\\n        if 'maxsteps' in kwargs:\\n            maxsteps = kwargs['maxsteps']\\n        else:\\n            maxsteps = iterations.maxsteps\\n        i = 0\\n        for x, error in iterations:\\n            if verbose:\\n                print('x:    ', x)\\n                print('error:', error)\\n            i += 1\\n            if error < tol * max(1, norm(x)) or i >= maxsteps:\\n                break\\n        else:\\n            if not i:\\n                raise ValueError('Could not find root using the given solver.\\\\n'\\n                                 'Try another starting point or tweak arguments.')\\n        if not isinstance(x, (list, tuple, ctx.matrix)):\\n            xl = [x]\\n        else:\\n            xl = x\\n        if verify and norm(f(*xl))**2 > tol: # TODO: better condition?\\n            raise ValueError('Could not find root within given tolerance. '\\n                             '(%s > %s)\\\\n'\\n                             'Try another starting point or tweak arguments.'\\n                             % (norm(f(*xl))**2, tol))\\n        return x\\n    finally:\\n        ctx.prec = prec\\n\\n\\ndef multiplicity(ctx, f, root, tol=None, maxsteps=10, **kwargs):\\n    \\\"\\\"\\\"\\n    Return the multiplicity of a given root of f.\\n\\n    Internally, numerical derivatives are used. This might be inefficient for\\n    higher order derviatives. Due to this, ``multiplicity`` cancels after\\n    evaluating 10 derivatives by default. You can be specify the n-th derivative\\n    using the dnf keyword.\\n\\n    >>> from mpmath import *\\n    >>> multiplicity(lambda x: sin(x) - 1, pi/2)\\n    2\\n\\n    \\\"\\\"\\\"\\n    if tol is None:\\n        tol = ctx.eps ** 0.8\\n    kwargs['d0f'] = f\\n    for i in xrange(maxsteps):\\n        dfstr = 'd' + str(i) + 'f'\\n        if dfstr in kwargs:\\n            df = kwargs[dfstr]\\n        else:\\n            df = lambda x: ctx.diff(f, x, i)\\n        if not abs(df(root)) < tol:\\n            break\\n    return i\\n\\ndef steffensen(f):\\n    \\\"\\\"\\\"\\n    linear convergent function -> quadratic convergent function\\n\\n    Steffensen's method for quadratic convergence of a linear converging\\n    sequence.\\n    Don not use it for higher rates of convergence.\\n    It may even work for divergent sequences.\\n\\n    Definition:\\n    F(x) = (x*f(f(x)) - f(x)**2) / (f(f(x)) - 2*f(x) + x)\\n\\n    Example\\n    .......\\n\\n    You can use Steffensen's method to accelerate a fixpoint iteration of linear\\n    (or less) convergence.\\n\\n    x* is a fixpoint of the iteration x_{k+1} = phi(x_k) if x* = phi(x*). For\\n    phi(x) = x**2 there are two fixpoints: 0 and 1.\\n\\n    Let's try Steffensen's method:\\n\\n    >>> f = lambda x: x**2\\n    >>> from mpmath.calculus.optimization import steffensen\\n    >>> F = steffensen(f)\\n    >>> for x in [0.5, 0.9, 2.0]:\\n    ...     fx = Fx = x\\n    ...     for i in xrange(9):\\n    ...         try:\\n    ...             fx = f(fx)\\n    ...         except OverflowError:\\n    ...             pass\\n    ...         try:\\n    ...             Fx = F(Fx)\\n    ...         except ZeroDivisionError:\\n    ...             pass\\n    ...         print('%20g  %20g' % (fx, Fx))\\n                    0.25                  -0.5\\n                  0.0625                   0.1\\n              0.00390625            -0.0011236\\n             1.52588e-05           1.41691e-09\\n             2.32831e-10          -2.84465e-27\\n             5.42101e-20           2.30189e-80\\n             2.93874e-39          -1.2197e-239\\n             8.63617e-78                     0\\n            7.45834e-155                     0\\n                    0.81               1.02676\\n                  0.6561               1.00134\\n                0.430467                     1\\n                0.185302                     1\\n               0.0343368                     1\\n              0.00117902                     1\\n             1.39008e-06                     1\\n             1.93233e-12                     1\\n             3.73392e-24                     1\\n                       4                   1.6\\n                      16                1.2962\\n                     256               1.10194\\n                   65536               1.01659\\n             4.29497e+09               1.00053\\n             1.84467e+19                     1\\n             3.40282e+38                     1\\n             1.15792e+77                     1\\n            1.34078e+154                     1\\n\\n    Unmodified, the iteration converges only towards 0. Modified it converges\\n    not only much faster, it converges even to the repelling fixpoint 1.\\n    \\\"\\\"\\\"\\n    def F(x):\\n        fx = f(x)\\n        ffx = f(fx)\\n        return (x*ffx - fx**2) / (ffx - 2*fx + x)\\n    return F\\n\\nOptimizationMethods.jacobian = jacobian\\nOptimizationMethods.findroot = findroot\\nOptimizationMethods.multiplicity = multiplicity\\n\\nif __name__ == '__main__':\\n    import doctest\\n    doctest.testmod()\\n\\n\\nfrom . import calculus\\n# XXX: hack to set methods\\nfrom . import approximation\\nfrom . import differentiation\\nfrom . import extrapolation\\nfrom . import polynomials\\n\\n\\n\\\"\\\"\\\"\\n-----------------------------------------------------------------------\\nThis module implements gamma- and zeta-related functions:\\n\\n* Bernoulli numbers\\n* Factorials\\n* The gamma function\\n* Polygamma functions\\n* Harmonic numbers\\n* The Riemann zeta function\\n* Constants related to these functions\\n\\n-----------------------------------------------------------------------\\n\\\"\\\"\\\"\\n\\nimport math\\nimport sys\\n\\nfrom .backend import xrange\\nfrom .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_THREE, gmpy\\n\\nfrom .libintmath import list_primes, ifac, ifac2, moebius\\n\\nfrom .libmpf import (\\\\\\n    round_floor, round_ceiling, round_down, round_up,\\n    round_nearest, round_fast,\\n    lshift, sqrt_fixed, isqrt_fast,\\n    fzero, fone, fnone, fhalf, ftwo, finf, fninf, fnan,\\n    from_int, to_int, to_fixed, from_man_exp, from_rational,\\n    mpf_pos, mpf_neg, mpf_abs, mpf_add, mpf_sub,\\n    mpf_mul, mpf_mul_int, mpf_div, mpf_sqrt, mpf_pow_int,\\n    mpf_rdiv_int,\\n    mpf_perturb, mpf_le, mpf_lt, mpf_gt, mpf_shift,\\n    negative_rnd, reciprocal_rnd,\\n    bitcount, to_float, mpf_floor, mpf_sign, ComplexResult\\n)\\n\\nfrom .libelefun import (\\\\\\n    constant_memo,\\n    def_mpf_constant,\\n    mpf_pi, pi_fixed, ln2_fixed, log_int_fixed, mpf_ln2,\\n    mpf_exp, mpf_log, mpf_pow, mpf_cosh,\\n    mpf_cos_sin, mpf_cosh_sinh, mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi,\\n    ln_sqrt2pi_fixed, mpf_ln_sqrt2pi, sqrtpi_fixed, mpf_sqrtpi,\\n    cos_sin_fixed, exp_fixed\\n)\\n\\nfrom .libmpc import (\\\\\\n    mpc_zero, mpc_one, mpc_half, mpc_two,\\n    mpc_abs, mpc_shift, mpc_pos, mpc_neg,\\n    mpc_add, mpc_sub, mpc_mul, mpc_div,\\n    mpc_add_mpf, mpc_mul_mpf, mpc_div_mpf, mpc_mpf_div,\\n    mpc_mul_int, mpc_pow_int,\\n    mpc_log, mpc_exp, mpc_pow,\\n    mpc_cos_pi, mpc_sin_pi,\\n    mpc_reciprocal, mpc_square,\\n    mpc_sub_mpf\\n)\\n\\n\\n\\n# Catalan's constant is computed using Lupas's rapidly convergent series\\n# (listed on http://mathworld.wolfram.com/CatalansConstant.html)\\n#            oo\\n#            ___       n-1  8n     2                   3    2\\n#        1  \\\\      (-1)    2   (40n  - 24n + 3) [(2n)!] (n!)\\n#  K =  ---  )     -----------------------------------------\\n#       64  /___               3               2\\n#                             n  (2n-1) [(4n)!]\\n#           n = 1\\n\\n@constant_memo\\ndef catalan_fixed(prec):\\n    prec = prec + 20\\n    a = one = MPZ_ONE << prec\\n    s, t, n = 0, 1, 1\\n    while t:\\n        a *= 32 * n**3 * (2*n-1)\\n        a //= (3-16*n+16*n**2)**2\\n        t = a * (-1)**(n-1) * (40*n**2-24*n+3) // (n**3 * (2*n-1))\\n        s += t\\n        n += 1\\n    return s >> (20 + 6)\\n\\n# Khinchin's constant is relatively difficult to compute. Here\\n# we use the rational zeta series\\n\\n#                    oo                2*n-1\\n#                   ___                ___\\n#                   \\\\   ` zeta(2*n)-1  \\\\   ` (-1)^(k+1)\\n#  log(K)*log(2) =   )    ------------  )    ----------\\n#                   /___.      n       /___.      k\\n#                   n = 1              k = 1\\n\\n# which adds half a digit per term. The essential trick for achieving\\n# reasonable efficiency is to recycle both the values of the zeta\\n# function (essentially Bernoulli numbers) and the partial terms of\\n# the inner sum.\\n\\n# An alternative might be to use K = 2*exp[1/log(2) X] where\\n\\n#      / 1     1       [ pi*x*(1-x^2) ]\\n#  X = |    ------ log [ ------------ ].\\n#      / 0  x(1+x)     [  sin(pi*x)   ]\\n\\n# and integrate numerically. In practice, this seems to be slightly\\n# slower than the zeta series at high precision.\\n\\n@constant_memo\\ndef khinchin_fixed(prec):\\n    wp = int(prec + prec**0.5 + 15)\\n    s = MPZ_ZERO\\n    fac = from_int(4)\\n    t = ONE = MPZ_ONE << wp\\n    pi = mpf_pi(wp)\\n    pipow = twopi2 = mpf_shift(mpf_mul(pi, pi, wp), 2)\\n    n = 1\\n    while 1:\\n        zeta2n = mpf_abs(mpf_bernoulli(2*n, wp))\\n        zeta2n = mpf_mul(zeta2n, pipow, wp)\\n        zeta2n = mpf_div(zeta2n, fac, wp)\\n        zeta2n = to_fixed(zeta2n, wp)\\n        term = (((zeta2n - ONE) * t) // n) >> wp\\n        if term < 100:\\n            break\\n        #if not n % 10:\\n        #    print n, math.log(int(abs(term)))\\n        s += term\\n        t += ONE//(2*n+1) - ONE//(2*n)\\n        n += 1\\n        fac = mpf_mul_int(fac, (2*n)*(2*n-1), wp)\\n        pipow = mpf_mul(pipow, twopi2, wp)\\n    s = (s << wp) // ln2_fixed(wp)\\n    K = mpf_exp(from_man_exp(s, -wp), wp)\\n    K = to_fixed(K, prec)\\n    return K\\n\\n\\n# Glaisher's constant is defined as A = exp(1/2 - zeta'(-1)).\\n# One way to compute it would be to perform direct numerical\\n# differentiation, but computing arbitrary Riemann zeta function\\n# values at high precision is expensive. We instead use the formula\\n\\n#     A = exp((6 (-zeta'(2))/pi^2 + log 2 pi + gamma)/12)\\n\\n# and compute zeta'(2) from the series representation\\n\\n#              oo\\n#              ___\\n#             \\\\     log k\\n#  -zeta'(2) = )    -----\\n#             /___     2\\n#                    k\\n#            k = 2\\n\\n# This series converges exceptionally slowly, but can be accelerated\\n# using Euler-Maclaurin formula. The important insight is that the\\n# E-M integral can be done in closed form and that the high order\\n# are given by\\n\\n#    n  /       \\\\\\n#   d   | log x |   a + b log x\\n#   --- | ----- | = -----------\\n#     n |   2   |      2 + n\\n#   dx  \\\\  x    /     x\\n\\n# where a and b are integers given by a simple recurrence. Note\\n# that just one logarithm is needed. However, lots of integer\\n# logarithms are required for the initial summation.\\n\\n# This algorithm could possibly be turned into a faster algorithm\\n# for general evaluation of zeta(s) or zeta'(s); this should be\\n# looked into.\\n\\n@constant_memo\\ndef glaisher_fixed(prec):\\n    wp = prec + 30\\n    # Number of direct terms to sum before applying the Euler-Maclaurin\\n    # formula to the tail. TODO: choose more intelligently\\n    N = int(0.33*prec + 5)\\n    ONE = MPZ_ONE << wp\\n    # Euler-Maclaurin, step 1: sum log(k)/k**2 for k from 2 to N-1\\n    s = MPZ_ZERO\\n    for k in range(2, N):\\n        #print k, N\\n        s += log_int_fixed(k, wp) // k**2\\n    logN = log_int_fixed(N, wp)\\n    #logN = to_fixed(mpf_log(from_int(N), wp+20), wp)\\n    # E-M step 2: integral of log(x)/x**2 from N to inf\\n    s += (ONE + logN) // N\\n    # E-M step 3: endpoint correction term f(N)/2\\n    s += logN // (N**2 * 2)\\n    # E-M step 4: the series of derivatives\\n    pN = N**3\\n    a = 1\\n    b = -2\\n    j = 3\\n    fac = from_int(2)\\n    k = 1\\n    while 1:\\n        # D(2*k-1) * B(2*k) / fac(2*k) [D(n) = nth derivative]\\n        D = ((a << wp) + b*logN) // pN\\n        D = from_man_exp(D, -wp)\\n        B = mpf_bernoulli(2*k, wp)\\n        term = mpf_mul(B, D, wp)\\n        term = mpf_div(term, fac, wp)\\n        term = to_fixed(term, wp)\\n        if abs(term) < 100:\\n            break\\n        #if not k % 10:\\n        #    print k, math.log(int(abs(term)), 10)\\n        s -= term\\n        # Advance derivative twice\\n        a, b, pN, j = b-a*j, -j*b, pN*N, j+1\\n        a, b, pN, j = b-a*j, -j*b, pN*N, j+1\\n        k += 1\\n        fac = mpf_mul_int(fac, (2*k)*(2*k-1), wp)\\n    # A = exp((6*s/pi**2 + log(2*pi) + euler)/12)\\n    pi = pi_fixed(wp)\\n    s *= 6\\n    s = (s << wp) // (pi**2 >> wp)\\n    s += euler_fixed(wp)\\n    s += to_fixed(mpf_log(from_man_exp(2*pi, -wp), wp), wp)\\n    s //= 12\\n    A = mpf_exp(from_man_exp(s, -wp), wp)\\n    return to_fixed(A, prec)\\n\\n# Apery's constant can be computed using the very rapidly convergent\\n# series\\n#              oo\\n#              ___              2                      10\\n#             \\\\         n  205 n  + 250 n + 77     (n!)\\n#  zeta(3) =   )    (-1)   -------------------  ----------\\n#             /___               64                      5\\n#             n = 0                             ((2n+1)!)\\n\\n@constant_memo\\ndef apery_fixed(prec):\\n    prec += 20\\n    d = MPZ_ONE << prec\\n    term = MPZ(77) << prec\\n    n = 1\\n    s = MPZ_ZERO\\n    while term:\\n        s += term\\n        d *= (n**10)\\n        d //= (((2*n+1)**5) * (2*n)**5)\\n        term = (-1)**n * (205*(n**2) + 250*n + 77) * d\\n        n += 1\\n    return s >> (20 + 6)\\n\\n\\\"\\\"\\\"\\nEuler's constant (gamma) is computed using the Brent-McMillan formula,\\ngamma ~= I(n)/J(n) - log(n), where\\n\\n   I(n) = sum_{k=0,1,2,...} (n**k / k!)**2 * H(k)\\n   J(n) = sum_{k=0,1,2,...} (n**k / k!)**2\\n   H(k) = 1 + 1/2 + 1/3 + ... + 1/k\\n\\nThe error is bounded by O(exp(-4n)). Choosing n to be a power\\nof two, 2**p, the logarithm becomes particularly easy to calculate.[1]\\n\\nWe use the formulation of Algorithm 3.9 in [2] to make the summation\\nmore efficient.\\n\\nReference:\\n[1] Xavier Gourdon & Pascal Sebah, The Euler constant: gamma\\nhttp://numbers.computation.free.fr/Constants/Gamma/gamma.pdf\\n\\n[2] [BorweinBailey]_\\n\\\"\\\"\\\"\\n\\n@constant_memo\\ndef euler_fixed(prec):\\n    extra = 30\\n    prec += extra\\n    # choose p such that exp(-4*(2**p)) < 2**-n\\n    p = int(math.log((prec/4) * math.log(2), 2)) + 1\\n    n = 2**p\\n    A = U = -p*ln2_fixed(prec)\\n    B = V = MPZ_ONE << prec\\n    k = 1\\n    while 1:\\n        B = B*n**2//k**2\\n        A = (A*n**2//k + B)//k\\n        U += A\\n        V += B\\n        if max(abs(A), abs(B)) < 100:\\n            break\\n        k += 1\\n    return (U<<(prec-extra))//V\\n\\n# Use zeta accelerated formulas for the Mertens and twin\\n# prime constants; see\\n# http://mathworld.wolfram.com/MertensConstant.html\\n# http://mathworld.wolfram.com/TwinPrimesConstant.html\\n\\n@constant_memo\\ndef mertens_fixed(prec):\\n    wp = prec + 20\\n    m = 2\\n    s = mpf_euler(wp)\\n    while 1:\\n        t = mpf_zeta_int(m, wp)\\n        if t == fone:\\n            break\\n        t = mpf_log(t, wp)\\n        t = mpf_mul_int(t, moebius(m), wp)\\n        t = mpf_div(t, from_int(m), wp)\\n        s = mpf_add(s, t)\\n        m += 1\\n    return to_fixed(s, prec)\\n\\n@constant_memo\\ndef twinprime_fixed(prec):\\n    def I(n):\\n        return sum(moebius(d)<<(n//d) for d in xrange(1,n+1) if not n%d)//n\\n    wp = 2*prec + 30\\n    res = fone\\n    primes = [from_rational(1,p,wp) for p in [2,3,5,7]]\\n    ppowers = [mpf_mul(p,p,wp) for p in primes]\\n    n = 2\\n    while 1:\\n        a = mpf_zeta_int(n, wp)\\n        for i in range(4):\\n            a = mpf_mul(a, mpf_sub(fone, ppowers[i]), wp)\\n            ppowers[i] = mpf_mul(ppowers[i], primes[i], wp)\\n        a = mpf_pow_int(a, -I(n), wp)\\n        if mpf_pos(a, prec+10, 'n') == fone:\\n            break\\n        #from libmpf import to_str\\n        #print n, to_str(mpf_sub(fone, a), 6)\\n        res = mpf_mul(res, a, wp)\\n        n += 1\\n    res = mpf_mul(res, from_int(3*15*35), wp)\\n    res = mpf_div(res, from_int(4*16*36), wp)\\n    return to_fixed(res, prec)\\n\\n\\nmpf_euler = def_mpf_constant(euler_fixed)\\nmpf_apery = def_mpf_constant(apery_fixed)\\nmpf_khinchin = def_mpf_constant(khinchin_fixed)\\nmpf_glaisher = def_mpf_constant(glaisher_fixed)\\nmpf_catalan = def_mpf_constant(catalan_fixed)\\nmpf_mertens = def_mpf_constant(mertens_fixed)\\nmpf_twinprime = def_mpf_constant(twinprime_fixed)\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                          Bernoulli numbers                            #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\nMAX_BERNOULLI_CACHE = 3000\\n\\n\\nr\\\"\\\"\\\"\\nSmall Bernoulli numbers and factorials are used in numerous summations,\\nso it is critical for speed that sequential computation is fast and that\\nvalues are cached up to a fairly high threshold.\\n\\nOn the other hand, we also want to support fast computation of isolated\\nlarge numbers. Currently, no such acceleration is provided for integer\\nfactorials (though it is for large floating-point factorials, which are\\ncomputed via gamma if the precision is low enough).\\n\\nFor sequential computation of Bernoulli numbers, we use Ramanujan's formula\\n\\n                           / n + 3 \\\\\\n  B   =  (A(n) - S(n))  /  |       |\\n   n                       \\\\   n   /\\n\\nwhere A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6\\nwhen n = 4 (mod 6), and\\n\\n         [n/6]\\n          ___\\n         \\\\      /  n + 3  \\\\\\n  S(n) =  )     |         | * B\\n         /___   \\\\ n - 6*k /    n-6*k\\n         k = 1\\n\\nFor isolated large Bernoulli numbers, we use the Riemann zeta function\\nto calculate a numerical value for B_n. The von Staudt-Clausen theorem\\ncan then be used to optionally find the exact value of the\\nnumerator and denominator.\\n\\\"\\\"\\\"\\n\\nbernoulli_cache = {}\\nf3 = from_int(3)\\nf6 = from_int(6)\\n\\ndef bernoulli_size(n):\\n    \\\"\\\"\\\"Accurately estimate the size of B_n (even n > 2 only)\\\"\\\"\\\"\\n    lgn = math.log(n,2)\\n    return int(2.326 + 0.5*lgn + n*(lgn - 4.094))\\n\\nBERNOULLI_PREC_CUTOFF = bernoulli_size(MAX_BERNOULLI_CACHE)\\n\\ndef mpf_bernoulli(n, prec, rnd=None):\\n    \\\"\\\"\\\"Computation of Bernoulli numbers (numerically)\\\"\\\"\\\"\\n    if n < 2:\\n        if n < 0:\\n            raise ValueError(\\\"Bernoulli numbers only defined for n >= 0\\\")\\n        if n == 0:\\n            return fone\\n        if n == 1:\\n            return mpf_neg(fhalf)\\n    # For odd n > 1, the Bernoulli numbers are zero\\n    if n & 1:\\n        return fzero\\n    # If precision is extremely high, we can save time by computing\\n    # the Bernoulli number at a lower precision that is sufficient to\\n    # obtain the exact fraction, round to the exact fraction, and\\n    # convert the fraction back to an mpf value at the original precision\\n    if prec > BERNOULLI_PREC_CUTOFF and prec > bernoulli_size(n)*1.1 + 1000:\\n        p, q = bernfrac(n)\\n        return from_rational(p, q, prec, rnd or round_floor)\\n    if n > MAX_BERNOULLI_CACHE:\\n        return mpf_bernoulli_huge(n, prec, rnd)\\n    wp = prec + 30\\n    # Reuse nearby precisions\\n    wp += 32 - (prec & 31)\\n    cached = bernoulli_cache.get(wp)\\n    if cached:\\n        numbers, state = cached\\n        if n in numbers:\\n            if not rnd:\\n                return numbers[n]\\n            return mpf_pos(numbers[n], prec, rnd)\\n        m, bin, bin1 = state\\n        if n - m > 10:\\n            return mpf_bernoulli_huge(n, prec, rnd)\\n    else:\\n        if n > 10:\\n            return mpf_bernoulli_huge(n, prec, rnd)\\n        numbers = {0:fone}\\n        m, bin, bin1 = state = [2, MPZ(10), MPZ_ONE]\\n        bernoulli_cache[wp] = (numbers, state)\\n    while m <= n:\\n        #print m\\n        case = m % 6\\n        # Accurately estimate size of B_m so we can use\\n        # fixed point math without using too much precision\\n        szbm = bernoulli_size(m)\\n        s = 0\\n        sexp = max(0, szbm)  - wp\\n        if m < 6:\\n            a = MPZ_ZERO\\n        else:\\n            a = bin1\\n        for j in xrange(1, m//6+1):\\n            usign, uman, uexp, ubc = u = numbers[m-6*j]\\n            if usign:\\n                uman = -uman\\n            s += lshift(a*uman, uexp-sexp)\\n            # Update inner binomial coefficient\\n            j6 = 6*j\\n            a *= ((m-5-j6)*(m-4-j6)*(m-3-j6)*(m-2-j6)*(m-1-j6)*(m-j6))\\n            a //= ((4+j6)*(5+j6)*(6+j6)*(7+j6)*(8+j6)*(9+j6))\\n        if case == 0: b = mpf_rdiv_int(m+3, f3, wp)\\n        if case == 2: b = mpf_rdiv_int(m+3, f3, wp)\\n        if case == 4: b = mpf_rdiv_int(-m-3, f6, wp)\\n        s = from_man_exp(s, sexp, wp)\\n        b = mpf_div(mpf_sub(b, s, wp), from_int(bin), wp)\\n        numbers[m] = b\\n        m += 2\\n        # Update outer binomial coefficient\\n        bin = bin * ((m+2)*(m+3)) // (m*(m-1))\\n        if m > 6:\\n            bin1 = bin1 * ((2+m)*(3+m)) // ((m-7)*(m-6))\\n        state[:] = [m, bin, bin1]\\n    return numbers[n]\\n\\ndef mpf_bernoulli_huge(n, prec, rnd=None):\\n    wp = prec + 10\\n    piprec = wp + int(math.log(n,2))\\n    v = mpf_gamma_int(n+1, wp)\\n    v = mpf_mul(v, mpf_zeta_int(n, wp), wp)\\n    v = mpf_mul(v, mpf_pow_int(mpf_pi(piprec), -n, wp))\\n    v = mpf_shift(v, 1-n)\\n    if not n & 3:\\n        v = mpf_neg(v)\\n    return mpf_pos(v, prec, rnd or round_fast)\\n\\ndef bernfrac(n):\\n    r\\\"\\\"\\\"\\n    Returns a tuple of integers `(p, q)` such that `p/q = B_n` exactly,\\n    where `B_n` denotes the `n`-th Bernoulli number. The fraction is\\n    always reduced to lowest terms. Note that for `n > 1` and `n` odd,\\n    `B_n = 0`, and `(0, 1)` is returned.\\n\\n    **Examples**\\n\\n    The first few Bernoulli numbers are exactly::\\n\\n        >>> from mpmath import *\\n        >>> for n in range(15):\\n        ...     p, q = bernfrac(n)\\n        ...     print(\\\"%s %s/%s\\\" % (n, p, q))\\n        ...\\n        0 1/1\\n        1 -1/2\\n        2 1/6\\n        3 0/1\\n        4 -1/30\\n        5 0/1\\n        6 1/42\\n        7 0/1\\n        8 -1/30\\n        9 0/1\\n        10 5/66\\n        11 0/1\\n        12 -691/2730\\n        13 0/1\\n        14 7/6\\n\\n    This function works for arbitrarily large `n`::\\n\\n        >>> p, q = bernfrac(10**4)\\n        >>> print(q)\\n        2338224387510\\n        >>> print(len(str(p)))\\n        27692\\n        >>> mp.dps = 15\\n        >>> print(mpf(p) / q)\\n        -9.04942396360948e+27677\\n        >>> print(bernoulli(10**4))\\n        -9.04942396360948e+27677\\n\\n    .. note ::\\n\\n        :func:`~mpmath.bernoulli` computes a floating-point approximation\\n        directly, without computing the exact fraction first.\\n        This is much faster for large `n`.\\n\\n    **Algorithm**\\n\\n    :func:`~mpmath.bernfrac` works by computing the value of `B_n` numerically\\n    and then using the von Staudt-Clausen theorem [1] to reconstruct\\n    the exact fraction. For large `n`, this is significantly faster than\\n    computing `B_1, B_2, \\\\ldots, B_2` recursively with exact arithmetic.\\n    The implementation has been tested for `n = 10^m` up to `m = 6`.\\n\\n    In practice, :func:`~mpmath.bernfrac` appears to be about three times\\n    slower than the specialized program calcbn.exe [2]\\n\\n    **References**\\n\\n    1. MathWorld, von Staudt-Clausen Theorem:\\n       http://mathworld.wolfram.com/vonStaudt-ClausenTheorem.html\\n\\n    2. The Bernoulli Number Page:\\n       http://www.bernoulli.org/\\n\\n    \\\"\\\"\\\"\\n    n = int(n)\\n    if n < 3:\\n        return [(1, 1), (-1, 2), (1, 6)][n]\\n    if n & 1:\\n        return (0, 1)\\n    q = 1\\n    for k in list_primes(n+1):\\n        if not (n % (k-1)):\\n            q *= k\\n    prec = bernoulli_size(n) + int(math.log(q,2)) + 20\\n    b = mpf_bernoulli(n, prec)\\n    p = mpf_mul(b, from_int(q))\\n    pint = to_int(p, round_nearest)\\n    return (pint, q)\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                         Polygamma functions                           #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\nr\\\"\\\"\\\"\\nFor all polygamma (psi) functions, we use the Euler-Maclaurin summation\\nformula. It looks slightly different in the m = 0 and m > 0 cases.\\n\\nFor m = 0, we have\\n                                 oo\\n                                ___   B\\n       (0)                1    \\\\       2 k    -2 k\\n    psi   (z)  ~ log z + --- -  )    ------  z\\n                         2 z   /___  (2 k)!\\n                               k = 1\\n\\nExperiment shows that the minimum term of the asymptotic series\\nreaches 2^(-p) when Re(z) > 0.11*p. So we simply use the recurrence\\nfor psi (equivalent, in fact, to summing to the first few terms\\ndirectly before applying E-M) to obtain z large enough.\\n\\nSince, very crudely, log z ~= 1 for Re(z) > 1, we can use\\nfixed-point arithmetic  (if z is extremely large, log(z) itself\\nis a sufficient approximation, so we can stop there already).\\n\\nFor Re(z) << 0, we could use recurrence, but this is of course\\ninefficient for large negative z, so there we use the\\nreflection formula instead.\\n\\nFor m > 0, we have\\n\\n                  N - 1\\n                   ___\\n  ~~~(m)       [  \\\\          1    ]         1            1\\n  psi   (z)  ~ [   )     -------- ] +  ---------- +  -------- +\\n               [  /___        m+1 ]           m+1           m\\n                  k = 1  (z+k)    ]    2 (z+N)       m (z+N)\\n\\n      oo\\n     ___    B\\n    \\\\        2 k   (m+1) (m+2) ... (m+2k-1)\\n  +  )     ------  ------------------------\\n    /___   (2 k)!            m + 2 k\\n    k = 1               (z+N)\\n\\nwhere ~~~ denotes the function rescaled by 1/((-1)^(m+1) m!).\\n\\nHere again N is chosen to make z+N large enough for the minimum\\nterm in the last series to become smaller than eps.\\n\\nTODO: the current estimation of N for m > 0 is *very suboptimal*.\\n\\nTODO: implement the reflection formula for m > 0, Re(z) << 0.\\nIt is generally a combination of multiple cotangents. Need to\\nfigure out a reasonably simple way to generate these formulas\\non the fly.\\n\\nTODO: maybe use exact algorithms to compute psi for integral\\nand certain rational arguments, as this can be much more\\nefficient. (On the other hand, the availability of these\\nspecial values provides a convenient way to test the general\\nalgorithm.)\\n\\\"\\\"\\\"\\n\\n# Harmonic numbers are just shifted digamma functions\\n# We should calculate these exactly when x is an integer\\n# and when doing so is faster.\\n\\ndef mpf_harmonic(x, prec, rnd):\\n    if x in (fzero, fnan, finf):\\n        return x\\n    a = mpf_psi0(mpf_add(fone, x, prec+5), prec)\\n    return mpf_add(a, mpf_euler(prec+5, rnd), prec, rnd)\\n\\ndef mpc_harmonic(z, prec, rnd):\\n    if z[1] == fzero:\\n        return (mpf_harmonic(z[0], prec, rnd), fzero)\\n    a = mpc_psi0(mpc_add_mpf(z, fone, prec+5), prec)\\n    return mpc_add_mpf(a, mpf_euler(prec+5, rnd), prec, rnd)\\n\\ndef mpf_psi0(x, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computation of the digamma function (psi function of order 0)\\n    of a real argument.\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    wp = prec + 10\\n    if not man:\\n        if x == finf: return x\\n        if x == fninf or x == fnan: return fnan\\n    if x == fzero or (exp >= 0 and sign):\\n        raise ValueError(\\\"polygamma pole\\\")\\n    # Near 0 -- fixed-point arithmetic becomes bad\\n    if exp+bc < -5:\\n        v = mpf_psi0(mpf_add(x, fone, prec, rnd), prec, rnd)\\n        return mpf_sub(v, mpf_div(fone, x, wp, rnd), prec, rnd)\\n    # Reflection formula\\n    if sign and exp+bc > 3:\\n        c, s = mpf_cos_sin_pi(x, wp)\\n        q = mpf_mul(mpf_div(c, s, wp), mpf_pi(wp), wp)\\n        p = mpf_psi0(mpf_sub(fone, x, wp), wp)\\n        return mpf_sub(p, q, prec, rnd)\\n    # The logarithmic term is accurate enough\\n    if (not sign) and bc + exp > wp:\\n        return mpf_log(mpf_sub(x, fone, wp), prec, rnd)\\n    # Initial recurrence to obtain a large enough x\\n    m = to_int(x)\\n    n = int(0.11*wp) + 2\\n    s = MPZ_ZERO\\n    x = to_fixed(x, wp)\\n    one = MPZ_ONE << wp\\n    if m < n:\\n        for k in xrange(m, n):\\n            s -= (one << wp) // x\\n            x += one\\n    x -= one\\n    # Logarithmic term\\n    s += to_fixed(mpf_log(from_man_exp(x, -wp, wp), wp), wp)\\n    # Endpoint term in Euler-Maclaurin expansion\\n    s += (one << wp) // (2*x)\\n    # Euler-Maclaurin remainder sum\\n    x2 = (x*x) >> wp\\n    t = one\\n    prev = 0\\n    k = 1\\n    while 1:\\n        t = (t*x2) >> wp\\n        bsign, bman, bexp, bbc = mpf_bernoulli(2*k, wp)\\n        offset = (bexp + 2*wp)\\n        if offset >= 0: term = (bman << offset) // (t*(2*k))\\n        else:           term = (bman >> (-offset)) // (t*(2*k))\\n        if k & 1: s -= term\\n        else:     s += term\\n        if k > 2 and term >= prev:\\n            break\\n        prev = term\\n        k += 1\\n    return from_man_exp(s, -wp, wp, rnd)\\n\\ndef mpc_psi0(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computation of the digamma function (psi function of order 0)\\n    of a complex argument.\\n    \\\"\\\"\\\"\\n    re, im = z\\n    # Fall back to the real case\\n    if im == fzero:\\n        return (mpf_psi0(re, prec, rnd), fzero)\\n    wp = prec + 20\\n    sign, man, exp, bc = re\\n    # Reflection formula\\n    if sign and exp+bc > 3:\\n        c = mpc_cos_pi(z, wp)\\n        s = mpc_sin_pi(z, wp)\\n        q = mpc_mul_mpf(mpc_div(c, s, wp), mpf_pi(wp), wp)\\n        p = mpc_psi0(mpc_sub(mpc_one, z, wp), wp)\\n        return mpc_sub(p, q, prec, rnd)\\n    # Just the logarithmic term\\n    if (not sign) and bc + exp > wp:\\n        return mpc_log(mpc_sub(z, mpc_one, wp), prec, rnd)\\n    # Initial recurrence to obtain a large enough z\\n    w = to_int(re)\\n    n = int(0.11*wp) + 2\\n    s = mpc_zero\\n    if w < n:\\n        for k in xrange(w, n):\\n            s = mpc_sub(s, mpc_reciprocal(z, wp), wp)\\n            z = mpc_add_mpf(z, fone, wp)\\n    z = mpc_sub(z, mpc_one, wp)\\n    # Logarithmic and endpoint term\\n    s = mpc_add(s, mpc_log(z, wp), wp)\\n    s = mpc_add(s, mpc_div(mpc_half, z, wp), wp)\\n    # Euler-Maclaurin remainder sum\\n    z2 = mpc_square(z, wp)\\n    t = mpc_one\\n    prev = mpc_zero\\n    szprev = fzero\\n    k = 1\\n    eps = mpf_shift(fone, -wp+2)\\n    while 1:\\n        t = mpc_mul(t, z2, wp)\\n        bern = mpf_bernoulli(2*k, wp)\\n        term = mpc_mpf_div(bern, mpc_mul_int(t, 2*k, wp), wp)\\n        s = mpc_sub(s, term, wp)\\n        szterm = mpc_abs(term, 10)\\n        if k > 2 and (mpf_le(szterm, eps) or mpf_le(szprev, szterm)):\\n            break\\n        prev = term\\n        szprev = szterm\\n        k += 1\\n    return s\\n\\n# Currently unoptimized\\ndef mpf_psi(m, x, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computation of the polygamma function of arbitrary integer order\\n    m >= 0, for a real argument x.\\n    \\\"\\\"\\\"\\n    if m == 0:\\n        return mpf_psi0(x, prec, rnd=round_fast)\\n    return mpc_psi(m, (x, fzero), prec, rnd)[0]\\n\\ndef mpc_psi(m, z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computation of the polygamma function of arbitrary integer order\\n    m >= 0, for a complex argument z.\\n    \\\"\\\"\\\"\\n    if m == 0:\\n        return mpc_psi0(z, prec, rnd)\\n    re, im = z\\n    wp = prec + 20\\n    sign, man, exp, bc = re\\n    if not im[1]:\\n        if im in (finf, fninf, fnan):\\n            return (fnan, fnan)\\n    if not man:\\n        if re == finf and im == fzero:\\n            return (fzero, fzero)\\n        if re == fnan:\\n            return (fnan, fnan)\\n    # Recurrence\\n    w = to_int(re)\\n    n = int(0.4*wp + 4*m)\\n    s = mpc_zero\\n    if w < n:\\n        for k in xrange(w, n):\\n            t = mpc_pow_int(z, -m-1, wp)\\n            s = mpc_add(s, t, wp)\\n            z = mpc_add_mpf(z, fone, wp)\\n    zm = mpc_pow_int(z, -m, wp)\\n    z2 = mpc_pow_int(z, -2, wp)\\n    # 1/m*(z+N)^m\\n    integral_term = mpc_div_mpf(zm, from_int(m), wp)\\n    s = mpc_add(s, integral_term, wp)\\n    # 1/2*(z+N)^(-(m+1))\\n    s = mpc_add(s, mpc_mul_mpf(mpc_div(zm, z, wp), fhalf, wp), wp)\\n    a = m + 1\\n    b = 2\\n    k = 1\\n    # Important: we want to sum up to the *relative* error,\\n    # not the absolute error, because psi^(m)(z) might be tiny\\n    magn = mpc_abs(s, 10)\\n    magn = magn[2]+magn[3]\\n    eps = mpf_shift(fone, magn-wp+2)\\n    while 1:\\n        zm = mpc_mul(zm, z2, wp)\\n        bern = mpf_bernoulli(2*k, wp)\\n        scal = mpf_mul_int(bern, a, wp)\\n        scal = mpf_div(scal, from_int(b), wp)\\n        term = mpc_mul_mpf(zm, scal, wp)\\n        s = mpc_add(s, term, wp)\\n        szterm = mpc_abs(term, 10)\\n        if k > 2 and mpf_le(szterm, eps):\\n            break\\n        #print k, to_str(szterm, 10), to_str(eps, 10)\\n        a *= (m+2*k)*(m+2*k+1)\\n        b *= (2*k+1)*(2*k+2)\\n        k += 1\\n    # Scale and sign factor\\n    v = mpc_mul_mpf(s, mpf_gamma(from_int(m+1), wp), prec, rnd)\\n    if not (m & 1):\\n        v = mpf_neg(v[0]), mpf_neg(v[1])\\n    return v\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                         Riemann zeta function                         #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\nr\\\"\\\"\\\"\\nWe use zeta(s) = eta(s) / (1 - 2**(1-s)) and Borwein's approximation\\n\\n                  n-1\\n                  ___       k\\n             -1  \\\\      (-1)  (d_k - d_n)\\n  eta(s) ~= ----  )     ------------------\\n             d_n /___              s\\n                 k = 0      (k + 1)\\nwhere\\n             k\\n             ___                i\\n            \\\\     (n + i - 1)! 4\\n  d_k  =  n  )    ---------------.\\n            /___   (n - i)! (2i)!\\n            i = 0\\n\\nIf s = a + b*I, the absolute error for eta(s) is bounded by\\n\\n    3 (1 + 2|b|)\\n    ------------ * exp(|b| pi/2)\\n               n\\n    (3+sqrt(8))\\n\\nDisregarding the linear term, we have approximately,\\n\\n  log(err) ~= log(exp(1.58*|b|)) - log(5.8**n)\\n  log(err) ~= 1.58*|b| - log(5.8)*n\\n  log(err) ~= 1.58*|b| - 1.76*n\\n  log2(err) ~= 2.28*|b| - 2.54*n\\n\\nSo for p bits, we should choose n > (p + 2.28*|b|) / 2.54.\\n\\nReferences:\\n-----------\\n\\nPeter Borwein, \\\"An Efficient Algorithm for the Riemann Zeta Function\\\"\\nhttp://www.cecm.sfu.ca/personal/pborwein/PAPERS/P117.ps\\n\\nhttp://en.wikipedia.org/wiki/Dirichlet_eta_function\\n\\\"\\\"\\\"\\n\\nborwein_cache = {}\\n\\ndef borwein_coefficients(n):\\n    if n in borwein_cache:\\n        return borwein_cache[n]\\n    ds = [MPZ_ZERO] * (n+1)\\n    d = MPZ_ONE\\n    s = ds[0] = MPZ_ONE\\n    for i in range(1, n+1):\\n        d = d * 4 * (n+i-1) * (n-i+1)\\n        d //= ((2*i) * ((2*i)-1))\\n        s += d\\n        ds[i] = s\\n    borwein_cache[n] = ds\\n    return ds\\n\\nZETA_INT_CACHE_MAX_PREC = 1000\\nzeta_int_cache = {}\\n\\ndef mpf_zeta_int(s, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Optimized computation of zeta(s) for an integer s.\\n    \\\"\\\"\\\"\\n    wp = prec + 20\\n    s = int(s)\\n    if s in zeta_int_cache and zeta_int_cache[s][0] >= wp:\\n        return mpf_pos(zeta_int_cache[s][1], prec, rnd)\\n    if s < 2:\\n        if s == 1:\\n            raise ValueError(\\\"zeta(1) pole\\\")\\n        if not s:\\n            return mpf_neg(fhalf)\\n        return mpf_div(mpf_bernoulli(-s+1, wp), from_int(s-1), prec, rnd)\\n    # 2^-s term vanishes?\\n    if s >= wp:\\n        return mpf_perturb(fone, 0, prec, rnd)\\n    # 5^-s term vanishes?\\n    elif s >= wp*0.431:\\n        t = one = 1 << wp\\n        t += 1 << (wp - s)\\n        t += one // (MPZ_THREE ** s)\\n        t += 1 << max(0, wp - s*2)\\n        return from_man_exp(t, -wp, prec, rnd)\\n    else:\\n        # Fast enough to sum directly?\\n        # Even better, we use the Euler product (idea stolen from pari)\\n        m = (float(wp)/(s-1) + 1)\\n        if m < 30:\\n            needed_terms = int(2.0**m + 1)\\n            if needed_terms < int(wp/2.54 + 5) / 10:\\n                t = fone\\n                for k in list_primes(needed_terms):\\n                    #print k, needed_terms\\n                    powprec = int(wp - s*math.log(k,2))\\n                    if powprec < 2:\\n                        break\\n                    a = mpf_sub(fone, mpf_pow_int(from_int(k), -s, powprec), wp)\\n                    t = mpf_mul(t, a, wp)\\n                return mpf_div(fone, t, wp)\\n    # Use Borwein's algorithm\\n    n = int(wp/2.54 + 5)\\n    d = borwein_coefficients(n)\\n    t = MPZ_ZERO\\n    s = MPZ(s)\\n    for k in xrange(n):\\n        t += (((-1)**k * (d[k] - d[n])) << wp) // (k+1)**s\\n    t = (t << wp) // (-d[n])\\n    t = (t << wp) // ((1 << wp) - (1 << (wp+1-s)))\\n    if (s in zeta_int_cache and zeta_int_cache[s][0] < wp) or (s not in zeta_int_cache):\\n        zeta_int_cache[s] = (wp, from_man_exp(t, -wp-wp))\\n    return from_man_exp(t, -wp-wp, prec, rnd)\\n\\ndef mpf_zeta(s, prec, rnd=round_fast, alt=0):\\n    sign, man, exp, bc = s\\n    if not man:\\n        if s == fzero:\\n            if alt:\\n                return fhalf\\n            else:\\n                return mpf_neg(fhalf)\\n        if s == finf:\\n            return fone\\n        return fnan\\n    wp = prec + 20\\n    # First term vanishes?\\n    if (not sign) and (exp + bc > (math.log(wp,2) + 2)):\\n        return mpf_perturb(fone, alt, prec, rnd)\\n    # Optimize for integer arguments\\n    elif exp >= 0:\\n        if alt:\\n            if s == fone:\\n                return mpf_ln2(prec, rnd)\\n            z = mpf_zeta_int(to_int(s), wp, negative_rnd[rnd])\\n            q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)\\n            return mpf_mul(z, q, prec, rnd)\\n        else:\\n            return mpf_zeta_int(to_int(s), prec, rnd)\\n    # Negative: use the reflection formula\\n    # Borwein only proves the accuracy bound for x >= 1/2. However, based on\\n    # tests, the accuracy without reflection is quite good even some distance\\n    # to the left of 1/2. XXX: verify this.\\n    if sign:\\n        # XXX: could use the separate refl. formula for Dirichlet eta\\n        if alt:\\n            q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)\\n            return mpf_mul(mpf_zeta(s, wp), q, prec, rnd)\\n        # XXX: -1 should be done exactly\\n        y = mpf_sub(fone, s, 10*wp)\\n        a = mpf_gamma(y, wp)\\n        b = mpf_zeta(y, wp)\\n        c = mpf_sin_pi(mpf_shift(s, -1), wp)\\n        wp2 = wp + max(0,exp+bc)\\n        pi = mpf_pi(wp+wp2)\\n        d = mpf_div(mpf_pow(mpf_shift(pi, 1), s, wp2), pi, wp2)\\n        return mpf_mul(a,mpf_mul(b,mpf_mul(c,d,wp),wp),prec,rnd)\\n\\n    # Near pole\\n    r = mpf_sub(fone, s, wp)\\n    asign, aman, aexp, abc = mpf_abs(r)\\n    pole_dist = -2*(aexp+abc)\\n    if pole_dist > wp:\\n        if alt:\\n            return mpf_ln2(prec, rnd)\\n        else:\\n            q = mpf_neg(mpf_div(fone, r, wp))\\n            return mpf_add(q, mpf_euler(wp), prec, rnd)\\n    else:\\n        wp += max(0, pole_dist)\\n\\n    t = MPZ_ZERO\\n    #wp += 16 - (prec & 15)\\n    # Use Borwein's algorithm\\n    n = int(wp/2.54 + 5)\\n    d = borwein_coefficients(n)\\n    t = MPZ_ZERO\\n    sf = to_fixed(s, wp)\\n    ln2 = ln2_fixed(wp)\\n    for k in xrange(n):\\n        u = (-sf*log_int_fixed(k+1, wp, ln2)) >> wp\\n        #esign, eman, eexp, ebc = mpf_exp(u, wp)\\n        #offset = eexp + wp\\n        #if offset >= 0:\\n        #    w = ((d[k] - d[n]) * eman) << offset\\n        #else:\\n        #    w = ((d[k] - d[n]) * eman) >> (-offset)\\n        eman = exp_fixed(u, wp, ln2)\\n        w = (d[k] - d[n]) * eman\\n        if k & 1:\\n            t -= w\\n        else:\\n            t += w\\n    t = t // (-d[n])\\n    t = from_man_exp(t, -wp, wp)\\n    if alt:\\n        return mpf_pos(t, prec, rnd)\\n    else:\\n        q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)\\n        return mpf_div(t, q, prec, rnd)\\n\\ndef mpc_zeta(s, prec, rnd=round_fast, alt=0, force=False):\\n    re, im = s\\n    if im == fzero:\\n        return mpf_zeta(re, prec, rnd, alt), fzero\\n\\n    # slow for large s\\n    if (not force) and mpf_gt(mpc_abs(s, 10), from_int(prec)):\\n        raise NotImplementedError\\n\\n    wp = prec + 20\\n\\n    # Near pole\\n    r = mpc_sub(mpc_one, s, wp)\\n    asign, aman, aexp, abc = mpc_abs(r, 10)\\n    pole_dist = -2*(aexp+abc)\\n    if pole_dist > wp:\\n        if alt:\\n            q = mpf_ln2(wp)\\n            y = mpf_mul(q, mpf_euler(wp), wp)\\n            g = mpf_shift(mpf_mul(q, q, wp), -1)\\n            g = mpf_sub(y, g)\\n            z = mpc_mul_mpf(r, mpf_neg(g), wp)\\n            z = mpc_add_mpf(z, q, wp)\\n            return mpc_pos(z, prec, rnd)\\n        else:\\n            q = mpc_neg(mpc_div(mpc_one, r, wp))\\n            q = mpc_add_mpf(q, mpf_euler(wp), wp)\\n            return mpc_pos(q, prec, rnd)\\n    else:\\n        wp += max(0, pole_dist)\\n\\n    # Reflection formula. To be rigorous, we should reflect to the left of\\n    # re = 1/2 (see comments for mpf_zeta), but this leads to unnecessary\\n    # slowdown for interesting values of s\\n    if mpf_lt(re, fzero):\\n        # XXX: could use the separate refl. formula for Dirichlet eta\\n        if alt:\\n            q = mpc_sub(mpc_one, mpc_pow(mpc_two, mpc_sub(mpc_one, s, wp),\\n                wp), wp)\\n            return mpc_mul(mpc_zeta(s, wp), q, prec, rnd)\\n        # XXX: -1 should be done exactly\\n        y = mpc_sub(mpc_one, s, 10*wp)\\n        a = mpc_gamma(y, wp)\\n        b = mpc_zeta(y, wp)\\n        c = mpc_sin_pi(mpc_shift(s, -1), wp)\\n        rsign, rman, rexp, rbc = re\\n        isign, iman, iexp, ibc = im\\n        mag = max(rexp+rbc, iexp+ibc)\\n        wp2 = wp + max(0, mag)\\n        pi = mpf_pi(wp+wp2)\\n        pi2 = (mpf_shift(pi, 1), fzero)\\n        d = mpc_div_mpf(mpc_pow(pi2, s, wp2), pi, wp2)\\n        return mpc_mul(a,mpc_mul(b,mpc_mul(c,d,wp),wp),prec,rnd)\\n    n = int(wp/2.54 + 5)\\n    n += int(0.9*abs(to_int(im)))\\n    d = borwein_coefficients(n)\\n    ref = to_fixed(re, wp)\\n    imf = to_fixed(im, wp)\\n    tre = MPZ_ZERO\\n    tim = MPZ_ZERO\\n    one = MPZ_ONE << wp\\n    one_2wp = MPZ_ONE << (2*wp)\\n    critical_line = re == fhalf\\n    ln2 = ln2_fixed(wp)\\n    pi2 = pi_fixed(wp-1)\\n    wp2 = wp+wp\\n    for k in xrange(n):\\n        log = log_int_fixed(k+1, wp, ln2)\\n        # A square root is much cheaper than an exp\\n        if critical_line:\\n            w = one_2wp // isqrt_fast((k+1) << wp2)\\n        else:\\n            w = exp_fixed((-ref*log) >> wp, wp)\\n        if k & 1:\\n            w *= (d[n] - d[k])\\n        else:\\n            w *= (d[k] - d[n])\\n        wre, wim = cos_sin_fixed((-imf*log)>>wp, wp, pi2)\\n        tre += (w * wre) >> wp\\n        tim += (w * wim) >> wp\\n    tre //= (-d[n])\\n    tim //= (-d[n])\\n    tre = from_man_exp(tre, -wp, wp)\\n    tim = from_man_exp(tim, -wp, wp)\\n    if alt:\\n        return mpc_pos((tre, tim), prec, rnd)\\n    else:\\n        q = mpc_sub(mpc_one, mpc_pow(mpc_two, r, wp), wp)\\n        return mpc_div((tre, tim), q, prec, rnd)\\n\\ndef mpf_altzeta(s, prec, rnd=round_fast):\\n    return mpf_zeta(s, prec, rnd, 1)\\n\\ndef mpc_altzeta(s, prec, rnd=round_fast):\\n    return mpc_zeta(s, prec, rnd, 1)\\n\\n# Not optimized currently\\nmpf_zetasum = None\\n\\n\\ndef pow_fixed(x, n, wp):\\n    if n == 1:\\n        return x\\n    y = MPZ_ONE << wp\\n    while n:\\n        if n & 1:\\n            y = (y*x) >> wp\\n            n -= 1\\n        x = (x*x) >> wp\\n        n //= 2\\n    return y\\n\\n# TODO: optimize / cleanup interface / unify with list_primes\\nsieve_cache = []\\nprimes_cache = []\\nmult_cache = []\\n\\ndef primesieve(n):\\n    global sieve_cache, primes_cache, mult_cache\\n    if n < len(sieve_cache):\\n        sieve = sieve_cache#[:n+1]\\n        primes = primes_cache[:primes_cache.index(max(sieve))+1]\\n        mult = mult_cache#[:n+1]\\n        return sieve, primes, mult\\n    sieve = [0] * (n+1)\\n    mult = [0] * (n+1)\\n    primes = list_primes(n)\\n    for p in primes:\\n        #sieve[p::p] = p\\n        for k in xrange(p,n+1,p):\\n            sieve[k] = p\\n    for i, p in enumerate(sieve):\\n        if i >= 2:\\n            m = 1\\n            n = i // p\\n            while not n % p:\\n                n //= p\\n                m += 1\\n            mult[i] = m\\n    sieve_cache = sieve\\n    primes_cache = primes\\n    mult_cache = mult\\n    return sieve, primes, mult\\n\\ndef zetasum_sieved(critical_line, sre, sim, a, n, wp):\\n    if a < 1:\\n        raise ValueError(\\\"a cannot be less than 1\\\")\\n    sieve, primes, mult = primesieve(a+n)\\n    basic_powers = {}\\n    one = MPZ_ONE << wp\\n    one_2wp = MPZ_ONE << (2*wp)\\n    wp2 = wp+wp\\n    ln2 = ln2_fixed(wp)\\n    pi2 = pi_fixed(wp-1)\\n    for p in primes:\\n        if p*2 > a+n:\\n            break\\n        log = log_int_fixed(p, wp, ln2)\\n        cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)\\n        if critical_line:\\n            u = one_2wp // isqrt_fast(p<<wp2)\\n        else:\\n            u = exp_fixed((-sre*log)>>wp, wp)\\n        pre = (u*cos) >> wp\\n        pim = (u*sin) >> wp\\n        basic_powers[p] = [(pre, pim)]\\n        tre, tim = pre, pim\\n        for m in range(1,int(math.log(a+n,p)+0.01)+1):\\n            tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp)\\n            basic_powers[p].append((tre,tim))\\n    xre = MPZ_ZERO\\n    xim = MPZ_ZERO\\n    if a == 1:\\n        xre += one\\n    aa = max(a,2)\\n    for k in xrange(aa, a+n+1):\\n        p = sieve[k]\\n        if p in basic_powers:\\n            m = mult[k]\\n            tre, tim = basic_powers[p][m-1]\\n            while 1:\\n                k //= p**m\\n                if k == 1:\\n                    break\\n                p = sieve[k]\\n                m = mult[k]\\n                pre, pim = basic_powers[p][m-1]\\n                tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp)\\n        else:\\n            log = log_int_fixed(k, wp, ln2)\\n            cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)\\n            if critical_line:\\n                u = one_2wp // isqrt_fast(k<<wp2)\\n            else:\\n                u = exp_fixed((-sre*log)>>wp, wp)\\n            tre = (u*cos) >> wp\\n            tim = (u*sin) >> wp\\n        xre += tre\\n        xim += tim\\n    return xre, xim\\n\\n# Set to something large to disable\\nZETASUM_SIEVE_CUTOFF = 10\\n\\ndef mpc_zetasum(s, a, n, derivatives, reflect, prec):\\n    \\\"\\\"\\\"\\n    Fast version of mp._zetasum, assuming s = complex, a = integer.\\n    \\\"\\\"\\\"\\n\\n    wp = prec + 10\\n    derivatives = list(derivatives)\\n    have_derivatives = derivatives != [0]\\n    have_one_derivative = len(derivatives) == 1\\n\\n    # parse s\\n    sre, sim = s\\n    critical_line = (sre == fhalf)\\n    sre = to_fixed(sre, wp)\\n    sim = to_fixed(sim, wp)\\n\\n    if a > 0 and n > ZETASUM_SIEVE_CUTOFF and not have_derivatives \\\\\\n            and not reflect and (n < 4e7 or sys.maxsize > 2**32):\\n        re, im = zetasum_sieved(critical_line, sre, sim, a, n, wp)\\n        xs = [(from_man_exp(re, -wp, prec, 'n'), from_man_exp(im, -wp, prec, 'n'))]\\n        return xs, []\\n\\n    maxd = max(derivatives)\\n    if not have_one_derivative:\\n        derivatives = range(maxd+1)\\n\\n    # x_d = 0, y_d = 0\\n    xre = [MPZ_ZERO for d in derivatives]\\n    xim = [MPZ_ZERO for d in derivatives]\\n    if reflect:\\n        yre = [MPZ_ZERO for d in derivatives]\\n        yim = [MPZ_ZERO for d in derivatives]\\n    else:\\n        yre = yim = []\\n\\n    one = MPZ_ONE << wp\\n    one_2wp = MPZ_ONE << (2*wp)\\n\\n    ln2 = ln2_fixed(wp)\\n    pi2 = pi_fixed(wp-1)\\n    wp2 = wp+wp\\n\\n    for w in xrange(a, a+n+1):\\n        log = log_int_fixed(w, wp, ln2)\\n        cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)\\n        if critical_line:\\n            u = one_2wp // isqrt_fast(w<<wp2)\\n        else:\\n            u = exp_fixed((-sre*log)>>wp, wp)\\n        xterm_re = (u * cos) >> wp\\n        xterm_im = (u * sin) >> wp\\n        if reflect:\\n            reciprocal = (one_2wp // (u*w))\\n            yterm_re = (reciprocal * cos) >> wp\\n            yterm_im = (reciprocal * sin) >> wp\\n\\n        if have_derivatives:\\n            if have_one_derivative:\\n                log = pow_fixed(log, maxd, wp)\\n                xre[0] += (xterm_re * log) >> wp\\n                xim[0] += (xterm_im * log) >> wp\\n                if reflect:\\n                    yre[0] += (yterm_re * log) >> wp\\n                    yim[0] += (yterm_im * log) >> wp\\n            else:\\n                t = MPZ_ONE << wp\\n                for d in derivatives:\\n                    xre[d] += (xterm_re * t) >> wp\\n                    xim[d] += (xterm_im * t) >> wp\\n                    if reflect:\\n                        yre[d] += (yterm_re * t) >> wp\\n                        yim[d] += (yterm_im * t) >> wp\\n                    t = (t * log) >> wp\\n        else:\\n            xre[0] += xterm_re\\n            xim[0] += xterm_im\\n            if reflect:\\n                yre[0] += yterm_re\\n                yim[0] += yterm_im\\n    if have_derivatives:\\n        if have_one_derivative:\\n            if maxd % 2:\\n                xre[0] = -xre[0]\\n                xim[0] = -xim[0]\\n                if reflect:\\n                    yre[0] = -yre[0]\\n                    yim[0] = -yim[0]\\n        else:\\n            xre = [(-1)**d * xre[d] for d in derivatives]\\n            xim = [(-1)**d * xim[d] for d in derivatives]\\n            if reflect:\\n                yre = [(-1)**d * yre[d] for d in derivatives]\\n                yim = [(-1)**d * yim[d] for d in derivatives]\\n    xs = [(from_man_exp(xa, -wp, prec, 'n'), from_man_exp(xb, -wp, prec, 'n'))\\n        for (xa, xb) in zip(xre, xim)]\\n    ys = [(from_man_exp(ya, -wp, prec, 'n'), from_man_exp(yb, -wp, prec, 'n'))\\n        for (ya, yb) in zip(yre, yim)]\\n    return xs, ys\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#              The gamma function  (NEW IMPLEMENTATION)                 #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\n# Higher means faster, but more precomputation time\\nMAX_GAMMA_TAYLOR_PREC = 5000\\n# Need to derive higher bounds for Taylor series to go higher\\nassert MAX_GAMMA_TAYLOR_PREC < 15000\\n\\n# Use Stirling's series if abs(x) > beta*prec\\n# Important: must be large enough for convergence!\\nGAMMA_STIRLING_BETA = 0.2\\n\\nSMALL_FACTORIAL_CACHE_SIZE = 150\\n\\ngamma_taylor_cache = {}\\ngamma_stirling_cache = {}\\n\\nsmall_factorial_cache = [from_int(ifac(n)) for \\\\\\n    n in range(SMALL_FACTORIAL_CACHE_SIZE+1)]\\n\\ndef zeta_array(N, prec):\\n    \\\"\\\"\\\"\\n    zeta(n) = A * pi**n / n! + B\\n\\n    where A is a rational number (A = Bernoulli number\\n    for n even) and B is an infinite sum over powers of exp(2*pi).\\n    (B = 0 for n even).\\n\\n    TODO: this is currently only used for gamma, but could\\n    be very useful elsewhere.\\n    \\\"\\\"\\\"\\n    extra = 30\\n    wp = prec+extra\\n    zeta_values = [MPZ_ZERO] * (N+2)\\n    pi = pi_fixed(wp)\\n    # STEP 1:\\n    one = MPZ_ONE << wp\\n    zeta_values[0] = -one//2\\n    f_2pi = mpf_shift(mpf_pi(wp),1)\\n    exp_2pi_k = exp_2pi = mpf_exp(f_2pi, wp)\\n    # Compute exponential series\\n    # Store values of 1/(exp(2*pi*k)-1),\\n    # exp(2*pi*k)/(exp(2*pi*k)-1)**2, 1/(exp(2*pi*k)-1)**2\\n    # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2\\n    exps3 = []\\n    k = 1\\n    while 1:\\n        tp = wp - 9*k\\n        if tp < 1:\\n            break\\n        # 1/(exp(2*pi*k-1)\\n        q1 = mpf_div(fone, mpf_sub(exp_2pi_k, fone, tp), tp)\\n        # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2\\n        q2 = mpf_mul(exp_2pi_k, mpf_mul(q1,q1,tp), tp)\\n        q1 = to_fixed(q1, wp)\\n        q2 = to_fixed(q2, wp)\\n        q2 = (k * q2 * pi) >> wp\\n        exps3.append((q1, q2))\\n        # Multiply for next round\\n        exp_2pi_k = mpf_mul(exp_2pi_k, exp_2pi, wp)\\n        k += 1\\n    # Exponential sum\\n    for n in xrange(3, N+1, 2):\\n        s = MPZ_ZERO\\n        k = 1\\n        for e1, e2 in exps3:\\n            if n%4 == 3:\\n                t = e1 // k**n\\n            else:\\n                U = (n-1)//4\\n                t = (e1 + e2//U) // k**n\\n            if not t:\\n                break\\n            s += t\\n            k += 1\\n        zeta_values[n] = -2*s\\n    # Even zeta values\\n    B = [mpf_abs(mpf_bernoulli(k,wp)) for k in xrange(N+2)]\\n    pi_pow = fpi = mpf_pow_int(mpf_shift(mpf_pi(wp), 1), 2, wp)\\n    pi_pow = mpf_div(pi_pow, from_int(4), wp)\\n    for n in xrange(2,N+2,2):\\n        z = mpf_mul(B[n], pi_pow, wp)\\n        zeta_values[n] = to_fixed(z, wp)\\n        pi_pow = mpf_mul(pi_pow, fpi, wp)\\n        pi_pow = mpf_div(pi_pow, from_int((n+1)*(n+2)), wp)\\n    # Zeta sum\\n    reciprocal_pi = (one << wp) // pi\\n    for n in xrange(3, N+1, 4):\\n        U = (n-3)//4\\n        s = zeta_values[4*U+4]*(4*U+7)//4\\n        for k in xrange(1, U+1):\\n            s -= (zeta_values[4*k] * zeta_values[4*U+4-4*k]) >> wp\\n        zeta_values[n] += (2*s*reciprocal_pi) >> wp\\n    for n in xrange(5, N+1, 4):\\n        U = (n-1)//4\\n        s = zeta_values[4*U+2]*(2*U+1)\\n        for k in xrange(1, 2*U+1):\\n            s += ((-1)**k*2*k* zeta_values[2*k] * zeta_values[4*U+2-2*k])>>wp\\n        zeta_values[n] += ((s*reciprocal_pi)>>wp)//(2*U)\\n    return [x>>extra for x in zeta_values]\\n\\ndef gamma_taylor_coefficients(inprec):\\n    \\\"\\\"\\\"\\n    Gives the Taylor coefficients of 1/gamma(1+x) as\\n    a list of fixed-point numbers. Enough coefficients are returned\\n    to ensure that the series converges to the given precision\\n    when x is in [0.5, 1.5].\\n    \\\"\\\"\\\"\\n    # Reuse nearby cache values (small case)\\n    if inprec < 400:\\n        prec = inprec + (10-(inprec%10))\\n    elif inprec < 1000:\\n        prec = inprec + (30-(inprec%30))\\n    else:\\n        prec = inprec\\n    if prec in gamma_taylor_cache:\\n        return gamma_taylor_cache[prec], prec\\n\\n    # Experimentally determined bounds\\n    if prec < 1000:\\n        N = int(prec**0.76 + 2)\\n    else:\\n        # Valid to at least 15000 bits\\n        N = int(prec**0.787 + 2)\\n\\n    # Reuse higher precision values\\n    for cprec in gamma_taylor_cache:\\n        if cprec > prec:\\n            coeffs = [x>>(cprec-prec) for x in gamma_taylor_cache[cprec][-N:]]\\n            if inprec < 1000:\\n                gamma_taylor_cache[prec] = coeffs\\n            return coeffs, prec\\n\\n    # Cache at a higher precision (large case)\\n    if prec > 1000:\\n        prec = int(prec * 1.2)\\n\\n    wp = prec + 20\\n    A = [0] * N\\n    A[0] = MPZ_ZERO\\n    A[1] = MPZ_ONE << wp\\n    A[2] = euler_fixed(wp)\\n    # SLOW, reference implementation\\n    #zeta_values = [0,0]+[to_fixed(mpf_zeta_int(k,wp),wp) for k in xrange(2,N)]\\n    zeta_values = zeta_array(N, wp)\\n    for k in xrange(3, N):\\n        a = (-A[2]*A[k-1])>>wp\\n        for j in xrange(2,k):\\n            a += ((-1)**j * zeta_values[j] * A[k-j]) >> wp\\n        a //= (1-k)\\n        A[k] = a\\n    A = [a>>20 for a in A]\\n    A = A[::-1]\\n    A = A[:-1]\\n    gamma_taylor_cache[prec] = A\\n    #return A, prec\\n    return gamma_taylor_coefficients(inprec)\\n\\ndef gamma_fixed_taylor(xmpf, x, wp, prec, rnd, type):\\n    # Determine nearest multiple of N/2\\n    #n = int(x >> (wp-1))\\n    #steps = (n-1)>>1\\n    nearest_int = ((x >> (wp-1)) + MPZ_ONE) >> 1\\n    one = MPZ_ONE << wp\\n    coeffs, cwp = gamma_taylor_coefficients(wp)\\n    if nearest_int > 0:\\n        r = one\\n        for i in xrange(nearest_int-1):\\n            x -= one\\n            r = (r*x) >> wp\\n        x -= one\\n        p = MPZ_ZERO\\n        for c in coeffs:\\n            p = c + ((x*p)>>wp)\\n        p >>= (cwp-wp)\\n        if type == 0:\\n            return from_man_exp((r<<wp)//p, -wp, prec, rnd)\\n        if type == 2:\\n            return mpf_shift(from_rational(p, (r<<wp), prec, rnd), wp)\\n        if type == 3:\\n            return mpf_log(mpf_abs(from_man_exp((r<<wp)//p, -wp)), prec, rnd)\\n    else:\\n        r = one\\n        for i in xrange(-nearest_int):\\n            r = (r*x) >> wp\\n            x += one\\n        p = MPZ_ZERO\\n        for c in coeffs:\\n            p = c + ((x*p)>>wp)\\n        p >>= (cwp-wp)\\n        if wp - bitcount(abs(x)) > 10:\\n            # pass very close to 0, so do floating-point multiply\\n            g = mpf_add(xmpf, from_int(-nearest_int))  # exact\\n            r = from_man_exp(p*r,-wp-wp)\\n            r = mpf_mul(r, g, wp)\\n            if type == 0:\\n                return mpf_div(fone, r, prec, rnd)\\n            if type == 2:\\n                return mpf_pos(r, prec, rnd)\\n            if type == 3:\\n                return mpf_log(mpf_abs(mpf_div(fone, r, wp)), prec, rnd)\\n        else:\\n            r = from_man_exp(x*p*r,-3*wp)\\n            if type == 0: return mpf_div(fone, r, prec, rnd)\\n            if type == 2: return mpf_pos(r, prec, rnd)\\n            if type == 3: return mpf_neg(mpf_log(mpf_abs(r), prec, rnd))\\n\\ndef stirling_coefficient(n):\\n    if n in gamma_stirling_cache:\\n        return gamma_stirling_cache[n]\\n    p, q = bernfrac(n)\\n    q *= MPZ(n*(n-1))\\n    gamma_stirling_cache[n] = p, q, bitcount(abs(p)), bitcount(q)\\n    return gamma_stirling_cache[n]\\n\\ndef real_stirling_series(x, prec):\\n    \\\"\\\"\\\"\\n    Sums the rational part of Stirling's expansion,\\n\\n    log(sqrt(2*pi)) - z + 1/(12*z) - 1/(360*z^3) + ...\\n\\n    \\\"\\\"\\\"\\n    t = (MPZ_ONE<<(prec+prec)) // x   # t = 1/x\\n    u = (t*t)>>prec                  # u = 1/x**2\\n    s = ln_sqrt2pi_fixed(prec) - x\\n    # Add initial terms of Stirling's series\\n    s += t//12;            t = (t*u)>>prec\\n    s -= t//360;           t = (t*u)>>prec\\n    s += t//1260;          t = (t*u)>>prec\\n    s -= t//1680;          t = (t*u)>>prec\\n    if not t: return s\\n    s += t//1188;          t = (t*u)>>prec\\n    s -= 691*t//360360;    t = (t*u)>>prec\\n    s += t//156;           t = (t*u)>>prec\\n    if not t: return s\\n    s -= 3617*t//122400;   t = (t*u)>>prec\\n    s += 43867*t//244188;  t = (t*u)>>prec\\n    s -= 174611*t//125400;  t = (t*u)>>prec\\n    if not t: return s\\n    k = 22\\n    # From here on, the coefficients are growing, so we\\n    # have to keep t at a roughly constant size\\n    usize = bitcount(abs(u))\\n    tsize = bitcount(abs(t))\\n    texp = 0\\n    while 1:\\n        p, q, pb, qb = stirling_coefficient(k)\\n        term_mag = tsize + pb + texp\\n        shift = -texp\\n        m = pb - term_mag\\n        if m > 0 and shift < m:\\n            p >>= m\\n            shift -= m\\n        m = tsize - term_mag\\n        if m > 0 and shift < m:\\n            w = t >> m\\n            shift -= m\\n        else:\\n            w = t\\n        term = (t*p//q) >> shift\\n        if not term:\\n            break\\n        s += term\\n        t = (t*u) >> usize\\n        texp -= (prec - usize)\\n        k += 2\\n    return s\\n\\ndef complex_stirling_series(x, y, prec):\\n    # t = 1/z\\n    _m = (x*x + y*y) >> prec\\n    tre = (x << prec) // _m\\n    tim = (-y << prec) // _m\\n    # u = 1/z**2\\n    ure = (tre*tre - tim*tim) >> prec\\n    uim = tim*tre >> (prec-1)\\n    # s = log(sqrt(2*pi)) - z\\n    sre = ln_sqrt2pi_fixed(prec) - x\\n    sim = -y\\n\\n    # Add initial terms of Stirling's series\\n    sre += tre//12; sim += tim//12;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre -= tre//360; sim -= tim//360;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre += tre//1260; sim += tim//1260;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre -= tre//1680; sim -= tim//1680;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    if abs(tre) + abs(tim) < 5: return sre, sim\\n    sre += tre//1188; sim += tim//1188;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre -= 691*tre//360360; sim -= 691*tim//360360;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre += tre//156; sim += tim//156;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    if abs(tre) + abs(tim) < 5: return sre, sim\\n    sre -= 3617*tre//122400; sim -= 3617*tim//122400;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre += 43867*tre//244188; sim += 43867*tim//244188;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    sre -= 174611*tre//125400; sim -= 174611*tim//125400;\\n    tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)\\n    if abs(tre) + abs(tim) < 5: return sre, sim\\n\\n    k = 22\\n    # From here on, the coefficients are growing, so we\\n    # have to keep t at a roughly constant size\\n    usize = bitcount(max(abs(ure), abs(uim)))\\n    tsize = bitcount(max(abs(tre), abs(tim)))\\n    texp = 0\\n    while 1:\\n        p, q, pb, qb = stirling_coefficient(k)\\n        term_mag = tsize + pb + texp\\n        shift = -texp\\n        m = pb - term_mag\\n        if m > 0 and shift < m:\\n            p >>= m\\n            shift -= m\\n        m = tsize - term_mag\\n        if m > 0 and shift < m:\\n            wre = tre >> m\\n            wim = tim >> m\\n            shift -= m\\n        else:\\n            wre = tre\\n            wim = tim\\n        termre = (tre*p//q) >> shift\\n        termim = (tim*p//q) >> shift\\n        if abs(termre) + abs(termim) < 5:\\n            break\\n        sre += termre\\n        sim += termim\\n        tre, tim = ((tre*ure - tim*uim)>>usize), \\\\\\n            ((tre*uim + tim*ure)>>usize)\\n        texp -= (prec - usize)\\n        k += 2\\n    return sre, sim\\n\\n\\ndef mpf_gamma(x, prec, rnd='d', type=0):\\n    \\\"\\\"\\\"\\n    This function implements multipurpose evaluation of the gamma\\n    function, G(x), as well as the following versions of the same:\\n\\n    type = 0 -- G(x)                    [standard gamma function]\\n    type = 1 -- G(x+1) = x*G(x+1) = x!  [factorial]\\n    type = 2 -- 1/G(x)                  [reciprocal gamma function]\\n    type = 3 -- log(|G(x)|)             [log-gamma function, real part]\\n    \\\"\\\"\\\"\\n\\n    # Specal values\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero:\\n            if type == 1: return fone\\n            if type == 2: return fzero\\n            raise ValueError(\\\"gamma function pole\\\")\\n        if x == finf:\\n            if type == 2: return fzero\\n            return finf\\n        return fnan\\n\\n    # First of all, for log gamma, numbers can be well beyond the fixed-point\\n    # range, so we must take care of huge numbers before e.g. trying\\n    # to convert x to the nearest integer\\n    if type == 3:\\n        wp = prec+20\\n        if exp+bc > wp and not sign:\\n            return mpf_sub(mpf_mul(x, mpf_log(x, wp), wp), x, prec, rnd)\\n\\n    # We strongly want to special-case small integers\\n    is_integer = exp >= 0\\n    if is_integer:\\n        # Poles\\n        if sign:\\n            if type == 2:\\n                return fzero\\n            raise ValueError(\\\"gamma function pole\\\")\\n        # n = x\\n        n = man << exp\\n        if n < SMALL_FACTORIAL_CACHE_SIZE:\\n            if type == 0:\\n                return mpf_pos(small_factorial_cache[n-1], prec, rnd)\\n            if type == 1:\\n                return mpf_pos(small_factorial_cache[n], prec, rnd)\\n            if type == 2:\\n                return mpf_div(fone, small_factorial_cache[n-1], prec, rnd)\\n            if type == 3:\\n                return mpf_log(small_factorial_cache[n-1], prec, rnd)\\n    else:\\n        # floor(abs(x))\\n        n = int(man >> (-exp))\\n\\n    # Estimate size and precision\\n    # Estimate log(gamma(|x|),2) as x*log(x,2)\\n    mag = exp + bc\\n    gamma_size = n*mag\\n\\n    if type == 3:\\n        wp = prec + 20\\n    else:\\n        wp = prec + bitcount(gamma_size) + 20\\n\\n    # Very close to 0, pole\\n    if mag < -wp:\\n        if type == 0:\\n            return mpf_sub(mpf_div(fone,x, wp),mpf_shift(fone,-wp),prec,rnd)\\n        if type == 1: return mpf_sub(fone, x, prec, rnd)\\n        if type == 2: return mpf_add(x, mpf_shift(fone,mag-wp), prec, rnd)\\n        if type == 3: return mpf_neg(mpf_log(mpf_abs(x), prec, rnd))\\n\\n    # From now on, we assume having a gamma function\\n    if type == 1:\\n        return mpf_gamma(mpf_add(x, fone), prec, rnd, 0)\\n\\n    # Special case integers (those not small enough to be caught above,\\n    # but still small enough for an exact factorial to be faster\\n    # than an approximate algorithm), and half-integers\\n    if exp >= -1:\\n        if is_integer:\\n            if gamma_size < 10*wp:\\n                if type == 0:\\n                    return from_int(ifac(n-1), prec, rnd)\\n                if type == 2:\\n                    return from_rational(MPZ_ONE, ifac(n-1), prec, rnd)\\n                if type == 3:\\n                    return mpf_log(from_int(ifac(n-1)), prec, rnd)\\n        # half-integer\\n        if n < 100 or gamma_size < 10*wp:\\n            if sign:\\n                w = sqrtpi_fixed(wp)\\n                if n % 2: f = ifac2(2*n+1)\\n                else:     f = -ifac2(2*n+1)\\n                if type == 0:\\n                    return mpf_shift(from_rational(w, f, prec, rnd), -wp+n+1)\\n                if type == 2:\\n                    return mpf_shift(from_rational(f, w, prec, rnd), wp-n-1)\\n                if type == 3:\\n                    return mpf_log(mpf_shift(from_rational(w, abs(f),\\n                        prec, rnd), -wp+n+1), prec, rnd)\\n            elif n == 0:\\n                if type == 0: return mpf_sqrtpi(prec, rnd)\\n                if type == 2: return mpf_div(fone, mpf_sqrtpi(wp), prec, rnd)\\n                if type == 3: return mpf_log(mpf_sqrtpi(wp), prec, rnd)\\n            else:\\n                w = sqrtpi_fixed(wp)\\n                w = from_man_exp(w * ifac2(2*n-1), -wp-n)\\n                if type == 0: return mpf_pos(w, prec, rnd)\\n                if type == 2: return mpf_div(fone, w, prec, rnd)\\n                if type == 3: return mpf_log(mpf_abs(w), prec, rnd)\\n\\n    # Convert to fixed point\\n    offset = exp + wp\\n    if offset >= 0: absxman = man << offset\\n    else:           absxman = man >> (-offset)\\n\\n    # For log gamma, provide accurate evaluation for x = 1+eps and 2+eps\\n    if type == 3 and not sign:\\n        one = MPZ_ONE << wp\\n        one_dist = abs(absxman-one)\\n        two_dist = abs(absxman-2*one)\\n        cancellation = (wp - bitcount(min(one_dist, two_dist)))\\n        if cancellation > 10:\\n            xsub1 = mpf_sub(fone, x)\\n            xsub2 = mpf_sub(ftwo, x)\\n            xsub1mag = xsub1[2]+xsub1[3]\\n            xsub2mag = xsub2[2]+xsub2[3]\\n            if xsub1mag < -wp:\\n                return mpf_mul(mpf_euler(wp), mpf_sub(fone, x), prec, rnd)\\n            if xsub2mag < -wp:\\n                return mpf_mul(mpf_sub(fone, mpf_euler(wp)),\\n                    mpf_sub(x, ftwo), prec, rnd)\\n            # Proceed but increase precision\\n            wp += max(-xsub1mag, -xsub2mag)\\n            offset = exp + wp\\n            if offset >= 0: absxman = man << offset\\n            else:           absxman = man >> (-offset)\\n\\n    # Use Taylor series if appropriate\\n    n_for_stirling = int(GAMMA_STIRLING_BETA*wp)\\n    if n < max(100, n_for_stirling) and wp < MAX_GAMMA_TAYLOR_PREC:\\n        if sign:\\n            absxman = -absxman\\n        return gamma_fixed_taylor(x, absxman, wp, prec, rnd, type)\\n\\n    # Use Stirling's series\\n    # First ensure that |x| is large enough for rapid convergence\\n    xorig = x\\n\\n    # Argument reduction\\n    r = 0\\n    if n < n_for_stirling:\\n        r = one = MPZ_ONE << wp\\n        d = n_for_stirling - n\\n        for k in xrange(d):\\n            r = (r * absxman) >> wp\\n            absxman += one\\n        x = xabs = from_man_exp(absxman, -wp)\\n        if sign:\\n            x = mpf_neg(x)\\n    else:\\n        xabs = mpf_abs(x)\\n\\n    # Asymptotic series\\n    y = real_stirling_series(absxman, wp)\\n    u = to_fixed(mpf_log(xabs, wp), wp)\\n    u = ((absxman - (MPZ_ONE<<(wp-1))) * u) >> wp\\n    y += u\\n    w = from_man_exp(y, -wp)\\n\\n    # Compute final value\\n    if sign:\\n        # Reflection formula\\n        A = mpf_mul(mpf_sin_pi(xorig, wp), xorig, wp)\\n        B = mpf_neg(mpf_pi(wp))\\n        if type == 0 or type == 2:\\n            A = mpf_mul(A, mpf_exp(w, wp))\\n            if r:\\n                B = mpf_mul(B, from_man_exp(r, -wp), wp)\\n            if type == 0:\\n                return mpf_div(B, A, prec, rnd)\\n            if type == 2:\\n                return mpf_div(A, B, prec, rnd)\\n        if type == 3:\\n            if r:\\n                B = mpf_mul(B, from_man_exp(r, -wp), wp)\\n            A = mpf_add(mpf_log(mpf_abs(A), wp), w, wp)\\n            return mpf_sub(mpf_log(mpf_abs(B), wp), A, prec, rnd)\\n    else:\\n        if type == 0:\\n            if r:\\n                return mpf_div(mpf_exp(w, wp),\\n                    from_man_exp(r, -wp), prec, rnd)\\n            return mpf_exp(w, prec, rnd)\\n        if type == 2:\\n            if r:\\n                return mpf_div(from_man_exp(r, -wp),\\n                    mpf_exp(w, wp), prec, rnd)\\n            return mpf_exp(mpf_neg(w), prec, rnd)\\n        if type == 3:\\n            if r:\\n                return mpf_sub(w, mpf_log(from_man_exp(r,-wp), wp), prec, rnd)\\n            return mpf_pos(w, prec, rnd)\\n\\n\\ndef mpc_gamma(z, prec, rnd='d', type=0):\\n    a, b = z\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n\\n    if b == fzero:\\n        # Imaginary part on negative half-axis for log-gamma function\\n        if type == 3 and asign:\\n            re = mpf_gamma(a, prec, rnd, 3)\\n            n = (-aman) >> (-aexp)\\n            im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd)\\n            return re, im\\n        return mpf_gamma(a, prec, rnd, type), fzero\\n\\n    # Some kind of complex inf/nan\\n    if (not aman and aexp) or (not bman and bexp):\\n        return (fnan, fnan)\\n\\n    # Initial working precision\\n    wp = prec + 20\\n\\n    amag = aexp+abc\\n    bmag = bexp+bbc\\n    if aman:\\n        mag = max(amag, bmag)\\n    else:\\n        mag = bmag\\n\\n    # Close to 0\\n    if mag < -8:\\n        if mag < -wp:\\n            # 1/gamma(z) = z + euler*z^2 + O(z^3)\\n            v = mpc_add(z, mpc_mul_mpf(mpc_mul(z,z,wp),mpf_euler(wp),wp), wp)\\n            if type == 0: return mpc_reciprocal(v, prec, rnd)\\n            if type == 1: return mpc_div(z, v, prec, rnd)\\n            if type == 2: return mpc_pos(v, prec, rnd)\\n            if type == 3: return mpc_log(mpc_reciprocal(v, prec), prec, rnd)\\n        elif type != 1:\\n            wp += (-mag)\\n\\n    # Handle huge log-gamma values; must do this before converting to\\n    # a fixed-point value. TODO: determine a precise cutoff of validity\\n    # depending on amag and bmag\\n    if type == 3 and mag > wp and ((not asign) or (bmag >= amag)):\\n        return mpc_sub(mpc_mul(z, mpc_log(z, wp), wp), z, prec, rnd)\\n\\n    # From now on, we assume having a gamma function\\n    if type == 1:\\n        return mpc_gamma((mpf_add(a, fone), b), prec, rnd, 0)\\n\\n    an = abs(to_int(a))\\n    bn = abs(to_int(b))\\n    absn = max(an, bn)\\n    gamma_size = absn*mag\\n    if type == 3:\\n        pass\\n    else:\\n        wp += bitcount(gamma_size)\\n\\n    # Reflect to the right half-plane. Note that Stirling's expansion\\n    # is valid in the left half-plane too, as long as we're not too close\\n    # to the real axis, but in order to use this argument reduction\\n    # in the negative direction must be implemented.\\n    #need_reflection = asign and ((bmag < 0) or (amag-bmag > 4))\\n    need_reflection = asign\\n    zorig = z\\n    if need_reflection:\\n        z = mpc_neg(z)\\n        asign, aman, aexp, abc = a = z[0]\\n        bsign, bman, bexp, bbc = b = z[1]\\n\\n    # Imaginary part very small compared to real one?\\n    yfinal = 0\\n    balance_prec = 0\\n    if bmag < -10:\\n        # Check z ~= 1 and z ~= 2 for loggamma\\n        if type == 3:\\n            zsub1 = mpc_sub_mpf(z, fone)\\n            if zsub1[0] == fzero:\\n                cancel1 = -bmag\\n            else:\\n                cancel1 = -max(zsub1[0][2]+zsub1[0][3], bmag)\\n            if cancel1 > wp:\\n                pi = mpf_pi(wp)\\n                x = mpc_mul_mpf(zsub1, pi, wp)\\n                x = mpc_mul(x, x, wp)\\n                x = mpc_div_mpf(x, from_int(12), wp)\\n                y = mpc_mul_mpf(zsub1, mpf_neg(mpf_euler(wp)), wp)\\n                yfinal = mpc_add(x, y, wp)\\n                if not need_reflection:\\n                    return mpc_pos(yfinal, prec, rnd)\\n            elif cancel1 > 0:\\n                wp += cancel1\\n            zsub2 = mpc_sub_mpf(z, ftwo)\\n            if zsub2[0] == fzero:\\n                cancel2 = -bmag\\n            else:\\n                cancel2 = -max(zsub2[0][2]+zsub2[0][3], bmag)\\n            if cancel2 > wp:\\n                pi = mpf_pi(wp)\\n                t = mpf_sub(mpf_mul(pi, pi), from_int(6))\\n                x = mpc_mul_mpf(mpc_mul(zsub2, zsub2, wp), t, wp)\\n                x = mpc_div_mpf(x, from_int(12), wp)\\n                y = mpc_mul_mpf(zsub2, mpf_sub(fone, mpf_euler(wp)), wp)\\n                yfinal = mpc_add(x, y, wp)\\n                if not need_reflection:\\n                    return mpc_pos(yfinal, prec, rnd)\\n            elif cancel2 > 0:\\n                wp += cancel2\\n        if bmag < -wp:\\n            # Compute directly from the real gamma function.\\n            pp = 2*(wp+10)\\n            aabs = mpf_abs(a)\\n            eps = mpf_shift(fone, amag-wp)\\n            x1 = mpf_gamma(aabs, pp, type=type)\\n            x2 = mpf_gamma(mpf_add(aabs, eps), pp, type=type)\\n            xprime = mpf_div(mpf_sub(x2, x1, pp), eps, pp)\\n            y = mpf_mul(b, xprime, prec, rnd)\\n            yfinal = (x1, y)\\n            # Note: we still need to use the reflection formula for\\n            # near-poles, and the correct branch of the log-gamma function\\n            if not need_reflection:\\n                return mpc_pos(yfinal, prec, rnd)\\n        else:\\n            balance_prec += (-bmag)\\n\\n    wp += balance_prec\\n    n_for_stirling = int(GAMMA_STIRLING_BETA*wp)\\n    need_reduction = absn < n_for_stirling\\n\\n    afix = to_fixed(a, wp)\\n    bfix = to_fixed(b, wp)\\n\\n    r = 0\\n    if not yfinal:\\n        zprered = z\\n        # Argument reduction\\n        if absn < n_for_stirling:\\n            absn = complex(an, bn)\\n            d = int((1 + n_for_stirling**2 - bn**2)**0.5 - an)\\n            rre = one = MPZ_ONE << wp\\n            rim = MPZ_ZERO\\n            for k in xrange(d):\\n                rre, rim = ((afix*rre-bfix*rim)>>wp), ((afix*rim + bfix*rre)>>wp)\\n                afix += one\\n            r = from_man_exp(rre, -wp), from_man_exp(rim, -wp)\\n            a = from_man_exp(afix, -wp)\\n            z = a, b\\n\\n        yre, yim = complex_stirling_series(afix, bfix, wp)\\n        # (z-1/2)*log(z) + S\\n        lre, lim = mpc_log(z, wp)\\n        lre = to_fixed(lre, wp)\\n        lim = to_fixed(lim, wp)\\n        yre = ((lre*afix - lim*bfix)>>wp) - (lre>>1) + yre\\n        yim = ((lre*bfix + lim*afix)>>wp) - (lim>>1) + yim\\n        y = from_man_exp(yre, -wp), from_man_exp(yim, -wp)\\n\\n        if r and type == 3:\\n            # If re(z) > 0 and abs(z) <= 4, the branches of loggamma(z)\\n            # and log(gamma(z)) coincide. Otherwise, use the zeroth order\\n            # Stirling expansion to compute the correct imaginary part.\\n            y = mpc_sub(y, mpc_log(r, wp), wp)\\n            zfa = to_float(zprered[0])\\n            zfb = to_float(zprered[1])\\n            zfabs = math.hypot(zfa,zfb)\\n            #if not (zfa > 0.0 and zfabs <= 4):\\n            yfb = to_float(y[1])\\n            u = math.atan2(zfb, zfa)\\n            if zfabs <= 0.5:\\n                gi = 0.577216*zfb - u\\n            else:\\n                gi = -zfb - 0.5*u + zfa*u + zfb*math.log(zfabs)\\n            n = int(math.floor((gi-yfb)/(2*math.pi)+0.5))\\n            y = (y[0], mpf_add(y[1], mpf_mul_int(mpf_pi(wp), 2*n, wp), wp))\\n\\n    if need_reflection:\\n        if type == 0 or type == 2:\\n            A = mpc_mul(mpc_sin_pi(zorig, wp), zorig, wp)\\n            B = (mpf_neg(mpf_pi(wp)), fzero)\\n            if yfinal:\\n                if type == 2:\\n                    A = mpc_div(A, yfinal, wp)\\n                else:\\n                    A = mpc_mul(A, yfinal, wp)\\n            else:\\n                A = mpc_mul(A, mpc_exp(y, wp), wp)\\n            if r:\\n                B = mpc_mul(B, r, wp)\\n            if type == 0: return mpc_div(B, A, prec, rnd)\\n            if type == 2: return mpc_div(A, B, prec, rnd)\\n\\n        # Reflection formula for the log-gamma function with correct branch\\n        # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0006/\\n        # LogGamma[z] == -LogGamma[-z] - Log[-z] +\\n        # Sign[Im[z]] Floor[Re[z]] Pi I + Log[Pi] -\\n        #      Log[Sin[Pi (z - Floor[Re[z]])]] -\\n        # Pi I (1 - Abs[Sign[Im[z]]]) Abs[Floor[Re[z]]]\\n        if type == 3:\\n            if yfinal:\\n                s1 = mpc_neg(yfinal)\\n            else:\\n                s1 = mpc_neg(y)\\n            # s -= log(-z)\\n            s1 = mpc_sub(s1, mpc_log(mpc_neg(zorig), wp), wp)\\n            # floor(re(z))\\n            rezfloor = mpf_floor(zorig[0])\\n            imzsign = mpf_sign(zorig[1])\\n            pi = mpf_pi(wp)\\n            t = mpf_mul(pi, rezfloor)\\n            t = mpf_mul_int(t, imzsign, wp)\\n            s1 = (s1[0], mpf_add(s1[1], t, wp))\\n            s1 = mpc_add_mpf(s1, mpf_log(pi, wp), wp)\\n            t = mpc_sin_pi(mpc_sub_mpf(zorig, rezfloor), wp)\\n            t = mpc_log(t, wp)\\n            s1 = mpc_sub(s1, t, wp)\\n            # Note: may actually be unused, because we fall back\\n            # to the mpf_ function for real arguments\\n            if not imzsign:\\n                t = mpf_mul(pi, mpf_floor(rezfloor), wp)\\n                s1 = (s1[0], mpf_sub(s1[1], t, wp))\\n            return mpc_pos(s1, prec, rnd)\\n    else:\\n        if type == 0:\\n            if r:\\n                return mpc_div(mpc_exp(y, wp), r, prec, rnd)\\n            return mpc_exp(y, prec, rnd)\\n        if type == 2:\\n            if r:\\n                return mpc_div(r, mpc_exp(y, wp), prec, rnd)\\n            return mpc_exp(mpc_neg(y), prec, rnd)\\n        if type == 3:\\n            return mpc_pos(y, prec, rnd)\\n\\ndef mpf_factorial(x, prec, rnd='d'):\\n    return mpf_gamma(x, prec, rnd, 1)\\n\\ndef mpc_factorial(x, prec, rnd='d'):\\n    return mpc_gamma(x, prec, rnd, 1)\\n\\ndef mpf_rgamma(x, prec, rnd='d'):\\n    return mpf_gamma(x, prec, rnd, 2)\\n\\ndef mpc_rgamma(x, prec, rnd='d'):\\n    return mpc_gamma(x, prec, rnd, 2)\\n\\ndef mpf_loggamma(x, prec, rnd='d'):\\n    sign, man, exp, bc = x\\n    if sign:\\n        raise ComplexResult\\n    return mpf_gamma(x, prec, rnd, 3)\\n\\ndef mpc_loggamma(z, prec, rnd='d'):\\n    a, b = z\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n    if b == fzero and asign:\\n        re = mpf_gamma(a, prec, rnd, 3)\\n        n = (-aman) >> (-aexp)\\n        im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd)\\n        return re, im\\n    return mpc_gamma(z, prec, rnd, 3)\\n\\ndef mpf_gamma_int(n, prec, rnd=round_fast):\\n    if n < SMALL_FACTORIAL_CACHE_SIZE:\\n        return mpf_pos(small_factorial_cache[n-1], prec, rnd)\\n    return mpf_gamma(from_int(n), prec, rnd)\\n\\n\\n\\\"\\\"\\\"\\nThis module implements computation of elementary transcendental\\nfunctions (powers, logarithms, trigonometric and hyperbolic\\nfunctions, inverse trigonometric and hyperbolic) for real\\nfloating-point numbers.\\n\\nFor complex and interval implementations of the same functions,\\nsee libmpc and libmpi.\\n\\n\\\"\\\"\\\"\\n\\nimport math\\nfrom bisect import bisect\\n\\nfrom .backend import xrange\\nfrom .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE, BACKEND\\n\\nfrom .libmpf import (\\n    round_floor, round_ceiling, round_down, round_up,\\n    round_nearest, round_fast,\\n    ComplexResult,\\n    bitcount, bctable, lshift, rshift, giant_steps, sqrt_fixed,\\n    from_int, to_int, from_man_exp, to_fixed, to_float, from_float,\\n    from_rational, normalize,\\n    fzero, fone, fnone, fhalf, finf, fninf, fnan,\\n    mpf_cmp, mpf_sign, mpf_abs,\\n    mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_div, mpf_shift,\\n    mpf_rdiv_int, mpf_pow_int, mpf_sqrt,\\n    reciprocal_rnd, negative_rnd, mpf_perturb,\\n    isqrt_fast\\n)\\n\\nfrom .libintmath import ifib\\n\\n\\n#-------------------------------------------------------------------------------\\n# Tuning parameters\\n#-------------------------------------------------------------------------------\\n\\n# Cutoff for computing exp from cosh+sinh. This reduces the\\n# number of terms by half, but also requires a square root which\\n# is expensive with the pure-Python square root code.\\nif BACKEND == 'python':\\n    EXP_COSH_CUTOFF = 600\\nelse:\\n    EXP_COSH_CUTOFF = 400\\n# Cutoff for using more than 2 series\\nEXP_SERIES_U_CUTOFF = 1500\\n\\n# Also basically determined by sqrt\\nif BACKEND == 'python':\\n    COS_SIN_CACHE_PREC = 400\\nelse:\\n    COS_SIN_CACHE_PREC = 200\\nCOS_SIN_CACHE_STEP = 8\\ncos_sin_cache = {}\\n\\n# Number of integer logarithms to cache (for zeta sums)\\nMAX_LOG_INT_CACHE = 2000\\nlog_int_cache = {}\\n\\nLOG_TAYLOR_PREC = 2500  # Use Taylor series with caching up to this prec\\nLOG_TAYLOR_SHIFT = 9    # Cache log values in steps of size 2^-N\\nlog_taylor_cache = {}\\n# prec/size ratio of x for fastest convergence in AGM formula\\nLOG_AGM_MAG_PREC_RATIO = 20\\n\\nATAN_TAYLOR_PREC = 3000  # Same as for log\\nATAN_TAYLOR_SHIFT = 7   # steps of size 2^-N\\natan_taylor_cache = {}\\n\\n\\n# ~= next power of two + 20\\ncache_prec_steps = [22,22]\\nfor k in xrange(1, bitcount(LOG_TAYLOR_PREC)+1):\\n    cache_prec_steps += [min(2**k,LOG_TAYLOR_PREC)+20] * 2**(k-1)\\n\\n\\n#----------------------------------------------------------------------------#\\n#                                                                            #\\n#                   Elementary mathematical constants                        #\\n#                                                                            #\\n#----------------------------------------------------------------------------#\\n\\ndef constant_memo(f):\\n    \\\"\\\"\\\"\\n    Decorator for caching computed values of mathematical\\n    constants. This decorator should be applied to a\\n    function taking a single argument prec as input and\\n    returning a fixed-point value with the given precision.\\n    \\\"\\\"\\\"\\n    f.memo_prec = -1\\n    f.memo_val = None\\n    def g(prec, **kwargs):\\n        memo_prec = f.memo_prec\\n        if prec <= memo_prec:\\n            return f.memo_val >> (memo_prec-prec)\\n        newprec = int(prec*1.05+10)\\n        f.memo_val = f(newprec, **kwargs)\\n        f.memo_prec = newprec\\n        return f.memo_val >> (newprec-prec)\\n    g.__name__ = f.__name__\\n    g.__doc__ = f.__doc__\\n    return g\\n\\ndef def_mpf_constant(fixed):\\n    \\\"\\\"\\\"\\n    Create a function that computes the mpf value for a mathematical\\n    constant, given a function that computes the fixed-point value.\\n\\n    Assumptions: the constant is positive and has magnitude ~= 1;\\n    the fixed-point function rounds to floor.\\n    \\\"\\\"\\\"\\n    def f(prec, rnd=round_fast):\\n        wp = prec + 20\\n        v = fixed(wp)\\n        if rnd in (round_up, round_ceiling):\\n            v += 1\\n        return normalize(0, v, -wp, bitcount(v), prec, rnd)\\n    f.__doc__ = fixed.__doc__\\n    return f\\n\\ndef bsp_acot(q, a, b, hyperbolic):\\n    if b - a == 1:\\n        a1 = MPZ(2*a + 3)\\n        if hyperbolic or a&1:\\n            return MPZ_ONE, a1 * q**2, a1\\n        else:\\n            return -MPZ_ONE, a1 * q**2, a1\\n    m = (a+b)//2\\n    p1, q1, r1 = bsp_acot(q, a, m, hyperbolic)\\n    p2, q2, r2 = bsp_acot(q, m, b, hyperbolic)\\n    return q2*p1 + r1*p2, q1*q2, r1*r2\\n\\n# the acoth(x) series converges like the geometric series for x^2\\n# N = ceil(p*log(2)/(2*log(x)))\\ndef acot_fixed(a, prec, hyperbolic):\\n    \\\"\\\"\\\"\\n    Compute acot(a) or acoth(a) for an integer a with binary splitting; see\\n    http://numbers.computation.free.fr/Constants/Algorithms/splitting.html\\n    \\\"\\\"\\\"\\n    N = int(0.35 * prec/math.log(a) + 20)\\n    p, q, r = bsp_acot(a, 0,N, hyperbolic)\\n    return ((p+q)<<prec)//(q*a)\\n\\ndef machin(coefs, prec, hyperbolic=False):\\n    \\\"\\\"\\\"\\n    Evaluate a Machin-like formula, i.e., a linear combination of\\n    acot(n) or acoth(n) for specific integer values of n, using fixed-\\n    point arithmetic. The input should be a list [(c, n), ...], giving\\n    c*acot[h](n) + ...\\n    \\\"\\\"\\\"\\n    extraprec = 10\\n    s = MPZ_ZERO\\n    for a, b in coefs:\\n        s += MPZ(a) * acot_fixed(MPZ(b), prec+extraprec, hyperbolic)\\n    return (s >> extraprec)\\n\\n# Logarithms of integers are needed for various computations involving\\n# logarithms, powers, radix conversion, etc\\n\\n@constant_memo\\ndef ln2_fixed(prec):\\n    \\\"\\\"\\\"\\n    Computes ln(2). This is done with a hyperbolic Machin-type formula,\\n    with binary splitting at high precision.\\n    \\\"\\\"\\\"\\n    return machin([(18, 26), (-2, 4801), (8, 8749)], prec, True)\\n\\n@constant_memo\\ndef ln10_fixed(prec):\\n    \\\"\\\"\\\"\\n    Computes ln(10). This is done with a hyperbolic Machin-type formula.\\n    \\\"\\\"\\\"\\n    return machin([(46, 31), (34, 49), (20, 161)], prec, True)\\n\\n\\nr\\\"\\\"\\\"\\nFor computation of pi, we use the Chudnovsky series:\\n\\n             oo\\n             ___        k\\n      1     \\\\       (-1)  (6 k)! (A + B k)\\n    ----- =  )     -----------------------\\n    12 pi   /___               3  3k+3/2\\n                    (3 k)! (k!)  C\\n            k = 0\\n\\nwhere A, B, and C are certain integer constants. This series adds roughly\\n14 digits per term. Note that C^(3/2) can be extracted so that the\\nseries contains only rational terms. This makes binary splitting very\\nefficient.\\n\\nThe recurrence formulas for the binary splitting were taken from\\nftp://ftp.gmplib.org/pub/src/gmp-chudnovsky.c\\n\\nPreviously, Machin's formula was used at low precision and the AGM iteration\\nwas used at high precision. However, the Chudnovsky series is essentially as\\nfast as the Machin formula at low precision and in practice about 3x faster\\nthan the AGM at high precision (despite theoretically having a worse\\nasymptotic complexity), so there is no reason not to use it in all cases.\\n\\n\\\"\\\"\\\"\\n\\n# Constants in Chudnovsky's series\\nCHUD_A = MPZ(13591409)\\nCHUD_B = MPZ(545140134)\\nCHUD_C = MPZ(640320)\\nCHUD_D = MPZ(12)\\n\\ndef bs_chudnovsky(a, b, level, verbose):\\n    \\\"\\\"\\\"\\n    Computes the sum from a to b of the series in the Chudnovsky\\n    formula. Returns g, p, q where p/q is the sum as an exact\\n    fraction and g is a temporary value used to save work\\n    for recursive calls.\\n    \\\"\\\"\\\"\\n    if b-a == 1:\\n        g = MPZ((6*b-5)*(2*b-1)*(6*b-1))\\n        p = b**3 * CHUD_C**3 // 24\\n        q = (-1)**b * g * (CHUD_A+CHUD_B*b)\\n    else:\\n        if verbose and level < 4:\\n            print(\\\"  binary splitting\\\", a, b)\\n        mid = (a+b)//2\\n        g1, p1, q1 = bs_chudnovsky(a, mid, level+1, verbose)\\n        g2, p2, q2 = bs_chudnovsky(mid, b, level+1, verbose)\\n        p = p1*p2\\n        g = g1*g2\\n        q = q1*p2 + q2*g1\\n    return g, p, q\\n\\n@constant_memo\\ndef pi_fixed(prec, verbose=False, verbose_base=None):\\n    \\\"\\\"\\\"\\n    Compute floor(pi * 2**prec) as a big integer.\\n\\n    This is done using Chudnovsky's series (see comments in\\n    libelefun.py for details).\\n    \\\"\\\"\\\"\\n    # The Chudnovsky series gives 14.18 digits per term\\n    N = int(prec/3.3219280948/14.181647462 + 2)\\n    if verbose:\\n        print(\\\"binary splitting with N =\\\", N)\\n    g, p, q = bs_chudnovsky(0, N, 0, verbose)\\n    sqrtC = isqrt_fast(CHUD_C<<(2*prec))\\n    v = p*CHUD_C*sqrtC//((q+CHUD_A*p)*CHUD_D)\\n    return v\\n\\ndef degree_fixed(prec):\\n    return pi_fixed(prec)//180\\n\\ndef bspe(a, b):\\n    \\\"\\\"\\\"\\n    Sum series for exp(1)-1 between a, b, returning the result\\n    as an exact fraction (p, q).\\n    \\\"\\\"\\\"\\n    if b-a == 1:\\n        return MPZ_ONE, MPZ(b)\\n    m = (a+b)//2\\n    p1, q1 = bspe(a, m)\\n    p2, q2 = bspe(m, b)\\n    return p1*q2+p2, q1*q2\\n\\n@constant_memo\\ndef e_fixed(prec):\\n    \\\"\\\"\\\"\\n    Computes exp(1). This is done using the ordinary Taylor series for\\n    exp, with binary splitting. For a description of the algorithm,\\n    see:\\n\\n        http://numbers.computation.free.fr/Constants/\\n            Algorithms/splitting.html\\n    \\\"\\\"\\\"\\n    # Slight overestimate of N needed for 1/N! < 2**(-prec)\\n    # This could be tightened for large N.\\n    N = int(1.1*prec/math.log(prec) + 20)\\n    p, q = bspe(0,N)\\n    return ((p+q)<<prec)//q\\n\\n@constant_memo\\ndef phi_fixed(prec):\\n    \\\"\\\"\\\"\\n    Computes the golden ratio, (1+sqrt(5))/2\\n    \\\"\\\"\\\"\\n    prec += 10\\n    a = isqrt_fast(MPZ_FIVE<<(2*prec)) + (MPZ_ONE << prec)\\n    return a >> 11\\n\\nmpf_phi    = def_mpf_constant(phi_fixed)\\nmpf_pi     = def_mpf_constant(pi_fixed)\\nmpf_e      = def_mpf_constant(e_fixed)\\nmpf_degree = def_mpf_constant(degree_fixed)\\nmpf_ln2    = def_mpf_constant(ln2_fixed)\\nmpf_ln10   = def_mpf_constant(ln10_fixed)\\n\\n\\n@constant_memo\\ndef ln_sqrt2pi_fixed(prec):\\n    wp = prec + 10\\n    # ln(sqrt(2*pi)) = ln(2*pi)/2\\n    return to_fixed(mpf_log(mpf_shift(mpf_pi(wp), 1), wp), prec-1)\\n\\n@constant_memo\\ndef sqrtpi_fixed(prec):\\n    return sqrt_fixed(pi_fixed(prec), prec)\\n\\nmpf_sqrtpi   = def_mpf_constant(sqrtpi_fixed)\\nmpf_ln_sqrt2pi   = def_mpf_constant(ln_sqrt2pi_fixed)\\n\\n\\n#----------------------------------------------------------------------------#\\n#                                                                            #\\n#                                    Powers                                  #\\n#                                                                            #\\n#----------------------------------------------------------------------------#\\n\\ndef mpf_pow(s, t, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Compute s**t. Raises ComplexResult if s is negative and t is\\n    fractional.\\n    \\\"\\\"\\\"\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    if ssign and texp < 0:\\n        raise ComplexResult(\\\"negative number raised to a fractional power\\\")\\n    if texp >= 0:\\n        return mpf_pow_int(s, (-1)**tsign * (tman<<texp), prec, rnd)\\n    # s**(n/2) = sqrt(s)**n\\n    if texp == -1:\\n        if tman == 1:\\n            if tsign:\\n                return mpf_div(fone, mpf_sqrt(s, prec+10,\\n                    reciprocal_rnd[rnd]), prec, rnd)\\n            return mpf_sqrt(s, prec, rnd)\\n        else:\\n            if tsign:\\n                return mpf_pow_int(mpf_sqrt(s, prec+10,\\n                    reciprocal_rnd[rnd]), -tman, prec, rnd)\\n            return mpf_pow_int(mpf_sqrt(s, prec+10, rnd), tman, prec, rnd)\\n    # General formula: s**t = exp(t*log(s))\\n    # TODO: handle rnd direction of the logarithm carefully\\n    c = mpf_log(s, prec+10, rnd)\\n    return mpf_exp(mpf_mul(t, c), prec, rnd)\\n\\ndef int_pow_fixed(y, n, prec):\\n    \\\"\\\"\\\"n-th power of a fixed point number with precision prec\\n\\n       Returns the power in the form man, exp,\\n       man * 2**exp ~= y**n\\n    \\\"\\\"\\\"\\n    if n == 2:\\n        return (y*y), 0\\n    bc = bitcount(y)\\n    exp = 0\\n    workprec = 2 * (prec + 4*bitcount(n) + 4)\\n    _, pm, pe, pbc = fone\\n    while 1:\\n        if n & 1:\\n            pm = pm*y\\n            pe = pe+exp\\n            pbc += bc - 2\\n            pbc = pbc + bctable[int(pm >> pbc)]\\n            if pbc > workprec:\\n                pm = pm >> (pbc-workprec)\\n                pe += pbc - workprec\\n                pbc = workprec\\n            n -= 1\\n            if not n:\\n                break\\n        y = y*y\\n        exp = exp+exp\\n        bc = bc + bc - 2\\n        bc = bc + bctable[int(y >> bc)]\\n        if bc > workprec:\\n            y = y >> (bc-workprec)\\n            exp += bc - workprec\\n            bc = workprec\\n        n = n // 2\\n    return pm, pe\\n\\n# froot(s, n, prec, rnd) computes the real n-th root of a\\n# positive mpf tuple s.\\n# To compute the root we start from a 50-bit estimate for r\\n# generated with ordinary floating-point arithmetic, and then refine\\n# the value to full accuracy using the iteration\\n\\n#            1  /                     y       \\\\\\n#   r     = --- | (n-1)  * r   +  ----------  |\\n#    n+1     n  \\\\           n     r_n**(n-1)  /\\n\\n# which is simply Newton's method applied to the equation r**n = y.\\n# With giant_steps(start, prec+extra) = [p0,...,pm, prec+extra]\\n# and y = man * 2**-shift  one has\\n# (man * 2**exp)**(1/n) =\\n# y**(1/n) * 2**(start-prec/n) * 2**(p0-start) * ... * 2**(prec+extra-pm) *\\n# 2**((exp+shift-(n-1)*prec)/n -extra))\\n# The last factor is accounted for in the last line of froot.\\n\\ndef nthroot_fixed(y, n, prec, exp1):\\n    start = 50\\n    try:\\n        y1 = rshift(y, prec - n*start)\\n        r = MPZ(int(y1**(1.0/n)))\\n    except OverflowError:\\n        y1 = from_int(y1, start)\\n        fn = from_int(n)\\n        fn = mpf_rdiv_int(1, fn, start)\\n        r = mpf_pow(y1, fn, start)\\n        r = to_int(r)\\n    extra = 10\\n    extra1 = n\\n    prevp = start\\n    for p in giant_steps(start, prec+extra):\\n        pm, pe = int_pow_fixed(r, n-1, prevp)\\n        r2 = rshift(pm, (n-1)*prevp - p - pe - extra1)\\n        B = lshift(y, 2*p-prec+extra1)//r2\\n        r = (B + (n-1) * lshift(r, p-prevp))//n\\n        prevp = p\\n    return r\\n\\ndef mpf_nthroot(s, n, prec, rnd=round_fast):\\n    \\\"\\\"\\\"nth-root of a positive number\\n\\n    Use the Newton method when faster, otherwise use x**(1/n)\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if sign:\\n        raise ComplexResult(\\\"nth root of a negative number\\\")\\n    if not man:\\n        if s == fnan:\\n            return fnan\\n        if s == fzero:\\n            if n > 0:\\n                return fzero\\n            if n == 0:\\n                return fone\\n            return finf\\n        # Infinity\\n        if not n:\\n            return fnan\\n        if n < 0:\\n            return fzero\\n        return finf\\n    flag_inverse = False\\n    if n < 2:\\n        if n == 0:\\n            return fone\\n        if n == 1:\\n            return mpf_pos(s, prec, rnd)\\n        if n == -1:\\n            return mpf_div(fone, s, prec, rnd)\\n        # n < 0\\n        rnd = reciprocal_rnd[rnd]\\n        flag_inverse = True\\n        extra_inverse = 5\\n        prec += extra_inverse\\n        n = -n\\n    if n > 20 and (n >= 20000 or prec < int(233 + 28.3 * n**0.62)):\\n        prec2 = prec + 10\\n        fn = from_int(n)\\n        nth = mpf_rdiv_int(1, fn, prec2)\\n        r = mpf_pow(s, nth, prec2, rnd)\\n        s = normalize(r[0], r[1], r[2], r[3], prec, rnd)\\n        if flag_inverse:\\n            return mpf_div(fone, s, prec-extra_inverse, rnd)\\n        else:\\n            return s\\n    # Convert to a fixed-point number with prec2 bits.\\n    prec2 = prec + 2*n - (prec%n)\\n    # a few tests indicate that\\n    # for 10 < n < 10**4 a bit more precision is needed\\n    if n > 10:\\n        prec2 += prec2//10\\n        prec2 = prec2 - prec2%n\\n    # Mantissa may have more bits than we need. Trim it down.\\n    shift = bc - prec2\\n    # Adjust exponents to make prec2 and exp+shift multiples of n.\\n    sign1 = 0\\n    es = exp+shift\\n    if es < 0:\\n        sign1 = 1\\n        es = -es\\n    if sign1:\\n        shift += es%n\\n    else:\\n        shift -= es%n\\n    man = rshift(man, shift)\\n    extra = 10\\n    exp1 = ((exp+shift-(n-1)*prec2)//n) - extra\\n    rnd_shift = 0\\n    if flag_inverse:\\n        if rnd == 'u' or rnd == 'c':\\n            rnd_shift = 1\\n    else:\\n        if rnd == 'd' or rnd == 'f':\\n            rnd_shift = 1\\n    man = nthroot_fixed(man+rnd_shift, n, prec2, exp1)\\n    s = from_man_exp(man, exp1, prec, rnd)\\n    if flag_inverse:\\n        return mpf_div(fone, s, prec-extra_inverse, rnd)\\n    else:\\n        return s\\n\\ndef mpf_cbrt(s, prec, rnd=round_fast):\\n    \\\"\\\"\\\"cubic root of a positive number\\\"\\\"\\\"\\n    return mpf_nthroot(s, 3, prec, rnd)\\n\\n#----------------------------------------------------------------------------#\\n#                                                                            #\\n#                                Logarithms                                  #\\n#                                                                            #\\n#----------------------------------------------------------------------------#\\n\\n\\ndef log_int_fixed(n, prec, ln2=None):\\n    \\\"\\\"\\\"\\n    Fast computation of log(n), caching the value for small n,\\n    intended for zeta sums.\\n    \\\"\\\"\\\"\\n    if n in log_int_cache:\\n        value, vprec = log_int_cache[n]\\n        if vprec >= prec:\\n            return value >> (vprec - prec)\\n    wp = prec + 10\\n    if wp <= LOG_TAYLOR_SHIFT:\\n        if ln2 is None:\\n            ln2 = ln2_fixed(wp)\\n        r = bitcount(n)\\n        x = n << (wp-r)\\n        v = log_taylor_cached(x, wp) + r*ln2\\n    else:\\n        v = to_fixed(mpf_log(from_int(n), wp+5), wp)\\n    if n < MAX_LOG_INT_CACHE:\\n        log_int_cache[n] = (v, wp)\\n    return v >> (wp-prec)\\n\\ndef agm_fixed(a, b, prec):\\n    \\\"\\\"\\\"\\n    Fixed-point computation of agm(a,b), assuming\\n    a, b both close to unit magnitude.\\n    \\\"\\\"\\\"\\n    i = 0\\n    while 1:\\n        anew = (a+b)>>1\\n        if i > 4 and abs(a-anew) < 8:\\n            return a\\n        b = isqrt_fast(a*b)\\n        a = anew\\n        i += 1\\n    return a\\n\\ndef log_agm(x, prec):\\n    \\\"\\\"\\\"\\n    Fixed-point computation of -log(x) = log(1/x), suitable\\n    for large precision. It is required that 0 < x < 1. The\\n    algorithm used is the Sasaki-Kanada formula\\n\\n        -log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1]\\n\\n    For faster convergence in the theta functions, x should\\n    be chosen closer to 0.\\n\\n    Guard bits must be added by the caller.\\n\\n    HYPOTHESIS: if x = 2^(-n), n bits need to be added to\\n    account for the truncation to a fixed-point number,\\n    and this is the only significant cancellation error.\\n\\n    The number of bits lost to roundoff is small and can be\\n    considered constant.\\n\\n    [1] Richard P. Brent, \\\"Fast Algorithms for High-Precision\\n        Computation of Elementary Functions (extended abstract)\\\",\\n        http://wwwmaths.anu.edu.au/~brent/pd/RNC7-Brent.pdf\\n\\n    \\\"\\\"\\\"\\n    x2 = (x*x) >> prec\\n    # Compute jtheta2(x)**2\\n    s = a = b = x2\\n    while a:\\n        b = (b*x2) >> prec\\n        a = (a*b) >> prec\\n        s += a\\n    s += (MPZ_ONE<<prec)\\n    s = (s*s)>>(prec-2)\\n    s = (s*isqrt_fast(x<<prec))>>prec\\n    # Compute jtheta3(x)**2\\n    t = a = b = x\\n    while a:\\n        b = (b*x2) >> prec\\n        a = (a*b) >> prec\\n        t += a\\n    t = (MPZ_ONE<<prec) + (t<<1)\\n    t = (t*t)>>prec\\n    # Final formula\\n    p = agm_fixed(s, t, prec)\\n    return (pi_fixed(prec) << prec) // p\\n\\ndef log_taylor(x, prec, r=0):\\n    \\\"\\\"\\\"\\n    Fixed-point calculation of log(x). It is assumed that x is close\\n    enough to 1 for the Taylor series to converge quickly. Convergence\\n    can be improved by specifying r > 0 to compute\\n    log(x^(1/2^r))*2^r, at the cost of performing r square roots.\\n\\n    The caller must provide sufficient guard bits.\\n    \\\"\\\"\\\"\\n    for i in xrange(r):\\n        x = isqrt_fast(x<<prec)\\n    one = MPZ_ONE << prec\\n    v = ((x-one)<<prec)//(x+one)\\n    sign = v < 0\\n    if sign:\\n        v = -v\\n    v2 = (v*v) >> prec\\n    v4 = (v2*v2) >> prec\\n    s0 = v\\n    s1 = v//3\\n    v = (v*v4) >> prec\\n    k = 5\\n    while v:\\n        s0 += v // k\\n        k += 2\\n        s1 += v // k\\n        v = (v*v4) >> prec\\n        k += 2\\n    s1 = (s1*v2) >> prec\\n    s = (s0+s1) << (1+r)\\n    if sign:\\n        return -s\\n    return s\\n\\ndef log_taylor_cached(x, prec):\\n    \\\"\\\"\\\"\\n    Fixed-point computation of log(x), assuming x in (0.5, 2)\\n    and prec <= LOG_TAYLOR_PREC.\\n    \\\"\\\"\\\"\\n    n = x >> (prec-LOG_TAYLOR_SHIFT)\\n    cached_prec = cache_prec_steps[prec]\\n    dprec = cached_prec - prec\\n    if (n, cached_prec) in log_taylor_cache:\\n        a, log_a = log_taylor_cache[n, cached_prec]\\n    else:\\n        a = n << (cached_prec - LOG_TAYLOR_SHIFT)\\n        log_a = log_taylor(a, cached_prec, 8)\\n        log_taylor_cache[n, cached_prec] = (a, log_a)\\n    a >>= dprec\\n    log_a >>= dprec\\n    u = ((x - a) << prec) // a\\n    v = (u << prec) // ((MPZ_TWO << prec) + u)\\n    v2 = (v*v) >> prec\\n    v4 = (v2*v2) >> prec\\n    s0 = v\\n    s1 = v//3\\n    v = (v*v4) >> prec\\n    k = 5\\n    while v:\\n        s0 += v//k\\n        k += 2\\n        s1 += v//k\\n        v = (v*v4) >> prec\\n        k += 2\\n    s1 = (s1*v2) >> prec\\n    s = (s0+s1) << 1\\n    return log_a + s\\n\\ndef mpf_log(x, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Compute the natural logarithm of the mpf value x. If x is negative,\\n    ComplexResult is raised.\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    #------------------------------------------------------------------\\n    # Handle special values\\n    if not man:\\n        if x == fzero: return fninf\\n        if x == finf: return finf\\n        if x == fnan: return fnan\\n    if sign:\\n        raise ComplexResult(\\\"logarithm of a negative number\\\")\\n    wp = prec + 20\\n    #------------------------------------------------------------------\\n    # Handle log(2^n) = log(n)*2.\\n    # Here we catch the only possible exact value, log(1) = 0\\n    if man == 1:\\n        if not exp:\\n            return fzero\\n        return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd)\\n    mag = exp+bc\\n    abs_mag = abs(mag)\\n    #------------------------------------------------------------------\\n    # Handle x = 1+eps, where log(x) ~ x. We need to check for\\n    # cancellation when moving to fixed-point math and compensate\\n    # by increasing the precision. Note that abs_mag in (0, 1) <=>\\n    # 0.5 < x < 2 and x != 1\\n    if abs_mag <= 1:\\n        # Calculate t = x-1 to measure distance from 1 in bits\\n        tsign = 1-abs_mag\\n        if tsign:\\n            tman = (MPZ_ONE<<bc) - man\\n        else:\\n            tman = man - (MPZ_ONE<<(bc-1))\\n        tbc = bitcount(tman)\\n        cancellation = bc - tbc\\n        if cancellation > wp:\\n            t = normalize(tsign, tman, abs_mag-bc, tbc, tbc, 'n')\\n            return mpf_perturb(t, tsign, prec, rnd)\\n        else:\\n            wp += cancellation\\n        # TODO: if close enough to 1, we could use Taylor series\\n        # even in the AGM precision range, since the Taylor series\\n        # converges rapidly\\n    #------------------------------------------------------------------\\n    # Another special case:\\n    # n*log(2) is a good enough approximation\\n    if abs_mag > 10000:\\n        if bitcount(abs_mag) > wp:\\n            return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd)\\n    #------------------------------------------------------------------\\n    # General case.\\n    # Perform argument reduction using log(x) = log(x*2^n) - n*log(2):\\n    # If we are in the Taylor precision range, choose magnitude 0 or 1.\\n    # If we are in the AGM precision range, choose magnitude -m for\\n    # some large m; benchmarking on one machine showed m = prec/20 to be\\n    # optimal between 1000 and 100,000 digits.\\n    if wp <= LOG_TAYLOR_PREC:\\n        m = log_taylor_cached(lshift(man, wp-bc), wp)\\n        if mag:\\n            m += mag*ln2_fixed(wp)\\n    else:\\n        optimal_mag = -wp//LOG_AGM_MAG_PREC_RATIO\\n        n = optimal_mag - mag\\n        x = mpf_shift(x, n)\\n        wp += (-optimal_mag)\\n        m = -log_agm(to_fixed(x, wp), wp)\\n        m -= n*ln2_fixed(wp)\\n    return from_man_exp(m, -wp, prec, rnd)\\n\\ndef mpf_log_hypot(a, b, prec, rnd):\\n    \\\"\\\"\\\"\\n    Computes log(sqrt(a^2+b^2)) accurately.\\n    \\\"\\\"\\\"\\n    # If either a or b is inf/nan/0, assume it to be a\\n    if not b[1]:\\n        a, b = b, a\\n    # a is inf/nan/0\\n    if not a[1]:\\n        # both are inf/nan/0\\n        if not b[1]:\\n            if a == b == fzero:\\n                return fninf\\n            if fnan in (a, b):\\n                return fnan\\n            # at least one term is (+/- inf)^2\\n            return finf\\n        # only a is inf/nan/0\\n        if a == fzero:\\n            # log(sqrt(0+b^2)) = log(|b|)\\n            return mpf_log(mpf_abs(b), prec, rnd)\\n        if a == fnan:\\n            return fnan\\n        return finf\\n    # Exact\\n    a2 = mpf_mul(a,a)\\n    b2 = mpf_mul(b,b)\\n    extra = 20\\n    # Not exact\\n    h2 = mpf_add(a2, b2, prec+extra)\\n    cancelled = mpf_add(h2, fnone, 10)\\n    mag_cancelled = cancelled[2]+cancelled[3]\\n    # Just redo the sum exactly if necessary (could be smarter\\n    # and avoid memory allocation when a or b is precisely 1\\n    # and the other is tiny...)\\n    if cancelled == fzero or mag_cancelled < -extra//2:\\n        h2 = mpf_add(a2, b2, prec+extra-min(a2[2],b2[2]))\\n    return mpf_shift(mpf_log(h2, prec, rnd), -1)\\n\\n\\n#----------------------------------------------------------------------\\n# Inverse tangent\\n#\\n\\ndef atan_newton(x, prec):\\n    if prec >= 100:\\n        r = math.atan(int((x>>(prec-53)))/2.0**53)\\n    else:\\n        r = math.atan(int(x)/2.0**prec)\\n    prevp = 50\\n    r = MPZ(int(r * 2.0**53) >> (53-prevp))\\n    extra_p = 50\\n    for wp in giant_steps(prevp, prec):\\n        wp += extra_p\\n        r = r << (wp-prevp)\\n        cos, sin = cos_sin_fixed(r, wp)\\n        tan = (sin << wp) // cos\\n        a = ((tan-rshift(x, prec-wp)) << wp) // ((MPZ_ONE<<wp) + ((tan**2)>>wp))\\n        r = r - a\\n        prevp = wp\\n    return rshift(r, prevp-prec)\\n\\ndef atan_taylor_get_cached(n, prec):\\n    # Taylor series with caching wins up to huge precisions\\n    # To avoid unnecessary precomputation at low precision, we\\n    # do it in steps\\n    # Round to next power of 2\\n    prec2 = (1<<(bitcount(prec-1))) + 20\\n    dprec = prec2 - prec\\n    if (n, prec2) in atan_taylor_cache:\\n        a, atan_a = atan_taylor_cache[n, prec2]\\n    else:\\n        a = n << (prec2 - ATAN_TAYLOR_SHIFT)\\n        atan_a = atan_newton(a, prec2)\\n        atan_taylor_cache[n, prec2] = (a, atan_a)\\n    return (a >> dprec), (atan_a >> dprec)\\n\\ndef atan_taylor(x, prec):\\n    n = (x >> (prec-ATAN_TAYLOR_SHIFT))\\n    a, atan_a = atan_taylor_get_cached(n, prec)\\n    d = x - a\\n    s0 = v = (d << prec) // ((a**2 >> prec) + (a*d >> prec) + (MPZ_ONE << prec))\\n    v2 = (v**2 >> prec)\\n    v4 = (v2 * v2) >> prec\\n    s1 = v//3\\n    v = (v * v4) >> prec\\n    k = 5\\n    while v:\\n        s0 += v // k\\n        k += 2\\n        s1 += v // k\\n        v = (v * v4) >> prec\\n        k += 2\\n    s1 = (s1 * v2) >> prec\\n    s = s0 - s1\\n    return atan_a + s\\n\\ndef atan_inf(sign, prec, rnd):\\n    if not sign:\\n        return mpf_shift(mpf_pi(prec, rnd), -1)\\n    return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1))\\n\\ndef mpf_atan(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero: return fzero\\n        if x == finf: return atan_inf(0, prec, rnd)\\n        if x == fninf: return atan_inf(1, prec, rnd)\\n        return fnan\\n    mag = exp + bc\\n    # Essentially infinity\\n    if mag > prec+20:\\n        return atan_inf(sign, prec, rnd)\\n    # Essentially ~ x\\n    if -mag > prec+20:\\n        return mpf_perturb(x, 1-sign, prec, rnd)\\n    wp = prec + 30 + abs(mag)\\n    # For large x, use atan(x) = pi/2 - atan(1/x)\\n    if mag >= 2:\\n        x = mpf_rdiv_int(1, x, wp)\\n        reciprocal = True\\n    else:\\n        reciprocal = False\\n    t = to_fixed(x, wp)\\n    if sign:\\n        t = -t\\n    if wp < ATAN_TAYLOR_PREC:\\n        a = atan_taylor(t, wp)\\n    else:\\n        a = atan_newton(t, wp)\\n    if reciprocal:\\n        a = ((pi_fixed(wp)>>1)+1) - a\\n    if sign:\\n        a = -a\\n    return from_man_exp(a, -wp, prec, rnd)\\n\\n# TODO: cleanup the special cases\\ndef mpf_atan2(y, x, prec, rnd=round_fast):\\n    xsign, xman, xexp, xbc = x\\n    ysign, yman, yexp, ybc = y\\n    if not yman:\\n        if y == fzero and x != fnan:\\n            if mpf_sign(x) >= 0:\\n                return fzero\\n            return mpf_pi(prec, rnd)\\n        if y in (finf, fninf):\\n            if x in (finf, fninf):\\n                return fnan\\n            # pi/2\\n            if y == finf:\\n                return mpf_shift(mpf_pi(prec, rnd), -1)\\n            # -pi/2\\n            return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1))\\n        return fnan\\n    if ysign:\\n        return mpf_neg(mpf_atan2(mpf_neg(y), x, prec, negative_rnd[rnd]))\\n    if not xman:\\n        if x == fnan:\\n            return fnan\\n        if x == finf:\\n            return fzero\\n        if x == fninf:\\n            return mpf_pi(prec, rnd)\\n        if y == fzero:\\n            return fzero\\n        return mpf_shift(mpf_pi(prec, rnd), -1)\\n    tquo = mpf_atan(mpf_div(y, x, prec+4), prec+4)\\n    if xsign:\\n        return mpf_add(mpf_pi(prec+4), tquo, prec, rnd)\\n    else:\\n        return mpf_pos(tquo, prec, rnd)\\n\\ndef mpf_asin(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if bc+exp > 0 and x not in (fone, fnone):\\n        raise ComplexResult(\\\"asin(x) is real only for -1 <= x <= 1\\\")\\n    # asin(x) = 2*atan(x/(1+sqrt(1-x**2)))\\n    wp = prec + 15\\n    a = mpf_mul(x, x)\\n    b = mpf_add(fone, mpf_sqrt(mpf_sub(fone, a, wp), wp), wp)\\n    c = mpf_div(x, b, wp)\\n    return mpf_shift(mpf_atan(c, prec, rnd), 1)\\n\\ndef mpf_acos(x, prec, rnd=round_fast):\\n    # acos(x) = 2*atan(sqrt(1-x**2)/(1+x))\\n    sign, man, exp, bc = x\\n    if bc + exp > 0:\\n        if x not in (fone, fnone):\\n            raise ComplexResult(\\\"acos(x) is real only for -1 <= x <= 1\\\")\\n        if x == fnone:\\n            return mpf_pi(prec, rnd)\\n    wp = prec + 15\\n    a = mpf_mul(x, x)\\n    b = mpf_sqrt(mpf_sub(fone, a, wp), wp)\\n    c = mpf_div(b, mpf_add(fone, x, wp), wp)\\n    return mpf_shift(mpf_atan(c, prec, rnd), 1)\\n\\ndef mpf_asinh(x, prec, rnd=round_fast):\\n    wp = prec + 20\\n    sign, man, exp, bc = x\\n    mag = exp+bc\\n    if mag < -8:\\n        if mag < -wp:\\n            return mpf_perturb(x, 1-sign, prec, rnd)\\n        wp += (-mag)\\n    # asinh(x) = log(x+sqrt(x**2+1))\\n    # use reflection symmetry to avoid cancellation\\n    q = mpf_sqrt(mpf_add(mpf_mul(x, x), fone, wp), wp)\\n    q = mpf_add(mpf_abs(x), q, wp)\\n    if sign:\\n        return mpf_neg(mpf_log(q, prec, negative_rnd[rnd]))\\n    else:\\n        return mpf_log(q, prec, rnd)\\n\\ndef mpf_acosh(x, prec, rnd=round_fast):\\n    # acosh(x) = log(x+sqrt(x**2-1))\\n    wp = prec + 15\\n    if mpf_cmp(x, fone) == -1:\\n        raise ComplexResult(\\\"acosh(x) is real only for x >= 1\\\")\\n    q = mpf_sqrt(mpf_add(mpf_mul(x,x), fnone, wp), wp)\\n    return mpf_log(mpf_add(x, q, wp), prec, rnd)\\n\\ndef mpf_atanh(x, prec, rnd=round_fast):\\n    # atanh(x) = log((1+x)/(1-x))/2\\n    sign, man, exp, bc = x\\n    if (not man) and exp:\\n        if x in (fzero, fnan):\\n            return x\\n        raise ComplexResult(\\\"atanh(x) is real only for -1 <= x <= 1\\\")\\n    mag = bc + exp\\n    if mag > 0:\\n        if mag == 1 and man == 1:\\n            return [finf, fninf][sign]\\n        raise ComplexResult(\\\"atanh(x) is real only for -1 <= x <= 1\\\")\\n    wp = prec + 15\\n    if mag < -8:\\n        if mag < -wp:\\n            return mpf_perturb(x, sign, prec, rnd)\\n        wp += (-mag)\\n    a = mpf_add(x, fone, wp)\\n    b = mpf_sub(fone, x, wp)\\n    return mpf_shift(mpf_log(mpf_div(a, b, wp), prec, rnd), -1)\\n\\ndef mpf_fibonacci(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fninf:\\n            return fnan\\n        return x\\n    # F(2^n) ~= 2^(2^n)\\n    size = abs(exp+bc)\\n    if exp >= 0:\\n        # Exact\\n        if size < 10 or size <= bitcount(prec):\\n            return from_int(ifib(to_int(x)), prec, rnd)\\n    # Use the modified Binet formula\\n    wp = prec + size + 20\\n    a = mpf_phi(wp)\\n    b = mpf_add(mpf_shift(a, 1), fnone, wp)\\n    u = mpf_pow(a, x, wp)\\n    v = mpf_cos_pi(x, wp)\\n    v = mpf_div(v, u, wp)\\n    u = mpf_sub(u, v, wp)\\n    u = mpf_div(u, b, prec, rnd)\\n    return u\\n\\n\\n#-------------------------------------------------------------------------------\\n# Exponential-type functions\\n#-------------------------------------------------------------------------------\\n\\ndef exponential_series(x, prec, type=0):\\n    \\\"\\\"\\\"\\n    Taylor series for cosh/sinh or cos/sin.\\n\\n    type = 0 -- returns exp(x)  (slightly faster than cosh+sinh)\\n    type = 1 -- returns (cosh(x), sinh(x))\\n    type = 2 -- returns (cos(x), sin(x))\\n    \\\"\\\"\\\"\\n    if x < 0:\\n        x = -x\\n        sign = 1\\n    else:\\n        sign = 0\\n    r = int(0.5*prec**0.5)\\n    xmag = bitcount(x) - prec\\n    r = max(0, xmag + r)\\n    extra = 10 + 2*max(r,-xmag)\\n    wp = prec + extra\\n    x <<= (extra - r)\\n    one = MPZ_ONE << wp\\n    alt = (type == 2)\\n    if prec < EXP_SERIES_U_CUTOFF:\\n        x2 = a = (x*x) >> wp\\n        x4 = (x2*x2) >> wp\\n        s0 = s1 = MPZ_ZERO\\n        k = 2\\n        while a:\\n            a //= (k-1)*k; s0 += a; k += 2\\n            a //= (k-1)*k; s1 += a; k += 2\\n            a = (a*x4) >> wp\\n        s1 = (x2*s1) >> wp\\n        if alt:\\n            c = s1 - s0 + one\\n        else:\\n            c = s1 + s0 + one\\n    else:\\n        u = int(0.3*prec**0.35)\\n        x2 = a = (x*x) >> wp\\n        xpowers = [one, x2]\\n        for i in xrange(1, u):\\n            xpowers.append((xpowers[-1]*x2)>>wp)\\n        sums = [MPZ_ZERO] * u\\n        k = 2\\n        while a:\\n            for i in xrange(u):\\n                a //= (k-1)*k\\n                if alt and k & 2: sums[i] -= a\\n                else:             sums[i] += a\\n                k += 2\\n            a = (a*xpowers[-1]) >> wp\\n        for i in xrange(1, u):\\n            sums[i] = (sums[i]*xpowers[i]) >> wp\\n        c = sum(sums) + one\\n    if type == 0:\\n        s = isqrt_fast(c*c - (one<<wp))\\n        if sign:\\n            v = c - s\\n        else:\\n            v = c + s\\n        for i in xrange(r):\\n            v = (v*v) >> wp\\n        return v >> extra\\n    else:\\n        # Repeatedly apply the double-angle formula\\n        # cosh(2*x) = 2*cosh(x)^2 - 1\\n        # cos(2*x) = 2*cos(x)^2 - 1\\n        pshift = wp-1\\n        for i in xrange(r):\\n            c = ((c*c) >> pshift) - one\\n        # With the abs, this is the same for sinh and sin\\n        s = isqrt_fast(abs((one<<wp) - c*c))\\n        if sign:\\n            s = -s\\n        return (c>>extra), (s>>extra)\\n\\ndef exp_basecase(x, prec):\\n    \\\"\\\"\\\"\\n    Compute exp(x) as a fixed-point number. Works for any x,\\n    but for speed should have |x| < 1. For an arbitrary number,\\n    use exp(x) = exp(x-m*log(2)) * 2^m where m = floor(x/log(2)).\\n    \\\"\\\"\\\"\\n    if prec > EXP_COSH_CUTOFF:\\n        return exponential_series(x, prec, 0)\\n    r = int(prec**0.5)\\n    prec += r\\n    s0 = s1 = (MPZ_ONE << prec)\\n    k = 2\\n    a = x2 = (x*x) >> prec\\n    while a:\\n        a //= k; s0 += a; k += 1\\n        a //= k; s1 += a; k += 1\\n        a = (a*x2) >> prec\\n    s1 = (s1*x) >> prec\\n    s = s0 + s1\\n    u = r\\n    while r:\\n        s = (s*s) >> prec\\n        r -= 1\\n    return s >> u\\n\\ndef exp_expneg_basecase(x, prec):\\n    \\\"\\\"\\\"\\n    Computation of exp(x), exp(-x)\\n    \\\"\\\"\\\"\\n    if prec > EXP_COSH_CUTOFF:\\n        cosh, sinh = exponential_series(x, prec, 1)\\n        return cosh+sinh, cosh-sinh\\n    a = exp_basecase(x, prec)\\n    b = (MPZ_ONE << (prec+prec)) // a\\n    return a, b\\n\\ndef cos_sin_basecase(x, prec):\\n    \\\"\\\"\\\"\\n    Compute cos(x), sin(x) as fixed-point numbers, assuming x\\n    in [0, pi/2). For an arbitrary number, use x' = x - m*(pi/2)\\n    where m = floor(x/(pi/2)) along with quarter-period symmetries.\\n    \\\"\\\"\\\"\\n    if prec > COS_SIN_CACHE_PREC:\\n        return exponential_series(x, prec, 2)\\n    precs = prec - COS_SIN_CACHE_STEP\\n    t = x >> precs\\n    n = int(t)\\n    if n not in cos_sin_cache:\\n        w = t<<(10+COS_SIN_CACHE_PREC-COS_SIN_CACHE_STEP)\\n        cos_t, sin_t = exponential_series(w, 10+COS_SIN_CACHE_PREC, 2)\\n        cos_sin_cache[n] = (cos_t>>10), (sin_t>>10)\\n    cos_t, sin_t = cos_sin_cache[n]\\n    offset = COS_SIN_CACHE_PREC - prec\\n    cos_t >>= offset\\n    sin_t >>= offset\\n    x -= t << precs\\n    cos = MPZ_ONE << prec\\n    sin = x\\n    k = 2\\n    a = -((x*x) >> prec)\\n    while a:\\n        a //= k; cos += a; k += 1; a = (a*x) >> prec\\n        a //= k; sin += a; k += 1; a = -((a*x) >> prec)\\n    return ((cos*cos_t-sin*sin_t) >> prec), ((sin*cos_t+cos*sin_t) >> prec)\\n\\ndef mpf_exp(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if man:\\n        mag = bc + exp\\n        wp = prec + 14\\n        if sign:\\n            man = -man\\n        # TODO: the best cutoff depends on both x and the precision.\\n        if prec > 600 and exp >= 0:\\n            # Need about log2(exp(n)) ~= 1.45*mag extra precision\\n            e = mpf_e(wp+int(1.45*mag))\\n            return mpf_pow_int(e, man<<exp, prec, rnd)\\n        if mag < -wp:\\n            return mpf_perturb(fone, sign, prec, rnd)\\n        # |x| >= 2\\n        if mag > 1:\\n            # For large arguments: exp(2^mag*(1+eps)) =\\n            # exp(2^mag)*exp(2^mag*eps) = exp(2^mag)*(1 + 2^mag*eps + ...)\\n            # so about mag extra bits is required.\\n            wpmod = wp + mag\\n            offset = exp + wpmod\\n            if offset >= 0:\\n                t = man << offset\\n            else:\\n                t = man >> (-offset)\\n            lg2 = ln2_fixed(wpmod)\\n            n, t = divmod(t, lg2)\\n            n = int(n)\\n            t >>= mag\\n        else:\\n            offset = exp + wp\\n            if offset >= 0:\\n                t = man << offset\\n            else:\\n                t = man >> (-offset)\\n            n = 0\\n        man = exp_basecase(t, wp)\\n        return from_man_exp(man, n-wp, prec, rnd)\\n    if not exp:\\n        return fone\\n    if x == fninf:\\n        return fzero\\n    return x\\n\\n\\ndef mpf_cosh_sinh(x, prec, rnd=round_fast, tanh=0):\\n    \\\"\\\"\\\"Simultaneously compute (cosh(x), sinh(x)) for real x\\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    if (not man) and exp:\\n        if tanh:\\n            if x == finf: return fone\\n            if x == fninf: return fnone\\n            return fnan\\n        if x == finf: return (finf, finf)\\n        if x == fninf: return (finf, fninf)\\n        return fnan, fnan\\n    mag = exp+bc\\n    wp = prec+14\\n    if mag < -4:\\n        # Extremely close to 0, sinh(x) ~= x and cosh(x) ~= 1\\n        if mag < -wp:\\n            if tanh:\\n                return mpf_perturb(x, 1-sign, prec, rnd)\\n            cosh = mpf_perturb(fone, 0, prec, rnd)\\n            sinh = mpf_perturb(x, sign, prec, rnd)\\n            return cosh, sinh\\n        # Fix for cancellation when computing sinh\\n        wp += (-mag)\\n    # Does exp(-2*x) vanish?\\n    if mag > 10:\\n        if 3*(1<<(mag-1)) > wp:\\n            # XXX: rounding\\n            if tanh:\\n                return mpf_perturb([fone,fnone][sign], 1-sign, prec, rnd)\\n            c = s = mpf_shift(mpf_exp(mpf_abs(x), prec, rnd), -1)\\n            if sign:\\n                s = mpf_neg(s)\\n            return c, s\\n    # |x| > 1\\n    if mag > 1:\\n        wpmod = wp + mag\\n        offset = exp + wpmod\\n        if offset >= 0:\\n            t = man << offset\\n        else:\\n            t = man >> (-offset)\\n        lg2 = ln2_fixed(wpmod)\\n        n, t = divmod(t, lg2)\\n        n = int(n)\\n        t >>= mag\\n    else:\\n        offset = exp + wp\\n        if offset >= 0:\\n            t = man << offset\\n        else:\\n            t = man >> (-offset)\\n        n = 0\\n    a, b = exp_expneg_basecase(t, wp)\\n    # TODO: optimize division precision\\n    cosh = a + (b>>(2*n))\\n    sinh = a - (b>>(2*n))\\n    if sign:\\n        sinh = -sinh\\n    if tanh:\\n        man = (sinh << wp) // cosh\\n        return from_man_exp(man, -wp, prec, rnd)\\n    else:\\n        cosh = from_man_exp(cosh, n-wp-1, prec, rnd)\\n        sinh = from_man_exp(sinh, n-wp-1, prec, rnd)\\n        return cosh, sinh\\n\\n\\ndef mod_pi2(man, exp, mag, wp):\\n    # Reduce to standard interval\\n    if mag > 0:\\n        i = 0\\n        while 1:\\n            cancellation_prec = 20 << i\\n            wpmod = wp + mag + cancellation_prec\\n            pi2 = pi_fixed(wpmod-1)\\n            pi4 = pi2 >> 1\\n            offset = wpmod + exp\\n            if offset >= 0:\\n                t = man << offset\\n            else:\\n                t = man >> (-offset)\\n            n, y = divmod(t, pi2)\\n            if y > pi4:\\n                small = pi2 - y\\n            else:\\n                small = y\\n            if small >> (wp+mag-10):\\n                n = int(n)\\n                t = y >> mag\\n                wp = wpmod - mag\\n                break\\n            i += 1\\n    else:\\n        wp += (-mag)\\n        offset = exp + wp\\n        if offset >= 0:\\n            t = man << offset\\n        else:\\n            t = man >> (-offset)\\n        n = 0\\n    return t, n, wp\\n\\n\\ndef mpf_cos_sin(x, prec, rnd=round_fast, which=0, pi=False):\\n    \\\"\\\"\\\"\\n    which:\\n    0 -- return cos(x), sin(x)\\n    1 -- return cos(x)\\n    2 -- return sin(x)\\n    3 -- return tan(x)\\n\\n    if pi=True, compute for pi*x\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    if not man:\\n        if exp:\\n            c, s = fnan, fnan\\n        else:\\n            c, s = fone, fzero\\n        if which == 0: return c, s\\n        if which == 1: return c\\n        if which == 2: return s\\n        if which == 3: return s\\n\\n    mag = bc + exp\\n    wp = prec + 10\\n\\n    # Extremely small?\\n    if mag < 0:\\n        if mag < -wp:\\n            if pi:\\n                x = mpf_mul(x, mpf_pi(wp))\\n            c = mpf_perturb(fone, 1, prec, rnd)\\n            s = mpf_perturb(x, 1-sign, prec, rnd)\\n            if which == 0: return c, s\\n            if which == 1: return c\\n            if which == 2: return s\\n            if which == 3: return mpf_perturb(x, sign, prec, rnd)\\n    if pi:\\n        if exp >= -1:\\n            if exp == -1:\\n                c = fzero\\n                s = (fone, fnone)[bool(man & 2) ^ sign]\\n            elif exp == 0:\\n                c, s = (fnone, fzero)\\n            else:\\n                c, s = (fone, fzero)\\n            if which == 0: return c, s\\n            if which == 1: return c\\n            if which == 2: return s\\n            if which == 3: return mpf_div(s, c, prec, rnd)\\n        # Subtract nearest half-integer (= mod by pi/2)\\n        n = ((man >> (-exp-2)) + 1) >> 1\\n        man = man - (n << (-exp-1))\\n        mag2 = bitcount(man) + exp\\n        wp = prec + 10 - mag2\\n        offset = exp + wp\\n        if offset >= 0:\\n            t = man << offset\\n        else:\\n            t = man >> (-offset)\\n        t = (t*pi_fixed(wp)) >> wp\\n    else:\\n        t, n, wp = mod_pi2(man, exp, mag, wp)\\n    c, s = cos_sin_basecase(t, wp)\\n    m = n & 3\\n    if   m == 1: c, s = -s, c\\n    elif m == 2: c, s = -c, -s\\n    elif m == 3: c, s = s, -c\\n    if sign:\\n        s = -s\\n    if which == 0:\\n        c = from_man_exp(c, -wp, prec, rnd)\\n        s = from_man_exp(s, -wp, prec, rnd)\\n        return c, s\\n    if which == 1:\\n        return from_man_exp(c, -wp, prec, rnd)\\n    if which == 2:\\n        return from_man_exp(s, -wp, prec, rnd)\\n    if which == 3:\\n        return from_rational(s, c, prec, rnd)\\n\\ndef mpf_cos(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1)\\ndef mpf_sin(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2)\\ndef mpf_tan(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 3)\\ndef mpf_cos_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 0, 1)\\ndef mpf_cos_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1, 1)\\ndef mpf_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2, 1)\\ndef mpf_cosh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[0]\\ndef mpf_sinh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[1]\\ndef mpf_tanh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd, tanh=1)\\n\\n\\n# Low-overhead fixed-point versions\\n\\ndef cos_sin_fixed(x, prec, pi2=None):\\n    if pi2 is None:\\n        pi2 = pi_fixed(prec-1)\\n    n, t = divmod(x, pi2)\\n    n = int(n)\\n    c, s = cos_sin_basecase(t, prec)\\n    m = n & 3\\n    if m == 0: return c, s\\n    if m == 1: return -s, c\\n    if m == 2: return -c, -s\\n    if m == 3: return s, -c\\n\\ndef exp_fixed(x, prec, ln2=None):\\n    if ln2 is None:\\n        ln2 = ln2_fixed(prec)\\n    n, t = divmod(x, ln2)\\n    n = int(n)\\n    v = exp_basecase(t, prec)\\n    if n >= 0:\\n        return v << n\\n    else:\\n        return v >> (-n)\\n\\n\\nif BACKEND == 'sage':\\n    try:\\n        import sage.libs.mpmath.ext_libmp as _lbmp\\n        mpf_sqrt = _lbmp.mpf_sqrt\\n        mpf_exp = _lbmp.mpf_exp\\n        mpf_log = _lbmp.mpf_log\\n        mpf_cos = _lbmp.mpf_cos\\n        mpf_sin = _lbmp.mpf_sin\\n        mpf_pow = _lbmp.mpf_pow\\n        exp_fixed = _lbmp.exp_fixed\\n        cos_sin_fixed = _lbmp.cos_sin_fixed\\n        log_int_fixed = _lbmp.log_int_fixed\\n    except (ImportError, AttributeError):\\n        print(\\\"Warning: Sage imports in libelefun failed\\\")\\n\\n\\n\\\"\\\"\\\"\\nLow-level functions for complex arithmetic.\\n\\\"\\\"\\\"\\n\\nimport sys\\n\\nfrom .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, BACKEND\\n\\nfrom .libmpf import (\\\\\\n    round_floor, round_ceiling, round_down, round_up,\\n    round_nearest, round_fast, bitcount,\\n    bctable, normalize, normalize1, reciprocal_rnd, rshift, lshift, giant_steps,\\n    negative_rnd,\\n    to_str, to_fixed, from_man_exp, from_float, to_float, from_int, to_int,\\n    fzero, fone, ftwo, fhalf, finf, fninf, fnan, fnone,\\n    mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul,\\n    mpf_div, mpf_mul_int, mpf_shift, mpf_sqrt, mpf_hypot,\\n    mpf_rdiv_int, mpf_floor, mpf_ceil, mpf_nint, mpf_frac,\\n    mpf_sign, mpf_hash,\\n    ComplexResult\\n)\\n\\nfrom .libelefun import (\\\\\\n    mpf_pi, mpf_exp, mpf_log, mpf_cos_sin, mpf_cosh_sinh, mpf_tan, mpf_pow_int,\\n    mpf_log_hypot,\\n    mpf_cos_sin_pi, mpf_phi,\\n    mpf_cos, mpf_sin, mpf_cos_pi, mpf_sin_pi,\\n    mpf_atan, mpf_atan2, mpf_cosh, mpf_sinh, mpf_tanh,\\n    mpf_asin, mpf_acos, mpf_acosh, mpf_nthroot, mpf_fibonacci\\n)\\n\\n# An mpc value is a (real, imag) tuple\\nmpc_one = fone, fzero\\nmpc_zero = fzero, fzero\\nmpc_two = ftwo, fzero\\nmpc_half = (fhalf, fzero)\\n\\n_infs = (finf, fninf)\\n_infs_nan = (finf, fninf, fnan)\\n\\ndef mpc_is_inf(z):\\n    \\\"\\\"\\\"Check if either real or imaginary part is infinite\\\"\\\"\\\"\\n    re, im = z\\n    if re in _infs: return True\\n    if im in _infs: return True\\n    return False\\n\\ndef mpc_is_infnan(z):\\n    \\\"\\\"\\\"Check if either real or imaginary part is infinite or nan\\\"\\\"\\\"\\n    re, im = z\\n    if re in _infs_nan: return True\\n    if im in _infs_nan: return True\\n    return False\\n\\ndef mpc_to_str(z, dps, **kwargs):\\n    re, im = z\\n    rs = to_str(re, dps)\\n    if im[0]:\\n        return rs + \\\" - \\\" + to_str(mpf_neg(im), dps, **kwargs) + \\\"j\\\"\\n    else:\\n        return rs + \\\" + \\\" + to_str(im, dps, **kwargs) + \\\"j\\\"\\n\\ndef mpc_to_complex(z, strict=False, rnd=round_fast):\\n    re, im = z\\n    return complex(to_float(re, strict, rnd), to_float(im, strict, rnd))\\n\\ndef mpc_hash(z):\\n    if sys.version_info >= (3, 2):\\n        re, im = z\\n        h = mpf_hash(re) + sys.hash_info.imag * mpf_hash(im)\\n        # Need to reduce either module 2^32 or 2^64\\n        h = h % (2**sys.hash_info.width)\\n        return int(h)\\n    else:\\n        try:\\n            return hash(mpc_to_complex(z, strict=True))\\n        except OverflowError:\\n            return hash(z)\\n\\ndef mpc_conjugate(z, prec, rnd=round_fast):\\n    re, im = z\\n    return re, mpf_neg(im, prec, rnd)\\n\\ndef mpc_is_nonzero(z):\\n    return z != mpc_zero\\n\\ndef mpc_add(z, w, prec, rnd=round_fast):\\n    a, b = z\\n    c, d = w\\n    return mpf_add(a, c, prec, rnd), mpf_add(b, d, prec, rnd)\\n\\ndef mpc_add_mpf(z, x, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_add(a, x, prec, rnd), b\\n\\ndef mpc_sub(z, w, prec=0, rnd=round_fast):\\n    a, b = z\\n    c, d = w\\n    return mpf_sub(a, c, prec, rnd), mpf_sub(b, d, prec, rnd)\\n\\ndef mpc_sub_mpf(z, p, prec=0, rnd=round_fast):\\n    a, b = z\\n    return mpf_sub(a, p, prec, rnd), b\\n\\ndef mpc_pos(z, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_pos(a, prec, rnd), mpf_pos(b, prec, rnd)\\n\\ndef mpc_neg(z, prec=None, rnd=round_fast):\\n    a, b = z\\n    return mpf_neg(a, prec, rnd), mpf_neg(b, prec, rnd)\\n\\ndef mpc_shift(z, n):\\n    a, b = z\\n    return mpf_shift(a, n), mpf_shift(b, n)\\n\\ndef mpc_abs(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Absolute value of a complex number, |a+bi|.\\n    Returns an mpf value.\\\"\\\"\\\"\\n    a, b = z\\n    return mpf_hypot(a, b, prec, rnd)\\n\\ndef mpc_arg(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Argument of a complex number. Returns an mpf value.\\\"\\\"\\\"\\n    a, b = z\\n    return mpf_atan2(b, a, prec, rnd)\\n\\ndef mpc_floor(z, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_floor(a, prec, rnd), mpf_floor(b, prec, rnd)\\n\\ndef mpc_ceil(z, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_ceil(a, prec, rnd), mpf_ceil(b, prec, rnd)\\n\\ndef mpc_nint(z, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_nint(a, prec, rnd), mpf_nint(b, prec, rnd)\\n\\ndef mpc_frac(z, prec, rnd=round_fast):\\n    a, b = z\\n    return mpf_frac(a, prec, rnd), mpf_frac(b, prec, rnd)\\n\\n\\ndef mpc_mul(z, w, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Complex multiplication.\\n\\n    Returns the real and imaginary part of (a+bi)*(c+di), rounded to\\n    the specified precision. The rounding mode applies to the real and\\n    imaginary parts separately.\\n    \\\"\\\"\\\"\\n    a, b = z\\n    c, d = w\\n    p = mpf_mul(a, c)\\n    q = mpf_mul(b, d)\\n    r = mpf_mul(a, d)\\n    s = mpf_mul(b, c)\\n    re = mpf_sub(p, q, prec, rnd)\\n    im = mpf_add(r, s, prec, rnd)\\n    return re, im\\n\\ndef mpc_square(z, prec, rnd=round_fast):\\n    # (a+b*I)**2 == a**2 - b**2 + 2*I*a*b\\n    a, b = z\\n    p = mpf_mul(a,a)\\n    q = mpf_mul(b,b)\\n    r = mpf_mul(a,b, prec, rnd)\\n    re = mpf_sub(p, q, prec, rnd)\\n    im = mpf_shift(r, 1)\\n    return re, im\\n\\ndef mpc_mul_mpf(z, p, prec, rnd=round_fast):\\n    a, b = z\\n    re = mpf_mul(a, p, prec, rnd)\\n    im = mpf_mul(b, p, prec, rnd)\\n    return re, im\\n\\ndef mpc_mul_imag_mpf(z, x, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Multiply the mpc value z by I*x where x is an mpf value.\\n    \\\"\\\"\\\"\\n    a, b = z\\n    re = mpf_neg(mpf_mul(b, x, prec, rnd))\\n    im = mpf_mul(a, x, prec, rnd)\\n    return re, im\\n\\ndef mpc_mul_int(z, n, prec, rnd=round_fast):\\n    a, b = z\\n    re = mpf_mul_int(a, n, prec, rnd)\\n    im = mpf_mul_int(b, n, prec, rnd)\\n    return re, im\\n\\ndef mpc_div(z, w, prec, rnd=round_fast):\\n    a, b = z\\n    c, d = w\\n    wp = prec + 10\\n    # mag = c*c + d*d\\n    mag = mpf_add(mpf_mul(c, c), mpf_mul(d, d), wp)\\n    # (a*c+b*d)/mag, (b*c-a*d)/mag\\n    t = mpf_add(mpf_mul(a,c), mpf_mul(b,d), wp)\\n    u = mpf_sub(mpf_mul(b,c), mpf_mul(a,d), wp)\\n    return mpf_div(t,mag,prec,rnd), mpf_div(u,mag,prec,rnd)\\n\\ndef mpc_div_mpf(z, p, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Calculate z/p where p is real\\\"\\\"\\\"\\n    a, b = z\\n    re = mpf_div(a, p, prec, rnd)\\n    im = mpf_div(b, p, prec, rnd)\\n    return re, im\\n\\ndef mpc_reciprocal(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Calculate 1/z efficiently\\\"\\\"\\\"\\n    a, b = z\\n    m = mpf_add(mpf_mul(a,a),mpf_mul(b,b),prec+10)\\n    re = mpf_div(a, m, prec, rnd)\\n    im = mpf_neg(mpf_div(b, m, prec, rnd))\\n    return re, im\\n\\ndef mpc_mpf_div(p, z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Calculate p/z where p is real efficiently\\\"\\\"\\\"\\n    a, b = z\\n    m = mpf_add(mpf_mul(a,a),mpf_mul(b,b), prec+10)\\n    re = mpf_div(mpf_mul(a,p), m, prec, rnd)\\n    im = mpf_div(mpf_neg(mpf_mul(b,p)), m, prec, rnd)\\n    return re, im\\n\\ndef complex_int_pow(a, b, n):\\n    \\\"\\\"\\\"Complex integer power: computes (a+b*I)**n exactly for\\n    nonnegative n (a and b must be Python ints).\\\"\\\"\\\"\\n    wre = 1\\n    wim = 0\\n    while n:\\n        if n & 1:\\n            wre, wim = wre*a - wim*b, wim*a + wre*b\\n            n -= 1\\n        a, b = a*a - b*b, 2*a*b\\n        n //= 2\\n    return wre, wim\\n\\ndef mpc_pow(z, w, prec, rnd=round_fast):\\n    if w[1] == fzero:\\n        return mpc_pow_mpf(z, w[0], prec, rnd)\\n    return mpc_exp(mpc_mul(mpc_log(z, prec+10), w, prec+10), prec, rnd)\\n\\ndef mpc_pow_mpf(z, p, prec, rnd=round_fast):\\n    psign, pman, pexp, pbc = p\\n    if pexp >= 0:\\n        return mpc_pow_int(z, (-1)**psign * (pman<<pexp), prec, rnd)\\n    if pexp == -1:\\n        sqrtz = mpc_sqrt(z, prec+10)\\n        return mpc_pow_int(sqrtz, (-1)**psign * pman, prec, rnd)\\n    return mpc_exp(mpc_mul_mpf(mpc_log(z, prec+10), p, prec+10), prec, rnd)\\n\\ndef mpc_pow_int(z, n, prec, rnd=round_fast):\\n    a, b = z\\n    if b == fzero:\\n        return mpf_pow_int(a, n, prec, rnd), fzero\\n    if a == fzero:\\n        v = mpf_pow_int(b, n, prec, rnd)\\n        n %= 4\\n        if n == 0:\\n            return v, fzero\\n        elif n == 1:\\n            return fzero, v\\n        elif n == 2:\\n            return mpf_neg(v), fzero\\n        elif n == 3:\\n            return fzero, mpf_neg(v)\\n    if n == 0: return mpc_one\\n    if n == 1: return mpc_pos(z, prec, rnd)\\n    if n == 2: return mpc_square(z, prec, rnd)\\n    if n == -1: return mpc_reciprocal(z, prec, rnd)\\n    if n < 0: return mpc_reciprocal(mpc_pow_int(z, -n, prec+4), prec, rnd)\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n    if asign: aman = -aman\\n    if bsign: bman = -bman\\n    de = aexp - bexp\\n    abs_de = abs(de)\\n    exact_size = n*(abs_de + max(abc, bbc))\\n    if exact_size < 10000:\\n        if de > 0:\\n            aman <<= de\\n            aexp = bexp\\n        else:\\n            bman <<= (-de)\\n            bexp = aexp\\n        re, im = complex_int_pow(aman, bman, n)\\n        re = from_man_exp(re, int(n*aexp), prec, rnd)\\n        im = from_man_exp(im, int(n*bexp), prec, rnd)\\n        return re, im\\n    return mpc_exp(mpc_mul_int(mpc_log(z, prec+10), n, prec+10), prec, rnd)\\n\\ndef mpc_sqrt(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex square root (principal branch).\\n\\n    We have sqrt(a+bi) = sqrt((r+a)/2) + b/sqrt(2*(r+a))*i where\\n    r = abs(a+bi), when a+bi is not a negative real number.\\\"\\\"\\\"\\n    a, b = z\\n    if b == fzero:\\n        if a == fzero:\\n            return (a, b)\\n        # When a+bi is a negative real number, we get a real sqrt times i\\n        if a[0]:\\n            im = mpf_sqrt(mpf_neg(a), prec, rnd)\\n            return (fzero, im)\\n        else:\\n            re = mpf_sqrt(a, prec, rnd)\\n            return (re, fzero)\\n    wp = prec+20\\n    if not a[0]:                               # case a positive\\n        t  = mpf_add(mpc_abs((a, b), wp), a, wp)  # t = abs(a+bi) + a\\n        u = mpf_shift(t, -1)                      # u = t/2\\n        re = mpf_sqrt(u, prec, rnd)               # re = sqrt(u)\\n        v = mpf_shift(t, 1)                       # v = 2*t\\n        w  = mpf_sqrt(v, wp)                      # w = sqrt(v)\\n        im = mpf_div(b, w, prec, rnd)             # im = b / w\\n    else:                                      # case a negative\\n        t = mpf_sub(mpc_abs((a, b), wp), a, wp)   # t = abs(a+bi) - a\\n        u = mpf_shift(t, -1)                      # u = t/2\\n        im = mpf_sqrt(u, prec, rnd)               # im = sqrt(u)\\n        v = mpf_shift(t, 1)                       # v = 2*t\\n        w  = mpf_sqrt(v, wp)                      # w = sqrt(v)\\n        re = mpf_div(b, w, prec, rnd)             # re = b/w\\n        if b[0]:\\n            re = mpf_neg(re)\\n            im = mpf_neg(im)\\n    return re, im\\n\\ndef mpc_nthroot_fixed(a, b, n, prec):\\n    # a, b signed integers at fixed precision prec\\n    start = 50\\n    a1 = int(rshift(a, prec - n*start))\\n    b1 = int(rshift(b, prec - n*start))\\n    try:\\n        r = (a1 + 1j * b1)**(1.0/n)\\n        re = r.real\\n        im = r.imag\\n        re = MPZ(int(re))\\n        im = MPZ(int(im))\\n    except OverflowError:\\n        a1 = from_int(a1, start)\\n        b1 = from_int(b1, start)\\n        fn = from_int(n)\\n        nth = mpf_rdiv_int(1, fn, start)\\n        re, im = mpc_pow((a1, b1), (nth, fzero), start)\\n        re = to_int(re)\\n        im = to_int(im)\\n    extra = 10\\n    prevp = start\\n    extra1 = n\\n    for p in giant_steps(start, prec+extra):\\n        # this is slow for large n, unlike int_pow_fixed\\n        re2, im2 = complex_int_pow(re, im, n-1)\\n        re2 = rshift(re2, (n-1)*prevp - p - extra1)\\n        im2 = rshift(im2, (n-1)*prevp - p - extra1)\\n        r4 = (re2*re2 + im2*im2) >> (p + extra1)\\n        ap = rshift(a, prec - p)\\n        bp = rshift(b, prec - p)\\n        rec = (ap * re2 + bp * im2) >> p\\n        imc = (-ap * im2 + bp * re2) >> p\\n        reb = (rec << p) // r4\\n        imb = (imc << p) // r4\\n        re = (reb + (n-1)*lshift(re, p-prevp))//n\\n        im = (imb + (n-1)*lshift(im, p-prevp))//n\\n        prevp = p\\n    return re, im\\n\\ndef mpc_nthroot(z, n, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Complex n-th root.\\n\\n    Use Newton method as in the real case when it is faster,\\n    otherwise use z**(1/n)\\n    \\\"\\\"\\\"\\n    a, b = z\\n    if a[0] == 0 and b == fzero:\\n        re = mpf_nthroot(a, n, prec, rnd)\\n        return (re, fzero)\\n    if n < 2:\\n        if n == 0:\\n            return mpc_one\\n        if n == 1:\\n            return mpc_pos((a, b), prec, rnd)\\n        if n == -1:\\n            return mpc_div(mpc_one, (a, b), prec, rnd)\\n        inverse = mpc_nthroot((a, b), -n, prec+5, reciprocal_rnd[rnd])\\n        return mpc_div(mpc_one, inverse, prec, rnd)\\n    if n <= 20:\\n        prec2 = int(1.2 * (prec + 10))\\n        asign, aman, aexp, abc = a\\n        bsign, bman, bexp, bbc = b\\n        pf = mpc_abs((a,b), prec)\\n        if pf[-2] + pf[-1] > -10  and pf[-2] + pf[-1] < prec:\\n            af = to_fixed(a, prec2)\\n            bf = to_fixed(b, prec2)\\n            re, im = mpc_nthroot_fixed(af, bf, n, prec2)\\n            extra = 10\\n            re = from_man_exp(re, -prec2-extra, prec2, rnd)\\n            im = from_man_exp(im, -prec2-extra, prec2, rnd)\\n            return re, im\\n    fn = from_int(n)\\n    prec2 = prec+10 + 10\\n    nth = mpf_rdiv_int(1, fn, prec2)\\n    re, im = mpc_pow((a, b), (nth, fzero), prec2, rnd)\\n    re = normalize(re[0], re[1], re[2], re[3], prec, rnd)\\n    im = normalize(im[0], im[1], im[2], im[3], prec, rnd)\\n    return re, im\\n\\ndef mpc_cbrt(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Complex cubic root.\\n    \\\"\\\"\\\"\\n    return mpc_nthroot(z, 3, prec, rnd)\\n\\ndef mpc_exp(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Complex exponential function.\\n\\n    We use the direct formula exp(a+bi) = exp(a) * (cos(b) + sin(b)*i)\\n    for the computation. This formula is very nice because it is\\n    pefectly stable; since we just do real multiplications, the only\\n    numerical errors that can creep in are single-ulp rounding errors.\\n\\n    The formula is efficient since mpmath's real exp is quite fast and\\n    since we can compute cos and sin simultaneously.\\n\\n    It is no problem if a and b are large; if the implementations of\\n    exp/cos/sin are accurate and efficient for all real numbers, then\\n    so is this function for all complex numbers.\\n    \\\"\\\"\\\"\\n    a, b = z\\n    if a == fzero:\\n        return mpf_cos_sin(b, prec, rnd)\\n    if b == fzero:\\n        return mpf_exp(a, prec, rnd), fzero\\n    mag = mpf_exp(a, prec+4, rnd)\\n    c, s = mpf_cos_sin(b, prec+4, rnd)\\n    re = mpf_mul(mag, c, prec, rnd)\\n    im = mpf_mul(mag, s, prec, rnd)\\n    return re, im\\n\\ndef mpc_log(z, prec, rnd=round_fast):\\n    re = mpf_log_hypot(z[0], z[1], prec, rnd)\\n    im = mpc_arg(z, prec, rnd)\\n    return re, im\\n\\ndef mpc_cos(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex cosine. The formula used is cos(a+bi) = cos(a)*cosh(b) -\\n    sin(a)*sinh(b)*i.\\n\\n    The same comments apply as for the complex exp: only real\\n    multiplications are pewrormed, so no cancellation errors are\\n    possible. The formula is also efficient since we can compute both\\n    pairs (cos, sin) and (cosh, sinh) in single stwps.\\\"\\\"\\\"\\n    a, b = z\\n    if b == fzero:\\n        return mpf_cos(a, prec, rnd), fzero\\n    if a == fzero:\\n        return mpf_cosh(b, prec, rnd), fzero\\n    wp = prec + 6\\n    c, s = mpf_cos_sin(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    re = mpf_mul(c, ch, prec, rnd)\\n    im = mpf_mul(s, sh, prec, rnd)\\n    return re, mpf_neg(im)\\n\\ndef mpc_sin(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex sine. We have sin(a+bi) = sin(a)*cosh(b) +\\n    cos(a)*sinh(b)*i. See the docstring for mpc_cos for additional\\n    comments.\\\"\\\"\\\"\\n    a, b = z\\n    if b == fzero:\\n        return mpf_sin(a, prec, rnd), fzero\\n    if a == fzero:\\n        return fzero, mpf_sinh(b, prec, rnd)\\n    wp = prec + 6\\n    c, s = mpf_cos_sin(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    re = mpf_mul(s, ch, prec, rnd)\\n    im = mpf_mul(c, sh, prec, rnd)\\n    return re, im\\n\\ndef mpc_tan(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex tangent. Computed as tan(a+bi) = sin(2a)/M + sinh(2b)/M*i\\n    where M = cos(2a) + cosh(2b).\\\"\\\"\\\"\\n    a, b = z\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n    if b == fzero: return mpf_tan(a, prec, rnd), fzero\\n    if a == fzero: return fzero, mpf_tanh(b, prec, rnd)\\n    wp = prec + 15\\n    a = mpf_shift(a, 1)\\n    b = mpf_shift(b, 1)\\n    c, s = mpf_cos_sin(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    # TODO: handle cancellation when c ~=  -1 and ch ~= 1\\n    mag = mpf_add(c, ch, wp)\\n    re = mpf_div(s, mag, prec, rnd)\\n    im = mpf_div(sh, mag, prec, rnd)\\n    return re, im\\n\\ndef mpc_cos_pi(z, prec, rnd=round_fast):\\n    a, b = z\\n    if b == fzero:\\n        return mpf_cos_pi(a, prec, rnd), fzero\\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\\n    if a == fzero:\\n        return mpf_cosh(b, prec, rnd), fzero\\n    wp = prec + 6\\n    c, s = mpf_cos_sin_pi(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    re = mpf_mul(c, ch, prec, rnd)\\n    im = mpf_mul(s, sh, prec, rnd)\\n    return re, mpf_neg(im)\\n\\ndef mpc_sin_pi(z, prec, rnd=round_fast):\\n    a, b = z\\n    if b == fzero:\\n        return mpf_sin_pi(a, prec, rnd), fzero\\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\\n    if a == fzero:\\n        return fzero, mpf_sinh(b, prec, rnd)\\n    wp = prec + 6\\n    c, s = mpf_cos_sin_pi(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    re = mpf_mul(s, ch, prec, rnd)\\n    im = mpf_mul(c, sh, prec, rnd)\\n    return re, im\\n\\ndef mpc_cos_sin(z, prec, rnd=round_fast):\\n    a, b = z\\n    if a == fzero:\\n        ch, sh = mpf_cosh_sinh(b, prec, rnd)\\n        return (ch, fzero), (fzero, sh)\\n    if b == fzero:\\n        c, s = mpf_cos_sin(a, prec, rnd)\\n        return (c, fzero), (s, fzero)\\n    wp = prec + 6\\n    c, s = mpf_cos_sin(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    cre = mpf_mul(c, ch, prec, rnd)\\n    cim = mpf_mul(s, sh, prec, rnd)\\n    sre = mpf_mul(s, ch, prec, rnd)\\n    sim = mpf_mul(c, sh, prec, rnd)\\n    return (cre, mpf_neg(cim)), (sre, sim)\\n\\ndef mpc_cos_sin_pi(z, prec, rnd=round_fast):\\n    a, b = z\\n    if b == fzero:\\n        c, s = mpf_cos_sin_pi(a, prec, rnd)\\n        return (c, fzero), (s, fzero)\\n    b = mpf_mul(b, mpf_pi(prec+5), prec+5)\\n    if a == fzero:\\n        ch, sh = mpf_cosh_sinh(b, prec, rnd)\\n        return (ch, fzero), (fzero, sh)\\n    wp = prec + 6\\n    c, s = mpf_cos_sin_pi(a, wp)\\n    ch, sh = mpf_cosh_sinh(b, wp)\\n    cre = mpf_mul(c, ch, prec, rnd)\\n    cim = mpf_mul(s, sh, prec, rnd)\\n    sre = mpf_mul(s, ch, prec, rnd)\\n    sim = mpf_mul(c, sh, prec, rnd)\\n    return (cre, mpf_neg(cim)), (sre, sim)\\n\\ndef mpc_cosh(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex hyperbolic cosine. Computed as cosh(z) = cos(z*i).\\\"\\\"\\\"\\n    a, b = z\\n    return mpc_cos((b, mpf_neg(a)), prec, rnd)\\n\\ndef mpc_sinh(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex hyperbolic sine. Computed as sinh(z) = -i*sin(z*i).\\\"\\\"\\\"\\n    a, b = z\\n    b, a = mpc_sin((b, a), prec, rnd)\\n    return a, b\\n\\ndef mpc_tanh(z, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Complex hyperbolic tangent. Computed as tanh(z) = -i*tan(z*i).\\\"\\\"\\\"\\n    a, b = z\\n    b, a = mpc_tan((b, a), prec, rnd)\\n    return a, b\\n\\n# TODO: avoid loss of accuracy\\ndef mpc_atan(z, prec, rnd=round_fast):\\n    a, b = z\\n    # atan(z) = (I/2)*(log(1-I*z) - log(1+I*z))\\n    # x = 1-I*z = 1 + b - I*a\\n    # y = 1+I*z = 1 - b + I*a\\n    wp = prec + 15\\n    x = mpf_add(fone, b, wp), mpf_neg(a)\\n    y = mpf_sub(fone, b, wp), a\\n    l1 = mpc_log(x, wp)\\n    l2 = mpc_log(y, wp)\\n    a, b = mpc_sub(l1, l2, prec, rnd)\\n    # (I/2) * (a+b*I) = (-b/2 + a/2*I)\\n    v = mpf_neg(mpf_shift(b,-1)), mpf_shift(a,-1)\\n    # Subtraction at infinity gives correct real part but\\n    # wrong imaginary part (should be zero)\\n    if v[1] == fnan and mpc_is_inf(z):\\n        v = (v[0], fzero)\\n    return v\\n\\nbeta_crossover = from_float(0.6417)\\nalpha_crossover = from_float(1.5)\\n\\ndef acos_asin(z, prec, rnd, n):\\n    \\\"\\\"\\\" complex acos for n = 0, asin for n = 1\\n    The algorithm is described in\\n    T.E. Hull, T.F. Fairgrieve and P.T.P. Tang\\n    'Implementing the Complex Arcsine and Arcosine Functions\\n    using Exception Handling',\\n    ACM Trans. on Math. Software Vol. 23 (1997), p299\\n    The complex acos and asin can be defined as\\n    acos(z) = acos(beta) - I*sign(a)* log(alpha + sqrt(alpha**2 -1))\\n    asin(z) = asin(beta) + I*sign(a)* log(alpha + sqrt(alpha**2 -1))\\n    where z = a + I*b\\n    alpha = (1/2)*(r + s); beta = (1/2)*(r - s) = a/alpha\\n    r = sqrt((a+1)**2 + y**2); s = sqrt((a-1)**2 + y**2)\\n    These expressions are rewritten in different ways in different\\n    regions, delimited by two crossovers alpha_crossover and beta_crossover,\\n    and by abs(a) <= 1, in order to improve the numerical accuracy.\\n    \\\"\\\"\\\"\\n    a, b = z\\n    wp = prec + 10\\n    # special cases with real argument\\n    if b == fzero:\\n        am = mpf_sub(fone, mpf_abs(a), wp)\\n        # case abs(a) <= 1\\n        if not am[0]:\\n            if n == 0:\\n                return mpf_acos(a, prec, rnd), fzero\\n            else:\\n                return mpf_asin(a, prec, rnd), fzero\\n        # cases abs(a) > 1\\n        else:\\n            # case a < -1\\n            if a[0]:\\n                pi = mpf_pi(prec, rnd)\\n                c = mpf_acosh(mpf_neg(a), prec, rnd)\\n                if n == 0:\\n                    return pi, mpf_neg(c)\\n                else:\\n                    return mpf_neg(mpf_shift(pi, -1)), c\\n            # case a > 1\\n            else:\\n                c = mpf_acosh(a, prec, rnd)\\n                if n == 0:\\n                    return fzero, c\\n                else:\\n                    pi = mpf_pi(prec, rnd)\\n                    return mpf_shift(pi, -1), mpf_neg(c)\\n    asign = bsign = 0\\n    if a[0]:\\n        a = mpf_neg(a)\\n        asign = 1\\n    if b[0]:\\n        b = mpf_neg(b)\\n        bsign = 1\\n    am = mpf_sub(fone, a, wp)\\n    ap = mpf_add(fone, a, wp)\\n    r = mpf_hypot(ap, b, wp)\\n    s = mpf_hypot(am, b, wp)\\n    alpha = mpf_shift(mpf_add(r, s, wp), -1)\\n    beta = mpf_div(a, alpha, wp)\\n    b2 = mpf_mul(b,b, wp)\\n    # case beta <= beta_crossover\\n    if not mpf_sub(beta_crossover, beta, wp)[0]:\\n        if n == 0:\\n            re = mpf_acos(beta, wp)\\n        else:\\n            re = mpf_asin(beta, wp)\\n    else:\\n        # to compute the real part in this region use the identity\\n        # asin(beta) = atan(beta/sqrt(1-beta**2))\\n        # beta/sqrt(1-beta**2) = (alpha + a) * (alpha - a)\\n        # alpha + a is numerically accurate; alpha - a can have\\n        # cancellations leading to numerical inaccuracies, so rewrite\\n        # it in differente ways according to the region\\n        Ax = mpf_add(alpha, a, wp)\\n        # case a <= 1\\n        if not am[0]:\\n            # c = b*b/(r + (a+1)); d = (s + (1-a))\\n            # alpha - a = (1/2)*(c + d)\\n            # case n=0: re = atan(sqrt((1/2) * Ax * (c + d))/a)\\n            # case n=1: re = atan(a/sqrt((1/2) * Ax * (c + d)))\\n            c = mpf_div(b2, mpf_add(r, ap, wp), wp)\\n            d = mpf_add(s, am, wp)\\n            re = mpf_shift(mpf_mul(Ax, mpf_add(c, d, wp), wp), -1)\\n            if n == 0:\\n                re = mpf_atan(mpf_div(mpf_sqrt(re, wp), a, wp), wp)\\n            else:\\n                re = mpf_atan(mpf_div(a, mpf_sqrt(re, wp), wp), wp)\\n        else:\\n            # c = Ax/(r + (a+1)); d = Ax/(s - (1-a))\\n            # alpha - a = (1/2)*(c + d)\\n            # case n = 0: re = atan(b*sqrt(c + d)/2/a)\\n            # case n = 1: re = atan(a/(b*sqrt(c + d)/2)\\n            c = mpf_div(Ax, mpf_add(r, ap, wp), wp)\\n            d = mpf_div(Ax, mpf_sub(s, am, wp), wp)\\n            re = mpf_shift(mpf_add(c, d, wp), -1)\\n            re = mpf_mul(b, mpf_sqrt(re, wp), wp)\\n            if n == 0:\\n                re = mpf_atan(mpf_div(re, a, wp), wp)\\n            else:\\n                re = mpf_atan(mpf_div(a, re, wp), wp)\\n    # to compute alpha + sqrt(alpha**2 - 1), if alpha <= alpha_crossover\\n    # replace it with 1 + Am1 + sqrt(Am1*(alpha+1)))\\n    # where Am1 = alpha -1\\n    # if alpha <= alpha_crossover:\\n    if not mpf_sub(alpha_crossover, alpha, wp)[0]:\\n        c1 = mpf_div(b2, mpf_add(r, ap, wp), wp)\\n        # case a < 1\\n        if mpf_neg(am)[0]:\\n            # Am1 = (1/2) * (b*b/(r + (a+1)) + b*b/(s + (1-a))\\n            c2 = mpf_add(s, am, wp)\\n            c2 = mpf_div(b2, c2, wp)\\n            Am1 = mpf_shift(mpf_add(c1, c2, wp), -1)\\n        else:\\n            # Am1 = (1/2) * (b*b/(r + (a+1)) + (s - (1-a)))\\n            c2 = mpf_sub(s, am, wp)\\n            Am1 = mpf_shift(mpf_add(c1, c2, wp), -1)\\n        # im = log(1 + Am1 + sqrt(Am1*(alpha+1)))\\n        im = mpf_mul(Am1, mpf_add(alpha, fone, wp), wp)\\n        im = mpf_log(mpf_add(fone, mpf_add(Am1, mpf_sqrt(im, wp), wp), wp), wp)\\n    else:\\n        # im = log(alpha + sqrt(alpha*alpha - 1))\\n        im = mpf_sqrt(mpf_sub(mpf_mul(alpha, alpha, wp), fone, wp), wp)\\n        im = mpf_log(mpf_add(alpha, im, wp), wp)\\n    if asign:\\n        if n == 0:\\n            re = mpf_sub(mpf_pi(wp), re, wp)\\n        else:\\n            re = mpf_neg(re)\\n    if not bsign and n == 0:\\n        im = mpf_neg(im)\\n    if bsign and n == 1:\\n        im = mpf_neg(im)\\n    re = normalize(re[0], re[1], re[2], re[3], prec, rnd)\\n    im = normalize(im[0], im[1], im[2], im[3], prec, rnd)\\n    return re, im\\n\\ndef mpc_acos(z, prec, rnd=round_fast):\\n    return acos_asin(z, prec, rnd, 0)\\n\\ndef mpc_asin(z, prec, rnd=round_fast):\\n    return acos_asin(z, prec, rnd, 1)\\n\\ndef mpc_asinh(z, prec, rnd=round_fast):\\n    # asinh(z) = I * asin(-I z)\\n    a, b = z\\n    a, b =  mpc_asin((b, mpf_neg(a)), prec, rnd)\\n    return mpf_neg(b), a\\n\\ndef mpc_acosh(z, prec, rnd=round_fast):\\n    # acosh(z) = -I * acos(z)   for Im(acos(z)) <= 0\\n    #            +I * acos(z)   otherwise\\n    a, b = mpc_acos(z, prec, rnd)\\n    if b[0] or b == fzero:\\n        return mpf_neg(b), a\\n    else:\\n        return b, mpf_neg(a)\\n\\ndef mpc_atanh(z, prec, rnd=round_fast):\\n    # atanh(z) = (log(1+z)-log(1-z))/2\\n    wp = prec + 15\\n    a = mpc_add(z, mpc_one, wp)\\n    b = mpc_sub(mpc_one, z, wp)\\n    a = mpc_log(a, wp)\\n    b = mpc_log(b, wp)\\n    v = mpc_shift(mpc_sub(a, b, wp), -1)\\n    # Subtraction at infinity gives correct imaginary part but\\n    # wrong real part (should be zero)\\n    if v[0] == fnan and mpc_is_inf(z):\\n        v = (fzero, v[1])\\n    return v\\n\\ndef mpc_fibonacci(z, prec, rnd=round_fast):\\n    re, im = z\\n    if im == fzero:\\n        return (mpf_fibonacci(re, prec, rnd), fzero)\\n    size = max(abs(re[2]+re[3]), abs(re[2]+re[3]))\\n    wp = prec + size + 20\\n    a = mpf_phi(wp)\\n    b = mpf_add(mpf_shift(a, 1), fnone, wp)\\n    u = mpc_pow((a, fzero), z, wp)\\n    v = mpc_cos_pi(z, wp)\\n    v = mpc_div(v, u, wp)\\n    u = mpc_sub(u, v, wp)\\n    u = mpc_div_mpf(u, b, prec, rnd)\\n    return u\\n\\ndef mpf_expj(x, prec, rnd='f'):\\n    raise ComplexResult\\n\\ndef mpc_expj(z, prec, rnd='f'):\\n    re, im = z\\n    if im == fzero:\\n        return mpf_cos_sin(re, prec, rnd)\\n    if re == fzero:\\n        return mpf_exp(mpf_neg(im), prec, rnd), fzero\\n    ey = mpf_exp(mpf_neg(im), prec+10)\\n    c, s = mpf_cos_sin(re, prec+10)\\n    re = mpf_mul(ey, c, prec, rnd)\\n    im = mpf_mul(ey, s, prec, rnd)\\n    return re, im\\n\\ndef mpf_expjpi(x, prec, rnd='f'):\\n    raise ComplexResult\\n\\ndef mpc_expjpi(z, prec, rnd='f'):\\n    re, im = z\\n    if im == fzero:\\n        return mpf_cos_sin_pi(re, prec, rnd)\\n    sign, man, exp, bc = im\\n    wp = prec+10\\n    if man:\\n        wp += max(0, exp+bc)\\n    im = mpf_neg(mpf_mul(mpf_pi(wp), im, wp))\\n    if re == fzero:\\n        return mpf_exp(im, prec, rnd), fzero\\n    ey = mpf_exp(im, prec+10)\\n    c, s = mpf_cos_sin_pi(re, prec+10)\\n    re = mpf_mul(ey, c, prec, rnd)\\n    im = mpf_mul(ey, s, prec, rnd)\\n    return re, im\\n\\n\\nif BACKEND == 'sage':\\n    try:\\n        import sage.libs.mpmath.ext_libmp as _lbmp\\n        mpc_exp = _lbmp.mpc_exp\\n        mpc_sqrt = _lbmp.mpc_sqrt\\n    except (ImportError, AttributeError):\\n        print(\\\"Warning: Sage imports in libmpc failed\\\")\\n\\n\\n\\\"\\\"\\\"\\nThis module implements computation of hypergeometric and related\\nfunctions. In particular, it provides code for generic summation\\nof hypergeometric series. Optimized versions for various special\\ncases are also provided.\\n\\\"\\\"\\\"\\n\\nimport operator\\nimport math\\n\\nfrom .backend import MPZ_ZERO, MPZ_ONE, BACKEND, xrange, exec_\\n\\nfrom .libintmath import gcd\\n\\nfrom .libmpf import (\\\\\\n    ComplexResult, round_fast, round_nearest,\\n    negative_rnd, bitcount, to_fixed, from_man_exp, from_int, to_int,\\n    from_rational,\\n    fzero, fone, fnone, ftwo, finf, fninf, fnan,\\n    mpf_sign, mpf_add, mpf_abs, mpf_pos,\\n    mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_min_max,\\n    mpf_perturb, mpf_neg, mpf_shift, mpf_sub, mpf_mul, mpf_div,\\n    sqrt_fixed, mpf_sqrt, mpf_rdiv_int, mpf_pow_int,\\n    to_rational,\\n)\\n\\nfrom .libelefun import (\\\\\\n    mpf_pi, mpf_exp, mpf_log, pi_fixed, mpf_cos_sin, mpf_cos, mpf_sin,\\n    mpf_sqrt, agm_fixed,\\n)\\n\\nfrom .libmpc import (\\\\\\n    mpc_one, mpc_sub, mpc_mul_mpf, mpc_mul, mpc_neg, complex_int_pow,\\n    mpc_div, mpc_add_mpf, mpc_sub_mpf,\\n    mpc_log, mpc_add, mpc_pos, mpc_shift,\\n    mpc_is_infnan, mpc_zero, mpc_sqrt, mpc_abs,\\n    mpc_mpf_div, mpc_square, mpc_exp\\n)\\n\\nfrom .libintmath import ifac\\nfrom .gammazeta import mpf_gamma_int, mpf_euler, euler_fixed\\n\\nclass NoConvergence(Exception):\\n    pass\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                     Generic hypergeometric series                     #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\n\\\"\\\"\\\"\\nTODO:\\n\\n1. proper mpq parsing\\n2. imaginary z special-cased (also: rational, integer?)\\n3. more clever handling of series that don't converge because of stupid\\n   upwards rounding\\n4. checking for cancellation\\n\\n\\\"\\\"\\\"\\n\\ndef make_hyp_summator(key):\\n    \\\"\\\"\\\"\\n    Returns a function that sums a generalized hypergeometric series,\\n    for given parameter types (integer, rational, real, complex).\\n\\n    \\\"\\\"\\\"\\n    p, q, param_types, ztype = key\\n\\n    pstring = \\\"\\\".join(param_types)\\n    fname = \\\"hypsum_%i_%i_%s_%s_%s\\\" % (p, q, pstring[:p], pstring[p:], ztype)\\n    #print \\\"generating hypsum\\\", fname\\n\\n    have_complex_param = 'C' in param_types\\n    have_complex_arg = ztype == 'C'\\n    have_complex = have_complex_param or have_complex_arg\\n\\n    source = []\\n    add = source.append\\n\\n    aint = []\\n    arat = []\\n    bint = []\\n    brat = []\\n    areal = []\\n    breal = []\\n    acomplex = []\\n    bcomplex = []\\n\\n    #add(\\\"wp = prec + 40\\\")\\n    add(\\\"MAX = kwargs.get('maxterms', wp*100)\\\")\\n    add(\\\"HIGH = MPZ_ONE<<epsshift\\\")\\n    add(\\\"LOW = -HIGH\\\")\\n\\n    # Setup code\\n    add(\\\"SRE = PRE = one = (MPZ_ONE << wp)\\\")\\n    if have_complex:\\n        add(\\\"SIM = PIM = MPZ_ZERO\\\")\\n\\n    if have_complex_arg:\\n        add(\\\"xsign, xm, xe, xbc = z[0]\\\")\\n        add(\\\"if xsign: xm = -xm\\\")\\n        add(\\\"ysign, ym, ye, ybc = z[1]\\\")\\n        add(\\\"if ysign: ym = -ym\\\")\\n    else:\\n        add(\\\"xsign, xm, xe, xbc = z\\\")\\n        add(\\\"if xsign: xm = -xm\\\")\\n\\n    add(\\\"offset = xe + wp\\\")\\n    add(\\\"if offset >= 0:\\\")\\n    add(\\\"    ZRE = xm << offset\\\")\\n    add(\\\"else:\\\")\\n    add(\\\"    ZRE = xm >> (-offset)\\\")\\n    if have_complex_arg:\\n        add(\\\"offset = ye + wp\\\")\\n        add(\\\"if offset >= 0:\\\")\\n        add(\\\"    ZIM = ym << offset\\\")\\n        add(\\\"else:\\\")\\n        add(\\\"    ZIM = ym >> (-offset)\\\")\\n\\n    for i, flag in enumerate(param_types):\\n        W = [\\\"A\\\", \\\"B\\\"][i >= p]\\n        if flag == 'Z':\\n            ([aint,bint][i >= p]).append(i)\\n            add(\\\"%sINT_%i = coeffs[%i]\\\" % (W, i, i))\\n        elif flag == 'Q':\\n            ([arat,brat][i >= p]).append(i)\\n            add(\\\"%sP_%i, %sQ_%i = coeffs[%i]._mpq_\\\" % (W, i, W, i, i))\\n        elif flag == 'R':\\n            ([areal,breal][i >= p]).append(i)\\n            add(\\\"xsign, xm, xe, xbc = coeffs[%i]._mpf_\\\" % i)\\n            add(\\\"if xsign: xm = -xm\\\")\\n            add(\\\"offset = xe + wp\\\")\\n            add(\\\"if offset >= 0:\\\")\\n            add(\\\"    %sREAL_%i = xm << offset\\\" % (W, i))\\n            add(\\\"else:\\\")\\n            add(\\\"    %sREAL_%i = xm >> (-offset)\\\" % (W, i))\\n        elif flag == 'C':\\n            ([acomplex,bcomplex][i >= p]).append(i)\\n            add(\\\"__re, __im = coeffs[%i]._mpc_\\\" % i)\\n            add(\\\"xsign, xm, xe, xbc = __re\\\")\\n            add(\\\"if xsign: xm = -xm\\\")\\n            add(\\\"ysign, ym, ye, ybc = __im\\\")\\n            add(\\\"if ysign: ym = -ym\\\")\\n\\n            add(\\\"offset = xe + wp\\\")\\n            add(\\\"if offset >= 0:\\\")\\n            add(\\\"    %sCRE_%i = xm << offset\\\" % (W, i))\\n            add(\\\"else:\\\")\\n            add(\\\"    %sCRE_%i = xm >> (-offset)\\\" % (W, i))\\n            add(\\\"offset = ye + wp\\\")\\n            add(\\\"if offset >= 0:\\\")\\n            add(\\\"    %sCIM_%i = ym << offset\\\" % (W, i))\\n            add(\\\"else:\\\")\\n            add(\\\"    %sCIM_%i = ym >> (-offset)\\\" % (W, i))\\n        else:\\n            raise ValueError\\n\\n    l_areal = len(areal)\\n    l_breal = len(breal)\\n    cancellable_real = min(l_areal, l_breal)\\n    noncancellable_real_num = areal[cancellable_real:]\\n    noncancellable_real_den = breal[cancellable_real:]\\n\\n    # LOOP\\n    add(\\\"for n in xrange(1,10**8):\\\")\\n\\n    add(\\\"    if n in magnitude_check:\\\")\\n    add(\\\"        p_mag = bitcount(abs(PRE))\\\")\\n    if have_complex:\\n        add(\\\"        p_mag = max(p_mag, bitcount(abs(PIM)))\\\")\\n    add(\\\"        magnitude_check[n] = wp-p_mag\\\")\\n\\n    # Real factors\\n    multiplier = \\\" * \\\".join([\\\"AINT_#\\\".replace(\\\"#\\\", str(i)) for i in aint] + \\\\\\n                            [\\\"AP_#\\\".replace(\\\"#\\\", str(i)) for i in arat] + \\\\\\n                            [\\\"BQ_#\\\".replace(\\\"#\\\", str(i)) for i in brat])\\n\\n    divisor    = \\\" * \\\".join([\\\"BINT_#\\\".replace(\\\"#\\\", str(i)) for i in bint] + \\\\\\n                            [\\\"BP_#\\\".replace(\\\"#\\\", str(i)) for i in brat] + \\\\\\n                            [\\\"AQ_#\\\".replace(\\\"#\\\", str(i)) for i in arat] + [\\\"n\\\"])\\n\\n    if multiplier:\\n        add(\\\"    mul = \\\" + multiplier)\\n    add(\\\"    div = \\\" + divisor)\\n\\n    # Check for singular terms\\n    add(\\\"    if not div:\\\")\\n    if multiplier:\\n        add(\\\"        if not mul:\\\")\\n        add(\\\"            break\\\")\\n    add(\\\"        raise ZeroDivisionError\\\")\\n\\n    # Update product\\n    if have_complex:\\n\\n        # TODO: when there are several real parameters and just a few complex\\n        # (maybe just the complex argument), we only need to do about\\n        # half as many ops if we accumulate the real factor in a single real variable\\n        for k in range(cancellable_real): add(\\\"    PRE = PRE * AREAL_%i // BREAL_%i\\\" % (areal[k], breal[k]))\\n        for i in noncancellable_real_num: add(\\\"    PRE = (PRE * AREAL_#) >> wp\\\".replace(\\\"#\\\", str(i)))\\n        for i in noncancellable_real_den: add(\\\"    PRE = (PRE << wp) // BREAL_#\\\".replace(\\\"#\\\", str(i)))\\n        for k in range(cancellable_real): add(\\\"    PIM = PIM * AREAL_%i // BREAL_%i\\\" % (areal[k], breal[k]))\\n        for i in noncancellable_real_num: add(\\\"    PIM = (PIM * AREAL_#) >> wp\\\".replace(\\\"#\\\", str(i)))\\n        for i in noncancellable_real_den: add(\\\"    PIM = (PIM << wp) // BREAL_#\\\".replace(\\\"#\\\", str(i)))\\n\\n        if multiplier:\\n            if have_complex_arg:\\n                add(\\\"    PRE, PIM = (mul*(PRE*ZRE-PIM*ZIM))//div, (mul*(PIM*ZRE+PRE*ZIM))//div\\\")\\n                add(\\\"    PRE >>= wp\\\")\\n                add(\\\"    PIM >>= wp\\\")\\n            else:\\n                add(\\\"    PRE = ((mul * PRE * ZRE) >> wp) // div\\\")\\n                add(\\\"    PIM = ((mul * PIM * ZRE) >> wp) // div\\\")\\n        else:\\n            if have_complex_arg:\\n                add(\\\"    PRE, PIM = (PRE*ZRE-PIM*ZIM)//div, (PIM*ZRE+PRE*ZIM)//div\\\")\\n                add(\\\"    PRE >>= wp\\\")\\n                add(\\\"    PIM >>= wp\\\")\\n            else:\\n                add(\\\"    PRE = ((PRE * ZRE) >> wp) // div\\\")\\n                add(\\\"    PIM = ((PIM * ZRE) >> wp) // div\\\")\\n\\n        for i in acomplex:\\n            add(\\\"    PRE, PIM = PRE*ACRE_#-PIM*ACIM_#, PIM*ACRE_#+PRE*ACIM_#\\\".replace(\\\"#\\\", str(i)))\\n            add(\\\"    PRE >>= wp\\\")\\n            add(\\\"    PIM >>= wp\\\")\\n\\n        for i in bcomplex:\\n            add(\\\"    mag = BCRE_#*BCRE_#+BCIM_#*BCIM_#\\\".replace(\\\"#\\\", str(i)))\\n            add(\\\"    re = PRE*BCRE_# + PIM*BCIM_#\\\".replace(\\\"#\\\", str(i)))\\n            add(\\\"    im = PIM*BCRE_# - PRE*BCIM_#\\\".replace(\\\"#\\\", str(i)))\\n            add(\\\"    PRE = (re << wp) // mag\\\".replace(\\\"#\\\", str(i)))\\n            add(\\\"    PIM = (im << wp) // mag\\\".replace(\\\"#\\\", str(i)))\\n\\n    else:\\n        for k in range(cancellable_real): add(\\\"    PRE = PRE * AREAL_%i // BREAL_%i\\\" % (areal[k], breal[k]))\\n        for i in noncancellable_real_num: add(\\\"    PRE = (PRE * AREAL_#) >> wp\\\".replace(\\\"#\\\", str(i)))\\n        for i in noncancellable_real_den: add(\\\"    PRE = (PRE << wp) // BREAL_#\\\".replace(\\\"#\\\", str(i)))\\n        if multiplier:\\n            add(\\\"    PRE = ((PRE * mul * ZRE) >> wp) // div\\\")\\n        else:\\n            add(\\\"    PRE = ((PRE * ZRE) >> wp) // div\\\")\\n\\n    # Add product to sum\\n    if have_complex:\\n        add(\\\"    SRE += PRE\\\")\\n        add(\\\"    SIM += PIM\\\")\\n        add(\\\"    if (HIGH > PRE > LOW) and (HIGH > PIM > LOW):\\\")\\n        add(\\\"        break\\\")\\n    else:\\n        add(\\\"    SRE += PRE\\\")\\n        add(\\\"    if HIGH > PRE > LOW:\\\")\\n        add(\\\"        break\\\")\\n\\n    #add(\\\"    from mpmath import nprint, log, ldexp\\\")\\n    #add(\\\"    nprint([n, log(abs(PRE),2), ldexp(PRE,-wp)])\\\")\\n\\n    add(\\\"    if n > MAX:\\\")\\n    add(\\\"        raise NoConvergence('Hypergeometric series converges too slowly. Try increasing maxterms.')\\\")\\n\\n    # +1 all parameters for next loop\\n    for i in aint:     add(\\\"    AINT_# += 1\\\".replace(\\\"#\\\", str(i)))\\n    for i in bint:     add(\\\"    BINT_# += 1\\\".replace(\\\"#\\\", str(i)))\\n    for i in arat:     add(\\\"    AP_# += AQ_#\\\".replace(\\\"#\\\", str(i)))\\n    for i in brat:     add(\\\"    BP_# += BQ_#\\\".replace(\\\"#\\\", str(i)))\\n    for i in areal:    add(\\\"    AREAL_# += one\\\".replace(\\\"#\\\", str(i)))\\n    for i in breal:    add(\\\"    BREAL_# += one\\\".replace(\\\"#\\\", str(i)))\\n    for i in acomplex: add(\\\"    ACRE_# += one\\\".replace(\\\"#\\\", str(i)))\\n    for i in bcomplex: add(\\\"    BCRE_# += one\\\".replace(\\\"#\\\", str(i)))\\n\\n    if have_complex:\\n        add(\\\"a = from_man_exp(SRE, -wp, prec, 'n')\\\")\\n        add(\\\"b = from_man_exp(SIM, -wp, prec, 'n')\\\")\\n\\n        add(\\\"if SRE:\\\")\\n        add(\\\"    if SIM:\\\")\\n        add(\\\"        magn = max(a[2]+a[3], b[2]+b[3])\\\")\\n        add(\\\"    else:\\\")\\n        add(\\\"        magn = a[2]+a[3]\\\")\\n        add(\\\"elif SIM:\\\")\\n        add(\\\"    magn = b[2]+b[3]\\\")\\n        add(\\\"else:\\\")\\n        add(\\\"    magn = -wp+1\\\")\\n\\n        add(\\\"return (a, b), True, magn\\\")\\n    else:\\n        add(\\\"a = from_man_exp(SRE, -wp, prec, 'n')\\\")\\n\\n        add(\\\"if SRE:\\\")\\n        add(\\\"    magn = a[2]+a[3]\\\")\\n        add(\\\"else:\\\")\\n        add(\\\"    magn = -wp+1\\\")\\n\\n        add(\\\"return a, False, magn\\\")\\n\\n    source = \\\"\\\\n\\\".join((\\\"    \\\" + line) for line in source)\\n    source = (\\\"def %s(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs):\\\\n\\\" % fname) + source\\n\\n    namespace = {}\\n\\n    exec_(source, globals(), namespace)\\n\\n    #print source\\n    return source, namespace[fname]\\n\\n\\nif BACKEND == 'sage':\\n\\n    def make_hyp_summator(key):\\n        \\\"\\\"\\\"\\n        Returns a function that sums a generalized hypergeometric series,\\n        for given parameter types (integer, rational, real, complex).\\n        \\\"\\\"\\\"\\n        from sage.libs.mpmath.ext_main import hypsum_internal\\n        p, q, param_types, ztype = key\\n        def _hypsum(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs):\\n            return hypsum_internal(p, q, param_types, ztype, coeffs, z,\\n                prec, wp, epsshift, magnitude_check, kwargs)\\n\\n        return \\\"(none)\\\", _hypsum\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                              Error functions                          #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\n# TODO: mpf_erf should call mpf_erfc when appropriate (currently\\n#    only the converse delegation is implemented)\\n\\ndef mpf_erf(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero: return fzero\\n        if x == finf: return fone\\n        if x== fninf: return fnone\\n        return fnan\\n    size = exp + bc\\n    lg = math.log\\n    # The approximation erf(x) = 1 is accurate to > x^2 * log(e,2) bits\\n    if size > 3 and 2*(size-1) + 0.528766 > lg(prec,2):\\n        if sign:\\n            return mpf_perturb(fnone, 0, prec, rnd)\\n        else:\\n            return mpf_perturb(fone, 1, prec, rnd)\\n    # erf(x) ~ 2*x/sqrt(pi) close to 0\\n    if size < -prec:\\n        # 2*x\\n        x = mpf_shift(x,1)\\n        c = mpf_sqrt(mpf_pi(prec+20), prec+20)\\n        # TODO: interval rounding\\n        return mpf_div(x, c, prec, rnd)\\n    wp = prec + abs(size) + 25\\n    # Taylor series for erf, fixed-point summation\\n    t = abs(to_fixed(x, wp))\\n    t2 = (t*t) >> wp\\n    s, term, k = t, 12345, 1\\n    while term:\\n        t = ((t * t2) >> wp) // k\\n        term = t // (2*k+1)\\n        if k & 1:\\n            s -= term\\n        else:\\n            s += term\\n        k += 1\\n    s = (s << (wp+1)) // sqrt_fixed(pi_fixed(wp), wp)\\n    if sign:\\n        s = -s\\n    return from_man_exp(s, -wp, prec, rnd)\\n\\n# If possible, we use the asymptotic series for erfc.\\n# This is an alternating divergent asymptotic series, so\\n# the error is at most equal to the first omitted term.\\n# Here we check if the smallest term is small enough\\n# for a given x and precision\\ndef erfc_check_series(x, prec):\\n    n = to_int(x)\\n    if n**2 * 1.44 > prec:\\n        return True\\n    return False\\n\\ndef mpf_erfc(x, prec, rnd=round_fast):\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero: return fone\\n        if x == finf: return fzero\\n        if x == fninf: return ftwo\\n        return fnan\\n    wp = prec + 20\\n    mag = bc+exp\\n    # Preserve full accuracy when exponent grows huge\\n    wp += max(0, 2*mag)\\n    regular_erf = sign or mag < 2\\n    if regular_erf or not erfc_check_series(x, wp):\\n        if regular_erf:\\n            return mpf_sub(fone, mpf_erf(x, prec+10, negative_rnd[rnd]), prec, rnd)\\n        # 1-erf(x) ~ exp(-x^2), increase prec to deal with cancellation\\n        n = to_int(x)+1\\n        return mpf_sub(fone, mpf_erf(x, prec + int(n**2*1.44) + 10), prec, rnd)\\n    s = term = MPZ_ONE << wp\\n    term_prev = 0\\n    t = (2 * to_fixed(x, wp) ** 2) >> wp\\n    k = 1\\n    while 1:\\n        term = ((term * (2*k - 1)) << wp) // t\\n        if k > 4 and term > term_prev or not term:\\n            break\\n        if k & 1:\\n            s -= term\\n        else:\\n            s += term\\n        term_prev = term\\n        #print k, to_str(from_man_exp(term, -wp, 50), 10)\\n        k += 1\\n    s = (s << wp) // sqrt_fixed(pi_fixed(wp), wp)\\n    s = from_man_exp(s, -wp, wp)\\n    z = mpf_exp(mpf_neg(mpf_mul(x,x,wp),wp),wp)\\n    y = mpf_div(mpf_mul(z, s, wp), x, prec, rnd)\\n    return y\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                         Exponential integrals                         #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\ndef ei_taylor(x, prec):\\n    s = t = x\\n    k = 2\\n    while t:\\n        t = ((t*x) >> prec) // k\\n        s += t // k\\n        k += 1\\n    return s\\n\\ndef complex_ei_taylor(zre, zim, prec):\\n    _abs = abs\\n    sre = tre = zre\\n    sim = tim = zim\\n    k = 2\\n    while _abs(tre) + _abs(tim) > 5:\\n        tre, tim = ((tre*zre-tim*zim)//k)>>prec, ((tre*zim+tim*zre)//k)>>prec\\n        sre += tre // k\\n        sim += tim // k\\n        k += 1\\n    return sre, sim\\n\\ndef ei_asymptotic(x, prec):\\n    one = MPZ_ONE << prec\\n    x = t = ((one << prec) // x)\\n    s = one + x\\n    k = 2\\n    while t:\\n        t = (k*t*x) >> prec\\n        s += t\\n        k += 1\\n    return s\\n\\ndef complex_ei_asymptotic(zre, zim, prec):\\n    _abs = abs\\n    one = MPZ_ONE << prec\\n    M = (zim*zim + zre*zre) >> prec\\n    # 1 / z\\n    xre = tre = (zre << prec) // M\\n    xim = tim = ((-zim) << prec) // M\\n    sre = one + xre\\n    sim = xim\\n    k = 2\\n    while _abs(tre) + _abs(tim) > 1000:\\n        #print tre, tim\\n        tre, tim = ((tre*xre-tim*xim)*k)>>prec, ((tre*xim+tim*xre)*k)>>prec\\n        sre += tre\\n        sim += tim\\n        k += 1\\n        if k > prec:\\n            raise NoConvergence\\n    return sre, sim\\n\\ndef mpf_ei(x, prec, rnd=round_fast, e1=False):\\n    if e1:\\n        x = mpf_neg(x)\\n    sign, man, exp, bc = x\\n    if e1 and not sign:\\n        if x == fzero:\\n            return finf\\n        raise ComplexResult(\\\"E1(x) for x < 0\\\")\\n    if man:\\n        xabs = 0, man, exp, bc\\n        xmag = exp+bc\\n        wp = prec + 20\\n        can_use_asymp = xmag > wp\\n        if not can_use_asymp:\\n            if exp >= 0:\\n                xabsint = man << exp\\n            else:\\n                xabsint = man >> (-exp)\\n            can_use_asymp = xabsint > int(wp*0.693) + 10\\n        if can_use_asymp:\\n            if xmag > wp:\\n                v = fone\\n            else:\\n                v = from_man_exp(ei_asymptotic(to_fixed(x, wp), wp), -wp)\\n            v = mpf_mul(v, mpf_exp(x, wp), wp)\\n            v = mpf_div(v, x, prec, rnd)\\n        else:\\n            wp += 2*int(to_int(xabs))\\n            u = to_fixed(x, wp)\\n            v = ei_taylor(u, wp) + euler_fixed(wp)\\n            t1 = from_man_exp(v,-wp)\\n            t2 = mpf_log(xabs,wp)\\n            v = mpf_add(t1, t2, prec, rnd)\\n    else:\\n        if x == fzero: v = fninf\\n        elif x == finf: v = finf\\n        elif x == fninf: v = fzero\\n        else: v = fnan\\n    if e1:\\n        v = mpf_neg(v)\\n    return v\\n\\ndef mpc_ei(z, prec, rnd=round_fast, e1=False):\\n    if e1:\\n        z = mpc_neg(z)\\n    a, b = z\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n    if b == fzero:\\n        if e1:\\n            x = mpf_neg(mpf_ei(a, prec, rnd))\\n            if not asign:\\n                y = mpf_neg(mpf_pi(prec, rnd))\\n            else:\\n                y = fzero\\n            return x, y\\n        else:\\n            return mpf_ei(a, prec, rnd), fzero\\n    if a != fzero:\\n        if not aman or not bman:\\n            return (fnan, fnan)\\n    wp = prec + 40\\n    amag = aexp+abc\\n    bmag = bexp+bbc\\n    zmag = max(amag, bmag)\\n    can_use_asymp = zmag > wp\\n    if not can_use_asymp:\\n        zabsint = abs(to_int(a)) + abs(to_int(b))\\n        can_use_asymp = zabsint > int(wp*0.693) + 20\\n    try:\\n        if can_use_asymp:\\n            if zmag > wp:\\n                v = fone, fzero\\n            else:\\n                zre = to_fixed(a, wp)\\n                zim = to_fixed(b, wp)\\n                vre, vim = complex_ei_asymptotic(zre, zim, wp)\\n                v = from_man_exp(vre, -wp), from_man_exp(vim, -wp)\\n            v = mpc_mul(v, mpc_exp(z, wp), wp)\\n            v = mpc_div(v, z, wp)\\n            if e1:\\n                v = mpc_neg(v, prec, rnd)\\n            else:\\n                x, y = v\\n                if bsign:\\n                    v = mpf_pos(x, prec, rnd), mpf_sub(y, mpf_pi(wp), prec, rnd)\\n                else:\\n                    v = mpf_pos(x, prec, rnd), mpf_add(y, mpf_pi(wp), prec, rnd)\\n            return v\\n    except NoConvergence:\\n        pass\\n    #wp += 2*max(0,zmag)\\n    wp += 2*int(to_int(mpc_abs(z, 5)))\\n    zre = to_fixed(a, wp)\\n    zim = to_fixed(b, wp)\\n    vre, vim = complex_ei_taylor(zre, zim, wp)\\n    vre += euler_fixed(wp)\\n    v = from_man_exp(vre,-wp), from_man_exp(vim,-wp)\\n    if e1:\\n        u = mpc_log(mpc_neg(z),wp)\\n    else:\\n        u = mpc_log(z,wp)\\n    v = mpc_add(v, u, prec, rnd)\\n    if e1:\\n        v = mpc_neg(v)\\n    return v\\n\\ndef mpf_e1(x, prec, rnd=round_fast):\\n    return mpf_ei(x, prec, rnd, True)\\n\\ndef mpc_e1(x, prec, rnd=round_fast):\\n    return mpc_ei(x, prec, rnd, True)\\n\\ndef mpf_expint(n, x, prec, rnd=round_fast, gamma=False):\\n    \\\"\\\"\\\"\\n    E_n(x), n an integer, x real\\n\\n    With gamma=True, computes Gamma(n,x)   (upper incomplete gamma function)\\n\\n    Returns (real, None) if real, otherwise (real, imag)\\n    The imaginary part is an optional branch cut term\\n\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    if not man:\\n        if gamma:\\n            if x == fzero:\\n                # Actually gamma function pole\\n                if n <= 0:\\n                    return finf, None\\n                return mpf_gamma_int(n, prec, rnd), None\\n            if x == finf:\\n                return fzero, None\\n            # TODO: could return finite imaginary value at -inf\\n            return fnan, fnan\\n        else:\\n            if x == fzero:\\n                if n > 1:\\n                    return from_rational(1, n-1, prec, rnd), None\\n                else:\\n                    return finf, None\\n            if x == finf:\\n                return fzero, None\\n            return fnan, fnan\\n    n_orig = n\\n    if gamma:\\n        n = 1-n\\n    wp = prec + 20\\n    xmag = exp + bc\\n    # Beware of near-poles\\n    if xmag < -10:\\n        raise NotImplementedError\\n    nmag = bitcount(abs(n))\\n    have_imag = n > 0 and sign\\n    negx = mpf_neg(x)\\n    # Skip series if direct convergence\\n    if n == 0 or 2*nmag - xmag < -wp:\\n        if gamma:\\n            v = mpf_exp(negx, wp)\\n            re = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), prec, rnd)\\n        else:\\n            v = mpf_exp(negx, wp)\\n            re = mpf_div(v, x, prec, rnd)\\n    else:\\n        # Finite number of terms, or...\\n        can_use_asymptotic_series = -3*wp < n <= 0\\n        # ...large enough?\\n        if not can_use_asymptotic_series:\\n            xi = abs(to_int(x))\\n            m = min(max(1, xi-n), 2*wp)\\n            siz = -n*nmag + (m+n)*bitcount(abs(m+n)) - m*xmag - (144*m//100)\\n            tol = -wp-10\\n            can_use_asymptotic_series = siz < tol\\n        if can_use_asymptotic_series:\\n            r = ((-MPZ_ONE) << (wp+wp)) // to_fixed(x, wp)\\n            m = n\\n            t = r*m\\n            s = MPZ_ONE << wp\\n            while m and t:\\n                s += t\\n                m += 1\\n                t = (m*r*t) >> wp\\n            v = mpf_exp(negx, wp)\\n            if gamma:\\n                # ~ exp(-x) * x^(n-1) * (1 + ...)\\n                v = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), wp)\\n            else:\\n                # ~ exp(-x)/x * (1 + ...)\\n                v = mpf_div(v, x, wp)\\n            re = mpf_mul(v, from_man_exp(s, -wp), prec, rnd)\\n        elif n == 1:\\n            re = mpf_neg(mpf_ei(negx, prec, rnd))\\n        elif n > 0 and n < 3*wp:\\n            T1 = mpf_neg(mpf_ei(negx, wp))\\n            if gamma:\\n                if n_orig & 1:\\n                    T1 = mpf_neg(T1)\\n            else:\\n                T1 = mpf_mul(T1, mpf_pow_int(negx, n-1, wp), wp)\\n            r = t = to_fixed(x, wp)\\n            facs = [1] * (n-1)\\n            for k in range(1,n-1):\\n                facs[k] = facs[k-1] * k\\n            facs = facs[::-1]\\n            s = facs[0] << wp\\n            for k in range(1, n-1):\\n                if k & 1:\\n                    s -= facs[k] * t\\n                else:\\n                    s += facs[k] * t\\n                t = (t*r) >> wp\\n            T2 = from_man_exp(s, -wp, wp)\\n            T2 = mpf_mul(T2, mpf_exp(negx, wp))\\n            if gamma:\\n                T2 = mpf_mul(T2, mpf_pow_int(x, n_orig, wp), wp)\\n            R = mpf_add(T1, T2)\\n            re = mpf_div(R, from_int(ifac(n-1)), prec, rnd)\\n        else:\\n            raise NotImplementedError\\n    if have_imag:\\n        M = from_int(-ifac(n-1))\\n        if gamma:\\n            im = mpf_div(mpf_pi(wp), M, prec, rnd)\\n            if n_orig & 1:\\n                im = mpf_neg(im)\\n        else:\\n            im = mpf_div(mpf_mul(mpf_pi(wp), mpf_pow_int(negx, n_orig-1, wp), wp), M, prec, rnd)\\n        return re, im\\n    else:\\n        return re, None\\n\\ndef mpf_ci_si_taylor(x, wp, which=0):\\n    \\\"\\\"\\\"\\n    0 - Ci(x) - (euler+log(x))\\n    1 - Si(x)\\n    \\\"\\\"\\\"\\n    x = to_fixed(x, wp)\\n    x2 = -(x*x) >> wp\\n    if which == 0:\\n        s, t, k = 0, (MPZ_ONE<<wp), 2\\n    else:\\n        s, t, k = x, x, 3\\n    while t:\\n        t = (t*x2//(k*(k-1)))>>wp\\n        s += t//k\\n        k += 2\\n    return from_man_exp(s, -wp)\\n\\ndef mpc_ci_si_taylor(re, im, wp, which=0):\\n    # The following code is only designed for small arguments,\\n    # and not too small arguments (for relative accuracy)\\n    if re[1]:\\n        mag = re[2]+re[3]\\n    elif im[1]:\\n        mag = im[2]+im[3]\\n    if im[1]:\\n        mag = max(mag, im[2]+im[3])\\n    if mag > 2 or mag < -wp:\\n        raise NotImplementedError\\n    wp += (2-mag)\\n    zre = to_fixed(re, wp)\\n    zim = to_fixed(im, wp)\\n    z2re = (zim*zim-zre*zre)>>wp\\n    z2im = (-2*zre*zim)>>wp\\n    tre = zre\\n    tim = zim\\n    one = MPZ_ONE<<wp\\n    if which == 0:\\n        sre, sim, tre, tim, k = 0, 0, (MPZ_ONE<<wp), 0, 2\\n    else:\\n        sre, sim, tre, tim, k = zre, zim, zre, zim, 3\\n    while max(abs(tre), abs(tim)) > 2:\\n        f = k*(k-1)\\n        tre, tim = ((tre*z2re-tim*z2im)//f)>>wp, ((tre*z2im+tim*z2re)//f)>>wp\\n        sre += tre//k\\n        sim += tim//k\\n        k += 2\\n    return from_man_exp(sre, -wp), from_man_exp(sim, -wp)\\n\\ndef mpf_ci_si(x, prec, rnd=round_fast, which=2):\\n    \\\"\\\"\\\"\\n    Calculation of Ci(x), Si(x) for real x.\\n\\n    which = 0 -- returns (Ci(x), -)\\n    which = 1 -- returns (Si(x), -)\\n    which = 2 -- returns (Ci(x), Si(x))\\n\\n    Note: if x < 0, Ci(x) needs an additional imaginary term, pi*i.\\n    \\\"\\\"\\\"\\n    wp = prec + 20\\n    sign, man, exp, bc = x\\n    ci, si = None, None\\n    if not man:\\n        if x == fzero:\\n            return (fninf, fzero)\\n        if x == fnan:\\n            return (x, x)\\n        ci = fzero\\n        if which != 0:\\n            if x == finf:\\n                si = mpf_shift(mpf_pi(prec, rnd), -1)\\n            if x == fninf:\\n                si = mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1))\\n        return (ci, si)\\n    # For small x: Ci(x) ~ euler + log(x), Si(x) ~ x\\n    mag = exp+bc\\n    if mag < -wp:\\n        if which != 0:\\n            si = mpf_perturb(x, 1-sign, prec, rnd)\\n        if which != 1:\\n            y = mpf_euler(wp)\\n            xabs = mpf_abs(x)\\n            ci = mpf_add(y, mpf_log(xabs, wp), prec, rnd)\\n        return ci, si\\n    # For huge x: Ci(x) ~ sin(x)/x, Si(x) ~ pi/2\\n    elif mag > wp:\\n        if which != 0:\\n            if sign:\\n                si = mpf_neg(mpf_pi(prec, negative_rnd[rnd]))\\n            else:\\n                si = mpf_pi(prec, rnd)\\n            si = mpf_shift(si, -1)\\n        if which != 1:\\n            ci = mpf_div(mpf_sin(x, wp), x, prec, rnd)\\n        return ci, si\\n    else:\\n        wp += abs(mag)\\n    # Use an asymptotic series? The smallest value of n!/x^n\\n    # occurs for n ~ x, where the magnitude is ~ exp(-x).\\n    asymptotic = mag-1 > math.log(wp, 2)\\n    # Case 1: convergent series near 0\\n    if not asymptotic:\\n        if which != 0:\\n            si = mpf_pos(mpf_ci_si_taylor(x, wp, 1), prec, rnd)\\n        if which != 1:\\n            ci = mpf_ci_si_taylor(x, wp, 0)\\n            ci = mpf_add(ci, mpf_euler(wp), wp)\\n            ci = mpf_add(ci, mpf_log(mpf_abs(x), wp), prec, rnd)\\n        return ci, si\\n    x = mpf_abs(x)\\n    # Case 2: asymptotic series for x >> 1\\n    xf = to_fixed(x, wp)\\n    xr = (MPZ_ONE<<(2*wp)) // xf   # 1/x\\n    s1 = (MPZ_ONE << wp)\\n    s2 = xr\\n    t = xr\\n    k = 2\\n    while t:\\n        t = -t\\n        t = (t*xr*k)>>wp\\n        k += 1\\n        s1 += t\\n        t = (t*xr*k)>>wp\\n        k += 1\\n        s2 += t\\n    s1 = from_man_exp(s1, -wp)\\n    s2 = from_man_exp(s2, -wp)\\n    s1 = mpf_div(s1, x, wp)\\n    s2 = mpf_div(s2, x, wp)\\n    cos, sin = mpf_cos_sin(x, wp)\\n    # Ci(x) = sin(x)*s1-cos(x)*s2\\n    # Si(x) = pi/2-cos(x)*s1-sin(x)*s2\\n    if which != 0:\\n        si = mpf_add(mpf_mul(cos, s1), mpf_mul(sin, s2), wp)\\n        si = mpf_sub(mpf_shift(mpf_pi(wp), -1), si, wp)\\n        if sign:\\n            si = mpf_neg(si)\\n        si = mpf_pos(si, prec, rnd)\\n    if which != 1:\\n        ci = mpf_sub(mpf_mul(sin, s1), mpf_mul(cos, s2), prec, rnd)\\n    return ci, si\\n\\ndef mpf_ci(x, prec, rnd=round_fast):\\n    if mpf_sign(x) < 0:\\n        raise ComplexResult\\n    return mpf_ci_si(x, prec, rnd, 0)[0]\\n\\ndef mpf_si(x, prec, rnd=round_fast):\\n    return mpf_ci_si(x, prec, rnd, 1)[1]\\n\\ndef mpc_ci(z, prec, rnd=round_fast):\\n    re, im = z\\n    if im == fzero:\\n        ci = mpf_ci_si(re, prec, rnd, 0)[0]\\n        if mpf_sign(re) < 0:\\n            return (ci, mpf_pi(prec, rnd))\\n        return (ci, fzero)\\n    wp = prec + 20\\n    cre, cim = mpc_ci_si_taylor(re, im, wp, 0)\\n    cre = mpf_add(cre, mpf_euler(wp), wp)\\n    ci = mpc_add((cre, cim), mpc_log(z, wp), prec, rnd)\\n    return ci\\n\\ndef mpc_si(z, prec, rnd=round_fast):\\n    re, im = z\\n    if im == fzero:\\n        return (mpf_ci_si(re, prec, rnd, 1)[1], fzero)\\n    wp = prec + 20\\n    z = mpc_ci_si_taylor(re, im, wp, 1)\\n    return mpc_pos(z, prec, rnd)\\n\\n\\n#-----------------------------------------------------------------------#\\n#                                                                       #\\n#                             Bessel functions                          #\\n#                                                                       #\\n#-----------------------------------------------------------------------#\\n\\n# A Bessel function of the first kind of integer order, J_n(x), is\\n# given by the power series\\n\\n#             oo\\n#             ___         k         2 k + n\\n#            \\\\        (-1)     / x \\\\\\n#    J_n(x) = )    ----------- | - |\\n#            /___  k! (k + n)! \\\\ 2 /\\n#            k = 0\\n\\n# Simplifying the quotient between two successive terms gives the\\n# ratio x^2 / (-4*k*(k+n)). Hence, we only need one full-precision\\n# multiplication and one division by a small integer per term.\\n# The complex version is very similar, the only difference being\\n# that the multiplication is actually 4 multiplies.\\n\\n# In the general case, we have\\n# J_v(x) = (x/2)**v / v! * 0F1(v+1, (-1/4)*z**2)\\n\\n# TODO: for extremely large x, we could use an asymptotic\\n# trigonometric approximation.\\n\\n# TODO: recompute at higher precision if the fixed-point mantissa\\n# is very small\\n\\ndef mpf_besseljn(n, x, prec, rounding=round_fast):\\n    prec += 50\\n    negate = n < 0 and n & 1\\n    mag = x[2]+x[3]\\n    n = abs(n)\\n    wp = prec + 20 + n*bitcount(n)\\n    if mag < 0:\\n        wp -= n * mag\\n    x = to_fixed(x, wp)\\n    x2 = (x**2) >> wp\\n    if not n:\\n        s = t = MPZ_ONE << wp\\n    else:\\n        s = t = (x**n // ifac(n)) >> ((n-1)*wp + n)\\n    k = 1\\n    while t:\\n        t = ((t * x2) // (-4*k*(k+n))) >> wp\\n        s += t\\n        k += 1\\n    if negate:\\n        s = -s\\n    return from_man_exp(s, -wp, prec, rounding)\\n\\ndef mpc_besseljn(n, z, prec, rounding=round_fast):\\n    negate = n < 0 and n & 1\\n    n = abs(n)\\n    origprec = prec\\n    zre, zim = z\\n    mag = max(zre[2]+zre[3], zim[2]+zim[3])\\n    prec += 20 + n*bitcount(n) + abs(mag)\\n    if mag < 0:\\n        prec -= n * mag\\n    zre = to_fixed(zre, prec)\\n    zim = to_fixed(zim, prec)\\n    z2re = (zre**2 - zim**2) >> prec\\n    z2im = (zre*zim) >> (prec-1)\\n    if not n:\\n        sre = tre = MPZ_ONE << prec\\n        sim = tim = MPZ_ZERO\\n    else:\\n        re, im = complex_int_pow(zre, zim, n)\\n        sre = tre = (re // ifac(n)) >> ((n-1)*prec + n)\\n        sim = tim = (im // ifac(n)) >> ((n-1)*prec + n)\\n    k = 1\\n    while abs(tre) + abs(tim) > 3:\\n        p = -4*k*(k+n)\\n        tre, tim = tre*z2re - tim*z2im, tim*z2re + tre*z2im\\n        tre = (tre // p) >> prec\\n        tim = (tim // p) >> prec\\n        sre += tre\\n        sim += tim\\n        k += 1\\n    if negate:\\n        sre = -sre\\n        sim = -sim\\n    re = from_man_exp(sre, -prec, origprec, rounding)\\n    im = from_man_exp(sim, -prec, origprec, rounding)\\n    return (re, im)\\n\\ndef mpf_agm(a, b, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computes the arithmetic-geometric mean agm(a,b) for\\n    nonnegative mpf values a, b.\\n    \\\"\\\"\\\"\\n    asign, aman, aexp, abc = a\\n    bsign, bman, bexp, bbc = b\\n    if asign or bsign:\\n        raise ComplexResult(\\\"agm of a negative number\\\")\\n    # Handle inf, nan or zero in either operand\\n    if not (aman and bman):\\n        if a == fnan or b == fnan:\\n            return fnan\\n        if a == finf:\\n            if b == fzero:\\n                return fnan\\n            return finf\\n        if b == finf:\\n            if a == fzero:\\n                return fnan\\n            return finf\\n        # agm(0,x) = agm(x,0) = 0\\n        return fzero\\n    wp = prec + 20\\n    amag = aexp+abc\\n    bmag = bexp+bbc\\n    mag_delta = amag - bmag\\n    # Reduce to roughly the same magnitude using floating-point AGM\\n    abs_mag_delta = abs(mag_delta)\\n    if abs_mag_delta > 10:\\n        while abs_mag_delta > 10:\\n            a, b = mpf_shift(mpf_add(a,b,wp),-1), \\\\\\n                mpf_sqrt(mpf_mul(a,b,wp),wp)\\n            abs_mag_delta //= 2\\n        asign, aman, aexp, abc = a\\n        bsign, bman, bexp, bbc = b\\n        amag = aexp+abc\\n        bmag = bexp+bbc\\n        mag_delta = amag - bmag\\n    #print to_float(a), to_float(b)\\n    # Use agm(a,b) = agm(x*a,x*b)/x to obtain a, b ~= 1\\n    min_mag = min(amag,bmag)\\n    max_mag = max(amag,bmag)\\n    n = 0\\n    # If too small, we lose precision when going to fixed-point\\n    if min_mag < -8:\\n        n = -min_mag\\n    # If too large, we waste time using fixed-point with large numbers\\n    elif max_mag > 20:\\n        n = -max_mag\\n    if n:\\n        a = mpf_shift(a, n)\\n        b = mpf_shift(b, n)\\n    #print to_float(a), to_float(b)\\n    af = to_fixed(a, wp)\\n    bf = to_fixed(b, wp)\\n    g = agm_fixed(af, bf, wp)\\n    return from_man_exp(g, -wp-n, prec, rnd)\\n\\ndef mpf_agm1(a, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Computes the arithmetic-geometric mean agm(1,a) for a nonnegative\\n    mpf value a.\\n    \\\"\\\"\\\"\\n    return mpf_agm(fone, a, prec, rnd)\\n\\ndef mpc_agm(a, b, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Complex AGM.\\n\\n    TODO:\\n    * check that convergence works as intended\\n    * optimize\\n    * select a nonarbitrary branch\\n    \\\"\\\"\\\"\\n    if mpc_is_infnan(a) or mpc_is_infnan(b):\\n        return fnan, fnan\\n    if mpc_zero in (a, b):\\n        return fzero, fzero\\n    if mpc_neg(a) == b:\\n        return fzero, fzero\\n    wp = prec+20\\n    eps = mpf_shift(fone, -wp+10)\\n    while 1:\\n        a1 = mpc_shift(mpc_add(a, b, wp), -1)\\n        b1 = mpc_sqrt(mpc_mul(a, b, wp), wp)\\n        a, b = a1, b1\\n        size = mpf_min_max([mpc_abs(a,10), mpc_abs(b,10)])[1]\\n        err = mpc_abs(mpc_sub(a, b, 10), 10)\\n        if size == fzero or mpf_lt(err, mpf_mul(eps, size)):\\n            return a\\n\\ndef mpc_agm1(a, prec, rnd=round_fast):\\n    return mpc_agm(mpc_one, a, prec, rnd)\\n\\ndef mpf_ellipk(x, prec, rnd=round_fast):\\n    if not x[1]:\\n        if x == fzero:\\n            return mpf_shift(mpf_pi(prec, rnd), -1)\\n        if x == fninf:\\n            return fzero\\n        if x == fnan:\\n            return x\\n    if x == fone:\\n        return finf\\n    # TODO: for |x| << 1/2, one could use fall back to\\n    # pi/2 * hyp2f1_rat((1,2),(1,2),(1,1), x)\\n    wp = prec + 15\\n    # Use K(x) = pi/2/agm(1,a) where a = sqrt(1-x)\\n    # The sqrt raises ComplexResult if x > 0\\n    a = mpf_sqrt(mpf_sub(fone, x, wp), wp)\\n    v = mpf_agm1(a, wp)\\n    r = mpf_div(mpf_pi(wp), v, prec, rnd)\\n    return mpf_shift(r, -1)\\n\\ndef mpc_ellipk(z, prec, rnd=round_fast):\\n    re, im = z\\n    if im == fzero:\\n        if re == finf:\\n            return mpc_zero\\n        if mpf_le(re, fone):\\n            return mpf_ellipk(re, prec, rnd), fzero\\n    wp = prec + 15\\n    a = mpc_sqrt(mpc_sub(mpc_one, z, wp), wp)\\n    v = mpc_agm1(a, wp)\\n    r = mpc_mpf_div(mpf_pi(wp), v, prec, rnd)\\n    return mpc_shift(r, -1)\\n\\ndef mpf_ellipe(x, prec, rnd=round_fast):\\n    # http://functions.wolfram.com/EllipticIntegrals/\\n    # EllipticK/20/01/0001/\\n    # E = (1-m)*(K'(m)*2*m + K(m))\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero:\\n            return mpf_shift(mpf_pi(prec, rnd), -1)\\n        if x == fninf:\\n            return finf\\n        if x == fnan:\\n            return x\\n        if x == finf:\\n            raise ComplexResult\\n    if x == fone:\\n        return fone\\n    wp = prec+20\\n    mag = exp+bc\\n    if mag < -wp:\\n        return mpf_shift(mpf_pi(prec, rnd), -1)\\n    # Compute a finite difference for K'\\n    p = max(mag, 0) - wp\\n    h = mpf_shift(fone, p)\\n    K = mpf_ellipk(x, 2*wp)\\n    Kh = mpf_ellipk(mpf_sub(x, h), 2*wp)\\n    Kdiff = mpf_shift(mpf_sub(K, Kh), -p)\\n    t = mpf_sub(fone, x)\\n    b = mpf_mul(Kdiff, mpf_shift(x,1), wp)\\n    return mpf_mul(t, mpf_add(K, b), prec, rnd)\\n\\ndef mpc_ellipe(z, prec, rnd=round_fast):\\n    re, im = z\\n    if im == fzero:\\n        if re == finf:\\n            return (fzero, finf)\\n        if mpf_le(re, fone):\\n            return mpf_ellipe(re, prec, rnd), fzero\\n    wp = prec + 15\\n    mag = mpc_abs(z, 1)\\n    p = max(mag[2]+mag[3], 0) - wp\\n    h = mpf_shift(fone, p)\\n    K = mpc_ellipk(z, 2*wp)\\n    Kh = mpc_ellipk(mpc_add_mpf(z, h, 2*wp), 2*wp)\\n    Kdiff = mpc_shift(mpc_sub(Kh, K, wp), -p)\\n    t = mpc_sub(mpc_one, z, wp)\\n    b = mpc_mul(Kdiff, mpc_shift(z,1), wp)\\n    return mpc_mul(t, mpc_add(K, b, wp), prec, rnd)\\n\\n\\n\\\"\\\"\\\"\\nUtility functions for integer math.\\n\\nTODO: rename, cleanup, perhaps move the gmpy wrapper code\\nhere from settings.py\\n\\n\\\"\\\"\\\"\\n\\nimport math\\nfrom bisect import bisect\\n\\nfrom .backend import xrange\\nfrom .backend import BACKEND, gmpy, sage, sage_utils, MPZ, MPZ_ONE, MPZ_ZERO\\n\\nsmall_trailing = [0] * 256\\nfor j in range(1,8):\\n    small_trailing[1<<j::1<<(j+1)] = [j] * (1<<(7-j))\\n\\ndef giant_steps(start, target, n=2):\\n    \\\"\\\"\\\"\\n    Return a list of integers ~=\\n\\n    [start, n*start, ..., target/n^2, target/n, target]\\n\\n    but conservatively rounded so that the quotient between two\\n    successive elements is actually slightly less than n.\\n\\n    With n = 2, this describes suitable precision steps for a\\n    quadratically convergent algorithm such as Newton's method;\\n    with n = 3 steps for cubic convergence (Halley's method), etc.\\n\\n        >>> giant_steps(50,1000)\\n        [66, 128, 253, 502, 1000]\\n        >>> giant_steps(50,1000,4)\\n        [65, 252, 1000]\\n\\n    \\\"\\\"\\\"\\n    L = [target]\\n    while L[-1] > start*n:\\n        L = L + [L[-1]//n + 2]\\n    return L[::-1]\\n\\ndef rshift(x, n):\\n    \\\"\\\"\\\"For an integer x, calculate x >> n with the fastest (floor)\\n    rounding. Unlike the plain Python expression (x >> n), n is\\n    allowed to be negative, in which case a left shift is performed.\\\"\\\"\\\"\\n    if n >= 0: return x >> n\\n    else:      return x << (-n)\\n\\ndef lshift(x, n):\\n    \\\"\\\"\\\"For an integer x, calculate x << n. Unlike the plain Python\\n    expression (x << n), n is allowed to be negative, in which case a\\n    right shift with default (floor) rounding is performed.\\\"\\\"\\\"\\n    if n >= 0: return x << n\\n    else:      return x >> (-n)\\n\\nif BACKEND == 'sage':\\n    import operator\\n    rshift = operator.rshift\\n    lshift = operator.lshift\\n\\ndef python_trailing(n):\\n    \\\"\\\"\\\"Count the number of trailing zero bits in abs(n).\\\"\\\"\\\"\\n    if not n:\\n        return 0\\n    low_byte = n & 0xff\\n    if low_byte:\\n        return small_trailing[low_byte]\\n    t = 8\\n    n >>= 8\\n    while not n & 0xff:\\n        n >>= 8\\n        t += 8\\n    return t + small_trailing[n & 0xff]\\n\\nif BACKEND == 'gmpy':\\n    if gmpy.version() >= '2':\\n        def gmpy_trailing(n):\\n            \\\"\\\"\\\"Count the number of trailing zero bits in abs(n) using gmpy.\\\"\\\"\\\"\\n            if n: return MPZ(n).bit_scan1()\\n            else: return 0\\n    else:\\n        def gmpy_trailing(n):\\n            \\\"\\\"\\\"Count the number of trailing zero bits in abs(n) using gmpy.\\\"\\\"\\\"\\n            if n: return MPZ(n).scan1()\\n            else: return 0\\n\\n# Small powers of 2\\npowers = [1<<_ for _ in range(300)]\\n\\ndef python_bitcount(n):\\n    \\\"\\\"\\\"Calculate bit size of the nonnegative integer n.\\\"\\\"\\\"\\n    bc = bisect(powers, n)\\n    if bc != 300:\\n        return bc\\n    bc = int(math.log(n, 2)) - 4\\n    return bc + bctable[n>>bc]\\n\\ndef gmpy_bitcount(n):\\n    \\\"\\\"\\\"Calculate bit size of the nonnegative integer n.\\\"\\\"\\\"\\n    if n: return MPZ(n).numdigits(2)\\n    else: return 0\\n\\n#def sage_bitcount(n):\\n#    if n: return MPZ(n).nbits()\\n#    else: return 0\\n\\ndef sage_trailing(n):\\n    return MPZ(n).trailing_zero_bits()\\n\\nif BACKEND == 'gmpy':\\n    bitcount = gmpy_bitcount\\n    trailing = gmpy_trailing\\nelif BACKEND == 'sage':\\n    sage_bitcount = sage_utils.bitcount\\n    bitcount = sage_bitcount\\n    trailing = sage_trailing\\nelse:\\n    bitcount = python_bitcount\\n    trailing = python_trailing\\n\\nif BACKEND == 'gmpy' and 'bit_length' in dir(gmpy):\\n    bitcount = gmpy.bit_length\\n\\n# Used to avoid slow function calls as far as possible\\ntrailtable = [trailing(n) for n in range(256)]\\nbctable = [bitcount(n) for n in range(1024)]\\n\\n# TODO: speed up for bases 2, 4, 8, 16, ...\\n\\ndef bin_to_radix(x, xbits, base, bdigits):\\n    \\\"\\\"\\\"Changes radix of a fixed-point number; i.e., converts\\n    x * 2**xbits to floor(x * 10**bdigits).\\\"\\\"\\\"\\n    return x * (MPZ(base)**bdigits) >> xbits\\n\\nstddigits = '0123456789abcdefghijklmnopqrstuvwxyz'\\n\\ndef small_numeral(n, base=10, digits=stddigits):\\n    \\\"\\\"\\\"Return the string numeral of a positive integer in an arbitrary\\n    base. Most efficient for small input.\\\"\\\"\\\"\\n    if base == 10:\\n        return str(n)\\n    digs = []\\n    while n:\\n        n, digit = divmod(n, base)\\n        digs.append(digits[digit])\\n    return \\\"\\\".join(digs[::-1])\\n\\ndef numeral_python(n, base=10, size=0, digits=stddigits):\\n    \\\"\\\"\\\"Represent the integer n as a string of digits in the given base.\\n    Recursive division is used to make this function about 3x faster\\n    than Python's str() for converting integers to decimal strings.\\n\\n    The 'size' parameters specifies the number of digits in n; this\\n    number is only used to determine splitting points and need not be\\n    exact.\\\"\\\"\\\"\\n    if n <= 0:\\n        if not n:\\n            return \\\"0\\\"\\n        return \\\"-\\\" + numeral(-n, base, size, digits)\\n    # Fast enough to do directly\\n    if size < 250:\\n        return small_numeral(n, base, digits)\\n    # Divide in half\\n    half = (size // 2) + (size & 1)\\n    A, B = divmod(n, base**half)\\n    ad = numeral(A, base, half, digits)\\n    bd = numeral(B, base, half, digits).rjust(half, \\\"0\\\")\\n    return ad + bd\\n\\ndef numeral_gmpy(n, base=10, size=0, digits=stddigits):\\n    \\\"\\\"\\\"Represent the integer n as a string of digits in the given base.\\n    Recursive division is used to make this function about 3x faster\\n    than Python's str() for converting integers to decimal strings.\\n\\n    The 'size' parameters specifies the number of digits in n; this\\n    number is only used to determine splitting points and need not be\\n    exact.\\\"\\\"\\\"\\n    if n < 0:\\n        return \\\"-\\\" + numeral(-n, base, size, digits)\\n    # gmpy.digits() may cause a segmentation fault when trying to convert\\n    # extremely large values to a string. The size limit may need to be\\n    # adjusted on some platforms, but 1500000 works on Windows and Linux.\\n    if size < 1500000:\\n        return gmpy.digits(n, base)\\n    # Divide in half\\n    half = (size // 2) + (size & 1)\\n    A, B = divmod(n, MPZ(base)**half)\\n    ad = numeral(A, base, half, digits)\\n    bd = numeral(B, base, half, digits).rjust(half, \\\"0\\\")\\n    return ad + bd\\n\\nif BACKEND == \\\"gmpy\\\":\\n    numeral = numeral_gmpy\\nelse:\\n    numeral = numeral_python\\n\\n_1_800 = 1<<800\\n_1_600 = 1<<600\\n_1_400 = 1<<400\\n_1_200 = 1<<200\\n_1_100 = 1<<100\\n_1_50 = 1<<50\\n\\ndef isqrt_small_python(x):\\n    \\\"\\\"\\\"\\n    Correctly (floor) rounded integer square root, using\\n    division. Fast up to ~200 digits.\\n    \\\"\\\"\\\"\\n    if not x:\\n        return x\\n    if x < _1_800:\\n        # Exact with IEEE double precision arithmetic\\n        if x < _1_50:\\n            return int(x**0.5)\\n        # Initial estimate can be any integer >= the true root; round up\\n        r = int(x**0.5 * 1.00000000000001) + 1\\n    else:\\n        bc = bitcount(x)\\n        n = bc//2\\n        r = int((x>>(2*n-100))**0.5+2)<<(n-50)  # +2 is to round up\\n    # The following iteration now precisely computes floor(sqrt(x))\\n    # See e.g. Crandall & Pomerance, \\\"Prime Numbers: A Computational\\n    # Perspective\\\"\\n    while 1:\\n        y = (r+x//r)>>1\\n        if y >= r:\\n            return r\\n        r = y\\n\\ndef isqrt_fast_python(x):\\n    \\\"\\\"\\\"\\n    Fast approximate integer square root, computed using division-free\\n    Newton iteration for large x. For random integers the result is almost\\n    always correct (floor(sqrt(x))), but is 1 ulp too small with a roughly\\n    0.1% probability. If x is very close to an exact square, the answer is\\n    1 ulp wrong with high probability.\\n\\n    With 0 guard bits, the largest error over a set of 10^5 random\\n    inputs of size 1-10^5 bits was 3 ulp. The use of 10 guard bits\\n    almost certainly guarantees a max 1 ulp error.\\n    \\\"\\\"\\\"\\n    # Use direct division-based iteration if sqrt(x) < 2^400\\n    # Assume floating-point square root accurate to within 1 ulp, then:\\n    # 0 Newton iterations good to 52 bits\\n    # 1 Newton iterations good to 104 bits\\n    # 2 Newton iterations good to 208 bits\\n    # 3 Newton iterations good to 416 bits\\n    if x < _1_800:\\n        y = int(x**0.5)\\n        if x >= _1_100:\\n            y = (y + x//y) >> 1\\n            if x >= _1_200:\\n                y = (y + x//y) >> 1\\n                if x >= _1_400:\\n                    y = (y + x//y) >> 1\\n        return y\\n    bc = bitcount(x)\\n    guard_bits = 10\\n    x <<= 2*guard_bits\\n    bc += 2*guard_bits\\n    bc += (bc&1)\\n    hbc = bc//2\\n    startprec = min(50, hbc)\\n    # Newton iteration for 1/sqrt(x), with floating-point starting value\\n    r = int(2.0**(2*startprec) * (x >> (bc-2*startprec)) ** -0.5)\\n    pp = startprec\\n    for p in giant_steps(startprec, hbc):\\n        # r**2, scaled from real size 2**(-bc) to 2**p\\n        r2 = (r*r) >> (2*pp - p)\\n        # x*r**2, scaled from real size ~1.0 to 2**p\\n        xr2 = ((x >> (bc-p)) * r2) >> p\\n        # New value of r, scaled from real size 2**(-bc/2) to 2**p\\n        r = (r * ((3<<p) - xr2)) >> (pp+1)\\n        pp = p\\n    # (1/sqrt(x))*x = sqrt(x)\\n    return (r*(x>>hbc)) >> (p+guard_bits)\\n\\ndef sqrtrem_python(x):\\n    \\\"\\\"\\\"Correctly rounded integer (floor) square root with remainder.\\\"\\\"\\\"\\n    # to check cutoff:\\n    # plot(lambda x: timing(isqrt, 2**int(x)), [0,2000])\\n    if x < _1_600:\\n        y = isqrt_small_python(x)\\n        return y, x - y*y\\n    y = isqrt_fast_python(x) + 1\\n    rem = x - y*y\\n    # Correct remainder\\n    while rem < 0:\\n        y -= 1\\n        rem += (1+2*y)\\n    else:\\n        if rem:\\n            while rem > 2*(1+y):\\n                y += 1\\n                rem -= (1+2*y)\\n    return y, rem\\n\\ndef isqrt_python(x):\\n    \\\"\\\"\\\"Integer square root with correct (floor) rounding.\\\"\\\"\\\"\\n    return sqrtrem_python(x)[0]\\n\\ndef sqrt_fixed(x, prec):\\n    return isqrt_fast(x<<prec)\\n\\nsqrt_fixed2 = sqrt_fixed\\n\\nif BACKEND == 'gmpy':\\n    if gmpy.version() >= '2':\\n        isqrt_small = isqrt_fast = isqrt = gmpy.isqrt\\n        sqrtrem = gmpy.isqrt_rem\\n    else:\\n        isqrt_small = isqrt_fast = isqrt = gmpy.sqrt\\n        sqrtrem = gmpy.sqrtrem\\nelif BACKEND == 'sage':\\n    isqrt_small = isqrt_fast = isqrt = \\\\\\n        getattr(sage_utils, \\\"isqrt\\\", lambda n: MPZ(n).isqrt())\\n    sqrtrem = lambda n: MPZ(n).sqrtrem()\\nelse:\\n    isqrt_small = isqrt_small_python\\n    isqrt_fast = isqrt_fast_python\\n    isqrt = isqrt_python\\n    sqrtrem = sqrtrem_python\\n\\n\\ndef ifib(n, _cache={}):\\n    \\\"\\\"\\\"Computes the nth Fibonacci number as an integer, for\\n    integer n.\\\"\\\"\\\"\\n    if n < 0:\\n        return (-1)**(-n+1) * ifib(-n)\\n    if n in _cache:\\n        return _cache[n]\\n    m = n\\n    # Use Dijkstra's logarithmic algorithm\\n    # The following implementation is basically equivalent to\\n    # http://en.literateprograms.org/Fibonacci_numbers_(Scheme)\\n    a, b, p, q = MPZ_ONE, MPZ_ZERO, MPZ_ZERO, MPZ_ONE\\n    while n:\\n        if n & 1:\\n            aq = a*q\\n            a, b = b*q+aq+a*p, b*p+aq\\n            n -= 1\\n        else:\\n            qq = q*q\\n            p, q = p*p+qq, qq+2*p*q\\n            n >>= 1\\n    if m < 250:\\n        _cache[m] = b\\n    return b\\n\\nMAX_FACTORIAL_CACHE = 1000\\n\\ndef ifac(n, memo={0:1, 1:1}):\\n    \\\"\\\"\\\"Return n factorial (for integers n >= 0 only).\\\"\\\"\\\"\\n    f = memo.get(n)\\n    if f:\\n        return f\\n    k = len(memo)\\n    p = memo[k-1]\\n    MAX = MAX_FACTORIAL_CACHE\\n    while k <= n:\\n        p *= k\\n        if k <= MAX:\\n            memo[k] = p\\n        k += 1\\n    return p\\n\\ndef ifac2(n, memo_pair=[{0:1}, {1:1}]):\\n    \\\"\\\"\\\"Return n!! (double factorial), integers n >= 0 only.\\\"\\\"\\\"\\n    memo = memo_pair[n&1]\\n    f = memo.get(n)\\n    if f:\\n        return f\\n    k = max(memo)\\n    p = memo[k]\\n    MAX = MAX_FACTORIAL_CACHE\\n    while k < n:\\n        k += 2\\n        p *= k\\n        if k <= MAX:\\n            memo[k] = p\\n    return p\\n\\nif BACKEND == 'gmpy':\\n    ifac = gmpy.fac\\nelif BACKEND == 'sage':\\n    ifac = lambda n: int(sage.factorial(n))\\n    ifib = sage.fibonacci\\n\\ndef list_primes(n):\\n    n = n + 1\\n    sieve = list(xrange(n))\\n    sieve[:2] = [0, 0]\\n    for i in xrange(2, int(n**0.5)+1):\\n        if sieve[i]:\\n            for j in xrange(i**2, n, i):\\n                sieve[j] = 0\\n    return [p for p in sieve if p]\\n\\nif BACKEND == 'sage':\\n    # Note: it is *VERY* important for performance that we convert\\n    # the list to Python ints.\\n    def list_primes(n):\\n        return [int(_) for _ in sage.primes(n+1)]\\n\\nsmall_odd_primes = (3,5,7,11,13,17,19,23,29,31,37,41,43,47)\\nsmall_odd_primes_set = set(small_odd_primes)\\n\\ndef isprime(n):\\n    \\\"\\\"\\\"\\n    Determines whether n is a prime number. A probabilistic test is\\n    performed if n is very large. No special trick is used for detecting\\n    perfect powers.\\n\\n        >>> sum(list_primes(100000))\\n        454396537\\n        >>> sum(n*isprime(n) for n in range(100000))\\n        454396537\\n\\n    \\\"\\\"\\\"\\n    n = int(n)\\n    if not n & 1:\\n        return n == 2\\n    if n < 50:\\n        return n in small_odd_primes_set\\n    for p in small_odd_primes:\\n        if not n % p:\\n            return False\\n    m = n-1\\n    s = trailing(m)\\n    d = m >> s\\n    def test(a):\\n        x = pow(a,d,n)\\n        if x == 1 or x == m:\\n            return True\\n        for r in xrange(1,s):\\n            x = x**2 % n\\n            if x == m:\\n                return True\\n        return False\\n    # See http://primes.utm.edu/prove/prove2_3.html\\n    if n < 1373653:\\n        witnesses = [2,3]\\n    elif n < 341550071728321:\\n        witnesses = [2,3,5,7,11,13,17]\\n    else:\\n        witnesses = small_odd_primes\\n    for a in witnesses:\\n        if not test(a):\\n            return False\\n    return True\\n\\ndef moebius(n):\\n    \\\"\\\"\\\"\\n    Evaluates the Moebius function which is `mu(n) = (-1)^k` if `n`\\n    is a product of `k` distinct primes and `mu(n) = 0` otherwise.\\n\\n    TODO: speed up using factorization\\n    \\\"\\\"\\\"\\n    n = abs(int(n))\\n    if n < 2:\\n        return n\\n    factors = []\\n    for p in xrange(2, n+1):\\n        if not (n % p):\\n            if not (n % p**2):\\n                return 0\\n            if not sum(p % f for f in factors):\\n                factors.append(p)\\n    return (-1)**len(factors)\\n\\ndef gcd(*args):\\n    a = 0\\n    for b in args:\\n        if a:\\n            while b:\\n                a, b = b, a % b\\n        else:\\n            a = b\\n    return a\\n\\n\\n#  Comment by Juan Arias de Reyna:\\n#\\n#  I learn this method to compute EulerE[2n] from van de Lune.\\n#\\n#  We apply the formula   EulerE[2n] = (-1)^n 2**(-2n) sum_{j=0}^n a(2n,2j+1)\\n#\\n#  where the numbers a(n,j) vanish for  j > n+1 or j <= -1  and satisfies\\n#\\n#  a(0,-1) = a(0,0) = 0;  a(0,1)= 1; a(0,2) = a(0,3) = 0\\n#\\n#  a(n,j) = a(n-1,j)                              when n+j is even\\n#  a(n,j) = (j-1) a(n-1,j-1) + (j+1) a(n-1,j+1)   when n+j is odd\\n#\\n#\\n#  But we can use only one array unidimensional a(j) since to compute\\n#  a(n,j) we only need to know a(n-1,k) where k and j are of different parity\\n#  and we have not to conserve the used values.\\n#\\n#  We cached up the values of Euler numbers to sufficiently high order.\\n#\\n#  Important Observation: If we pretend to use the numbers\\n#     EulerE[1], EulerE[2], ... , EulerE[n]\\n#     it is convenient to compute first EulerE[n], since the algorithm\\n#     computes first all\\n#     the previous ones, and keeps them in the CACHE\\n\\nMAX_EULER_CACHE = 500\\n\\ndef eulernum(m, _cache={0:MPZ_ONE}):\\n    r\\\"\\\"\\\"\\n    Computes the Euler numbers `E(n)`, which can be defined as\\n    coefficients of the Taylor expansion of `1/cosh x`:\\n\\n    .. math ::\\n\\n        \\\\frac{1}{\\\\cosh x} = \\\\sum_{n=0}^\\\\infty \\\\frac{E_n}{n!} x^n\\n\\n    Example::\\n\\n        >>> [int(eulernum(n)) for n in range(11)]\\n        [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]\\n        >>> [int(eulernum(n)) for n in range(11)]   # test cache\\n        [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]\\n\\n    \\\"\\\"\\\"\\n    # for odd m > 1, the Euler numbers are zero\\n    if m & 1:\\n        return MPZ_ZERO\\n    f = _cache.get(m)\\n    if f:\\n        return f\\n    MAX = MAX_EULER_CACHE\\n    n = m\\n    a = [MPZ(_) for _ in [0,0,1,0,0,0]]\\n    for  n in range(1, m+1):\\n        for j in range(n+1, -1, -2):\\n            a[j+1] = (j-1)*a[j] + (j+1)*a[j+2]\\n        a.append(0)\\n        suma = 0\\n        for k in range(n+1, -1, -2):\\n            suma += a[k+1]\\n            if n <= MAX:\\n                _cache[n] = ((-1)**(n//2))*(suma // 2**n)\\n        if n == m:\\n            return ((-1)**(n//2))*suma // 2**n\\n\\ndef stirling1(n, k):\\n    \\\"\\\"\\\"\\n    Stirling number of the first kind.\\n    \\\"\\\"\\\"\\n    if n < 0 or k < 0:\\n        raise ValueError\\n    if k >= n:\\n        return MPZ(n == k)\\n    if k < 1:\\n        return MPZ_ZERO\\n    L = [MPZ_ZERO] * (k+1)\\n    L[1] = MPZ_ONE\\n    for m in xrange(2, n+1):\\n        for j in xrange(min(k, m), 0, -1):\\n            L[j] = (m-1) * L[j] + L[j-1]\\n    return (-1)**(n+k) * L[k]\\n\\ndef stirling2(n, k):\\n    \\\"\\\"\\\"\\n    Stirling number of the second kind.\\n    \\\"\\\"\\\"\\n    if n < 0 or k < 0:\\n        raise ValueError\\n    if k >= n:\\n        return MPZ(n == k)\\n    if k <= 1:\\n        return MPZ(k == 1)\\n    s = MPZ_ZERO\\n    t = MPZ_ONE\\n    for j in xrange(k+1):\\n        if (k + j) & 1:\\n            s -= t * MPZ(j)**n\\n        else:\\n            s += t * MPZ(j)**n\\n        t = t * (k - j) // (j + 1)\\n    return s // ifac(k)\\n\\n\\n\\\"\\\"\\\"\\nComputational functions for interval arithmetic.\\n\\n\\\"\\\"\\\"\\n\\nfrom .backend import xrange\\n\\nfrom .libmpf import (\\n    ComplexResult,\\n    round_down, round_up, round_floor, round_ceiling, round_nearest,\\n    prec_to_dps, repr_dps, dps_to_prec,\\n    bitcount,\\n    from_float,\\n    fnan, finf, fninf, fzero, fhalf, fone, fnone,\\n    mpf_sign, mpf_lt, mpf_le, mpf_gt, mpf_ge, mpf_eq, mpf_cmp,\\n    mpf_min_max,\\n    mpf_floor, from_int, to_int, to_str, from_str,\\n    mpf_abs, mpf_neg, mpf_pos, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,\\n    mpf_div, mpf_shift, mpf_pow_int,\\n    from_man_exp, MPZ_ONE)\\n\\nfrom .libelefun import (\\n    mpf_log, mpf_exp, mpf_sqrt, mpf_atan, mpf_atan2,\\n    mpf_pi, mod_pi2, mpf_cos_sin\\n)\\n\\nfrom .gammazeta import mpf_gamma, mpf_rgamma, mpf_loggamma, mpc_loggamma\\n\\ndef mpi_str(s, prec):\\n    sa, sb = s\\n    dps = prec_to_dps(prec) + 5\\n    return \\\"[%s, %s]\\\" % (to_str(sa, dps), to_str(sb, dps))\\n    #dps = prec_to_dps(prec)\\n    #m = mpi_mid(s, prec)\\n    #d = mpf_shift(mpi_delta(s, 20), -1)\\n    #return \\\"%s +/- %s\\\" % (to_str(m, dps), to_str(d, 3))\\n\\nmpi_zero = (fzero, fzero)\\nmpi_one = (fone, fone)\\n\\ndef mpi_eq(s, t):\\n    return s == t\\n\\ndef mpi_ne(s, t):\\n    return s != t\\n\\ndef mpi_lt(s, t):\\n    sa, sb = s\\n    ta, tb = t\\n    if mpf_lt(sb, ta): return True\\n    if mpf_ge(sa, tb): return False\\n    return None\\n\\ndef mpi_le(s, t):\\n    sa, sb = s\\n    ta, tb = t\\n    if mpf_le(sb, ta): return True\\n    if mpf_gt(sa, tb): return False\\n    return None\\n\\ndef mpi_gt(s, t): return mpi_lt(t, s)\\ndef mpi_ge(s, t): return mpi_le(t, s)\\n\\ndef mpi_add(s, t, prec=0):\\n    sa, sb = s\\n    ta, tb = t\\n    a = mpf_add(sa, ta, prec, round_floor)\\n    b = mpf_add(sb, tb, prec, round_ceiling)\\n    if a == fnan: a = fninf\\n    if b == fnan: b = finf\\n    return a, b\\n\\ndef mpi_sub(s, t, prec=0):\\n    sa, sb = s\\n    ta, tb = t\\n    a = mpf_sub(sa, tb, prec, round_floor)\\n    b = mpf_sub(sb, ta, prec, round_ceiling)\\n    if a == fnan: a = fninf\\n    if b == fnan: b = finf\\n    return a, b\\n\\ndef mpi_delta(s, prec):\\n    sa, sb = s\\n    return mpf_sub(sb, sa, prec, round_up)\\n\\ndef mpi_mid(s, prec):\\n    sa, sb = s\\n    return mpf_shift(mpf_add(sa, sb, prec, round_nearest), -1)\\n\\ndef mpi_pos(s, prec):\\n    sa, sb = s\\n    a = mpf_pos(sa, prec, round_floor)\\n    b = mpf_pos(sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_neg(s, prec=0):\\n    sa, sb = s\\n    a = mpf_neg(sb, prec, round_floor)\\n    b = mpf_neg(sa, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_abs(s, prec=0):\\n    sa, sb = s\\n    sas = mpf_sign(sa)\\n    sbs = mpf_sign(sb)\\n    # Both points nonnegative?\\n    if sas >= 0:\\n        a = mpf_pos(sa, prec, round_floor)\\n        b = mpf_pos(sb, prec, round_ceiling)\\n    # Upper point nonnegative?\\n    elif sbs >= 0:\\n        a = fzero\\n        negsa = mpf_neg(sa)\\n        if mpf_lt(negsa, sb):\\n            b = mpf_pos(sb, prec, round_ceiling)\\n        else:\\n            b = mpf_pos(negsa, prec, round_ceiling)\\n    # Both negative?\\n    else:\\n        a = mpf_neg(sb, prec, round_floor)\\n        b = mpf_neg(sa, prec, round_ceiling)\\n    return a, b\\n\\n# TODO: optimize\\ndef mpi_mul_mpf(s, t, prec):\\n    return mpi_mul(s, (t, t), prec)\\n\\ndef mpi_div_mpf(s, t, prec):\\n    return mpi_div(s, (t, t), prec)\\n\\ndef mpi_mul(s, t, prec=0):\\n    sa, sb = s\\n    ta, tb = t\\n    sas = mpf_sign(sa)\\n    sbs = mpf_sign(sb)\\n    tas = mpf_sign(ta)\\n    tbs = mpf_sign(tb)\\n    if sas == sbs == 0:\\n        # Should maybe be undefined\\n        if ta == fninf or tb == finf:\\n            return fninf, finf\\n        return fzero, fzero\\n    if tas == tbs == 0:\\n        # Should maybe be undefined\\n        if sa == fninf or sb == finf:\\n            return fninf, finf\\n        return fzero, fzero\\n    if sas >= 0:\\n        # positive * positive\\n        if tas >= 0:\\n            a = mpf_mul(sa, ta, prec, round_floor)\\n            b = mpf_mul(sb, tb, prec, round_ceiling)\\n            if a == fnan: a = fzero\\n            if b == fnan: b = finf\\n        # positive * negative\\n        elif tbs <= 0:\\n            a = mpf_mul(sb, ta, prec, round_floor)\\n            b = mpf_mul(sa, tb, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = fzero\\n        # positive * both signs\\n        else:\\n            a = mpf_mul(sb, ta, prec, round_floor)\\n            b = mpf_mul(sb, tb, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = finf\\n    elif sbs <= 0:\\n        # negative * positive\\n        if tas >= 0:\\n            a = mpf_mul(sa, tb, prec, round_floor)\\n            b = mpf_mul(sb, ta, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = fzero\\n        # negative * negative\\n        elif tbs <= 0:\\n            a = mpf_mul(sb, tb, prec, round_floor)\\n            b = mpf_mul(sa, ta, prec, round_ceiling)\\n            if a == fnan: a = fzero\\n            if b == fnan: b = finf\\n        # negative * both signs\\n        else:\\n            a = mpf_mul(sa, tb, prec, round_floor)\\n            b = mpf_mul(sa, ta, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = finf\\n    else:\\n        # General case: perform all cross-multiplications and compare\\n        # Since the multiplications can be done exactly, we need only\\n        # do 4 (instead of 8: two for each rounding mode)\\n        cases = [mpf_mul(sa, ta), mpf_mul(sa, tb), mpf_mul(sb, ta), mpf_mul(sb, tb)]\\n        if fnan in cases:\\n            a, b = (fninf, finf)\\n        else:\\n            a, b = mpf_min_max(cases)\\n            a = mpf_pos(a, prec, round_floor)\\n            b = mpf_pos(b, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_square(s, prec=0):\\n    sa, sb = s\\n    if mpf_ge(sa, fzero):\\n        a = mpf_mul(sa, sa, prec, round_floor)\\n        b = mpf_mul(sb, sb, prec, round_ceiling)\\n    elif mpf_le(sb, fzero):\\n        a = mpf_mul(sb, sb, prec, round_floor)\\n        b = mpf_mul(sa, sa, prec, round_ceiling)\\n    else:\\n        sa = mpf_neg(sa)\\n        sa, sb = mpf_min_max([sa, sb])\\n        a = fzero\\n        b = mpf_mul(sb, sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_div(s, t, prec):\\n    sa, sb = s\\n    ta, tb = t\\n    sas = mpf_sign(sa)\\n    sbs = mpf_sign(sb)\\n    tas = mpf_sign(ta)\\n    tbs = mpf_sign(tb)\\n    # 0 / X\\n    if sas == sbs == 0:\\n        # 0 / <interval containing 0>\\n        if (tas < 0 and tbs > 0) or (tas == 0 or tbs == 0):\\n            return fninf, finf\\n        return fzero, fzero\\n    # Denominator contains both negative and positive numbers;\\n    # this should properly be a multi-interval, but the closest\\n    # match is the entire (extended) real line\\n    if tas < 0 and tbs > 0:\\n        return fninf, finf\\n    # Assume denominator to be nonnegative\\n    if tas < 0:\\n        return mpi_div(mpi_neg(s), mpi_neg(t), prec)\\n    # Division by zero\\n    # XXX: make sure all results make sense\\n    if tas == 0:\\n        # Numerator contains both signs?\\n        if sas < 0 and sbs > 0:\\n            return fninf, finf\\n        if tas == tbs:\\n            return fninf, finf\\n        # Numerator positive?\\n        if sas >= 0:\\n            a = mpf_div(sa, tb, prec, round_floor)\\n            b = finf\\n        if sbs <= 0:\\n            a = fninf\\n            b = mpf_div(sb, tb, prec, round_ceiling)\\n    # Division with positive denominator\\n    # We still have to handle nans resulting from inf/0 or inf/inf\\n    else:\\n        # Nonnegative numerator\\n        if sas >= 0:\\n            a = mpf_div(sa, tb, prec, round_floor)\\n            b = mpf_div(sb, ta, prec, round_ceiling)\\n            if a == fnan: a = fzero\\n            if b == fnan: b = finf\\n        # Nonpositive numerator\\n        elif sbs <= 0:\\n            a = mpf_div(sa, ta, prec, round_floor)\\n            b = mpf_div(sb, tb, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = fzero\\n        # Numerator contains both signs?\\n        else:\\n            a = mpf_div(sa, ta, prec, round_floor)\\n            b = mpf_div(sb, ta, prec, round_ceiling)\\n            if a == fnan: a = fninf\\n            if b == fnan: b = finf\\n    return a, b\\n\\ndef mpi_pi(prec):\\n    a = mpf_pi(prec, round_floor)\\n    b = mpf_pi(prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_exp(s, prec):\\n    sa, sb = s\\n    # exp is monotonic\\n    a = mpf_exp(sa, prec, round_floor)\\n    b = mpf_exp(sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_log(s, prec):\\n    sa, sb = s\\n    # log is monotonic\\n    a = mpf_log(sa, prec, round_floor)\\n    b = mpf_log(sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_sqrt(s, prec):\\n    sa, sb = s\\n    # sqrt is monotonic\\n    a = mpf_sqrt(sa, prec, round_floor)\\n    b = mpf_sqrt(sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_atan(s, prec):\\n    sa, sb = s\\n    a = mpf_atan(sa, prec, round_floor)\\n    b = mpf_atan(sb, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_pow_int(s, n, prec):\\n    sa, sb = s\\n    if n < 0:\\n        return mpi_div((fone, fone), mpi_pow_int(s, -n, prec+20), prec)\\n    if n == 0:\\n        return (fone, fone)\\n    if n == 1:\\n        return s\\n    if n == 2:\\n        return mpi_square(s, prec)\\n    # Odd -- signs are preserved\\n    if n & 1:\\n        a = mpf_pow_int(sa, n, prec, round_floor)\\n        b = mpf_pow_int(sb, n, prec, round_ceiling)\\n    # Even -- important to ensure positivity\\n    else:\\n        sas = mpf_sign(sa)\\n        sbs = mpf_sign(sb)\\n        # Nonnegative?\\n        if sas >= 0:\\n            a = mpf_pow_int(sa, n, prec, round_floor)\\n            b = mpf_pow_int(sb, n, prec, round_ceiling)\\n        # Nonpositive?\\n        elif sbs <= 0:\\n            a = mpf_pow_int(sb, n, prec, round_floor)\\n            b = mpf_pow_int(sa, n, prec, round_ceiling)\\n        # Mixed signs?\\n        else:\\n            a = fzero\\n            # max(-a,b)**n\\n            sa = mpf_neg(sa)\\n            if mpf_ge(sa, sb):\\n                b = mpf_pow_int(sa, n, prec, round_ceiling)\\n            else:\\n                b = mpf_pow_int(sb, n, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_pow(s, t, prec):\\n    ta, tb = t\\n    if ta == tb and ta not in (finf, fninf):\\n        if ta == from_int(to_int(ta)):\\n            return mpi_pow_int(s, to_int(ta), prec)\\n        if ta == fhalf:\\n            return mpi_sqrt(s, prec)\\n    u = mpi_log(s, prec + 20)\\n    v = mpi_mul(u, t, prec + 20)\\n    return mpi_exp(v, prec)\\n\\ndef MIN(x, y):\\n    if mpf_le(x, y):\\n        return x\\n    return y\\n\\ndef MAX(x, y):\\n    if mpf_ge(x, y):\\n        return x\\n    return y\\n\\ndef cos_sin_quadrant(x, wp):\\n    sign, man, exp, bc = x\\n    if x == fzero:\\n        return fone, fzero, 0\\n    # TODO: combine evaluation code to avoid duplicate modulo\\n    c, s = mpf_cos_sin(x, wp)\\n    t, n, wp_ = mod_pi2(man, exp, exp+bc, 15)\\n    if sign:\\n        n = -1-n\\n    return c, s, n\\n\\ndef mpi_cos_sin(x, prec):\\n    a, b = x\\n    if a == b == fzero:\\n        return (fone, fone), (fzero, fzero)\\n    # Guaranteed to contain both -1 and 1\\n    if (finf in x) or (fninf in x):\\n        return (fnone, fone), (fnone, fone)\\n    wp = prec + 20\\n    ca, sa, na = cos_sin_quadrant(a, wp)\\n    cb, sb, nb = cos_sin_quadrant(b, wp)\\n    ca, cb = mpf_min_max([ca, cb])\\n    sa, sb = mpf_min_max([sa, sb])\\n    # Both functions are monotonic within one quadrant\\n    if na == nb:\\n        pass\\n    # Guaranteed to contain both -1 and 1\\n    elif nb - na >= 4:\\n        return (fnone, fone), (fnone, fone)\\n    else:\\n        # cos has maximum between a and b\\n        if na//4 != nb//4:\\n            cb = fone\\n        # cos has minimum\\n        if (na-2)//4 != (nb-2)//4:\\n            ca = fnone\\n        # sin has maximum\\n        if (na-1)//4 != (nb-1)//4:\\n            sb = fone\\n        # sin has minimum\\n        if (na-3)//4 != (nb-3)//4:\\n            sa = fnone\\n    # Perturb to force interval rounding\\n    more = from_man_exp((MPZ_ONE<<wp) + (MPZ_ONE<<10), -wp)\\n    less = from_man_exp((MPZ_ONE<<wp) - (MPZ_ONE<<10), -wp)\\n    def finalize(v, rounding):\\n        if bool(v[0]) == (rounding == round_floor):\\n            p = more\\n        else:\\n            p = less\\n        v = mpf_mul(v, p, prec, rounding)\\n        sign, man, exp, bc = v\\n        if exp+bc >= 1:\\n            if sign:\\n                return fnone\\n            return fone\\n        return v\\n    ca = finalize(ca, round_floor)\\n    cb = finalize(cb, round_ceiling)\\n    sa = finalize(sa, round_floor)\\n    sb = finalize(sb, round_ceiling)\\n    return (ca,cb), (sa,sb)\\n\\ndef mpi_cos(x, prec):\\n    return mpi_cos_sin(x, prec)[0]\\n\\ndef mpi_sin(x, prec):\\n    return mpi_cos_sin(x, prec)[1]\\n\\ndef mpi_tan(x, prec):\\n    cos, sin = mpi_cos_sin(x, prec+20)\\n    return mpi_div(sin, cos, prec)\\n\\ndef mpi_cot(x, prec):\\n    cos, sin = mpi_cos_sin(x, prec+20)\\n    return mpi_div(cos, sin, prec)\\n\\ndef mpi_from_str_a_b(x, y, percent, prec):\\n    wp = prec + 20\\n    xa = from_str(x, wp, round_floor)\\n    xb = from_str(x, wp, round_ceiling)\\n    #ya = from_str(y, wp, round_floor)\\n    y = from_str(y, wp, round_ceiling)\\n    assert mpf_ge(y, fzero)\\n    if percent:\\n        y = mpf_mul(MAX(mpf_abs(xa), mpf_abs(xb)), y, wp, round_ceiling)\\n        y = mpf_div(y, from_int(100), wp, round_ceiling)\\n    a = mpf_sub(xa, y, prec, round_floor)\\n    b = mpf_add(xb, y, prec, round_ceiling)\\n    return a, b\\n\\ndef mpi_from_str(s, prec):\\n    \\\"\\\"\\\"\\n    Parse an interval number given as a string.\\n\\n    Allowed forms are\\n\\n    \\\"-1.23e-27\\\"\\n        Any single decimal floating-point literal.\\n    \\\"a +- b\\\"  or  \\\"a (b)\\\"\\n        a is the midpoint of the interval and b is the half-width\\n    \\\"a +- b%\\\"  or  \\\"a (b%)\\\"\\n        a is the midpoint of the interval and the half-width\\n        is b percent of a (`a \\\\times b / 100`).\\n    \\\"[a, b]\\\"\\n        The interval indicated directly.\\n    \\\"x[y,z]e\\\"\\n        x are shared digits, y and z are unequal digits, e is the exponent.\\n\\n    \\\"\\\"\\\"\\n    e = ValueError(\\\"Improperly formed interval number '%s'\\\" % s)\\n    s = s.replace(\\\" \\\", \\\"\\\")\\n    wp = prec + 20\\n    if \\\"+-\\\" in s:\\n        x, y = s.split(\\\"+-\\\")\\n        return mpi_from_str_a_b(x, y, False, prec)\\n    # case 2\\n    elif \\\"(\\\" in s:\\n        # Don't confuse with a complex number (x,y)\\n        if s[0] == \\\"(\\\" or \\\")\\\" not in s:\\n            raise e\\n        s = s.replace(\\\")\\\", \\\"\\\")\\n        percent = False\\n        if \\\"%\\\" in s:\\n            if s[-1] != \\\"%\\\":\\n                raise e\\n            percent = True\\n            s = s.replace(\\\"%\\\", \\\"\\\")\\n        x, y = s.split(\\\"(\\\")\\n        return mpi_from_str_a_b(x, y, percent, prec)\\n    elif \\\",\\\" in s:\\n        if ('[' not in s) or (']' not in s):\\n            raise e\\n        if s[0] == '[':\\n            # case 3\\n            s = s.replace(\\\"[\\\", \\\"\\\")\\n            s = s.replace(\\\"]\\\", \\\"\\\")\\n            a, b = s.split(\\\",\\\")\\n            a = from_str(a, prec, round_floor)\\n            b = from_str(b, prec, round_ceiling)\\n            return a, b\\n        else:\\n            # case 4\\n            x, y = s.split('[')\\n            y, z = y.split(',')\\n            if 'e' in s:\\n                z, e = z.split(']')\\n            else:\\n                z, e = z.rstrip(']'), ''\\n            a = from_str(x+y+e, prec, round_floor)\\n            b = from_str(x+z+e, prec, round_ceiling)\\n            return a, b\\n    else:\\n        a = from_str(s, prec, round_floor)\\n        b = from_str(s, prec, round_ceiling)\\n        return a, b\\n\\ndef mpi_to_str(x, dps, use_spaces=True, brackets='[]', mode='brackets', error_dps=4, **kwargs):\\n    \\\"\\\"\\\"\\n    Convert a mpi interval to a string.\\n\\n    **Arguments**\\n\\n    *dps*\\n        decimal places to use for printing\\n    *use_spaces*\\n        use spaces for more readable output, defaults to true\\n    *brackets*\\n        pair of strings (or two-character string) giving left and right brackets\\n    *mode*\\n        mode of display: 'plusminus', 'percent', 'brackets' (default) or 'diff'\\n    *error_dps*\\n        limit the error to *error_dps* digits (mode 'plusminus and 'percent')\\n\\n    Additional keyword arguments are forwarded to the mpf-to-string conversion\\n    for the components of the output.\\n\\n    **Examples**\\n\\n        >>> from mpmath import mpi, mp\\n        >>> mp.dps = 30\\n        >>> x = mpi(1, 2)._mpi_\\n        >>> mpi_to_str(x, 2, mode='plusminus')\\n        '1.5 +- 0.5'\\n        >>> mpi_to_str(x, 2, mode='percent')\\n        '1.5 (33.33%)'\\n        >>> mpi_to_str(x, 2, mode='brackets')\\n        '[1.0, 2.0]'\\n        >>> mpi_to_str(x, 2, mode='brackets' , brackets=('<', '>'))\\n        '<1.0, 2.0>'\\n        >>> x = mpi('5.2582327113062393041', '5.2582327113062749951')._mpi_\\n        >>> mpi_to_str(x, 15, mode='diff')\\n        '5.2582327113062[4, 7]'\\n        >>> mpi_to_str(mpi(0)._mpi_, 2, mode='percent')\\n        '0.0 (0.0%)'\\n\\n    \\\"\\\"\\\"\\n    prec = dps_to_prec(dps)\\n    wp = prec + 20\\n    a, b = x\\n    mid = mpi_mid(x, prec)\\n    delta = mpi_delta(x, prec)\\n    a_str = to_str(a, dps, **kwargs)\\n    b_str = to_str(b, dps, **kwargs)\\n    mid_str = to_str(mid, dps, **kwargs)\\n    sp = \\\"\\\"\\n    if use_spaces:\\n        sp = \\\" \\\"\\n    br1, br2 = brackets\\n    if mode == 'plusminus':\\n        delta_str = to_str(mpf_shift(delta,-1), dps, **kwargs)\\n        s = mid_str + sp + \\\"+-\\\" + sp + delta_str\\n    elif mode == 'percent':\\n        if mid == fzero:\\n            p = fzero\\n        else:\\n            # p = 100 * delta(x) / (2*mid(x))\\n            p = mpf_mul(delta, from_int(100))\\n            p = mpf_div(p, mpf_mul(mid, from_int(2)), wp)\\n        s = mid_str + sp + \\\"(\\\" + to_str(p, error_dps) + \\\"%)\\\"\\n    elif mode == 'brackets':\\n        s = br1 + a_str + \\\",\\\" + sp + b_str + br2\\n    elif mode == 'diff':\\n        # use more digits if str(x.a) and str(x.b) are equal\\n        if a_str == b_str:\\n            a_str = to_str(a, dps+3, **kwargs)\\n            b_str = to_str(b, dps+3, **kwargs)\\n        # separate mantissa and exponent\\n        a = a_str.split('e')\\n        if len(a) == 1:\\n            a.append('')\\n        b = b_str.split('e')\\n        if len(b) == 1:\\n            b.append('')\\n        if a[1] == b[1]:\\n            if a[0] != b[0]:\\n                for i in xrange(len(a[0]) + 1):\\n                    if a[0][i] != b[0][i]:\\n                        break\\n                s = (a[0][:i] + br1 + a[0][i:] + ',' + sp + b[0][i:] + br2\\n                     + 'e'*min(len(a[1]), 1) + a[1])\\n            else: # no difference\\n                s = a[0] + br1 + br2 + 'e'*min(len(a[1]), 1) + a[1]\\n        else:\\n            s = br1 + 'e'.join(a) + ',' + sp + 'e'.join(b) + br2\\n    else:\\n        raise ValueError(\\\"'%s' is unknown mode for printing mpi\\\" % mode)\\n    return s\\n\\ndef mpci_add(x, y, prec):\\n    a, b = x\\n    c, d = y\\n    return mpi_add(a, c, prec), mpi_add(b, d, prec)\\n\\ndef mpci_sub(x, y, prec):\\n    a, b = x\\n    c, d = y\\n    return mpi_sub(a, c, prec), mpi_sub(b, d, prec)\\n\\ndef mpci_neg(x, prec=0):\\n    a, b = x\\n    return mpi_neg(a, prec), mpi_neg(b, prec)\\n\\ndef mpci_pos(x, prec):\\n    a, b = x\\n    return mpi_pos(a, prec), mpi_pos(b, prec)\\n\\ndef mpci_mul(x, y, prec):\\n    # TODO: optimize for real/imag cases\\n    a, b = x\\n    c, d = y\\n    r1 = mpi_mul(a,c)\\n    r2 = mpi_mul(b,d)\\n    re = mpi_sub(r1,r2,prec)\\n    i1 = mpi_mul(a,d)\\n    i2 = mpi_mul(b,c)\\n    im = mpi_add(i1,i2,prec)\\n    return re, im\\n\\ndef mpci_div(x, y, prec):\\n    # TODO: optimize for real/imag cases\\n    a, b = x\\n    c, d = y\\n    wp = prec+20\\n    m1 = mpi_square(c)\\n    m2 = mpi_square(d)\\n    m = mpi_add(m1,m2,wp)\\n    re = mpi_add(mpi_mul(a,c), mpi_mul(b,d), wp)\\n    im = mpi_sub(mpi_mul(b,c), mpi_mul(a,d), wp)\\n    re = mpi_div(re, m, prec)\\n    im = mpi_div(im, m, prec)\\n    return re, im\\n\\ndef mpci_exp(x, prec):\\n    a, b = x\\n    wp = prec+20\\n    r = mpi_exp(a, wp)\\n    c, s = mpi_cos_sin(b, wp)\\n    a = mpi_mul(r, c, prec)\\n    b = mpi_mul(r, s, prec)\\n    return a, b\\n\\ndef mpi_shift(x, n):\\n    a, b = x\\n    return mpf_shift(a,n), mpf_shift(b,n)\\n\\ndef mpi_cosh_sinh(x, prec):\\n    # TODO: accuracy for small x\\n    wp = prec+20\\n    e1 = mpi_exp(x, wp)\\n    e2 = mpi_div(mpi_one, e1, wp)\\n    c = mpi_add(e1, e2, prec)\\n    s = mpi_sub(e1, e2, prec)\\n    c = mpi_shift(c, -1)\\n    s = mpi_shift(s, -1)\\n    return c, s\\n\\ndef mpci_cos(x, prec):\\n    a, b = x\\n    wp = prec+10\\n    c, s = mpi_cos_sin(a, wp)\\n    ch, sh = mpi_cosh_sinh(b, wp)\\n    re = mpi_mul(c, ch, prec)\\n    im = mpi_mul(s, sh, prec)\\n    return re, mpi_neg(im)\\n\\ndef mpci_sin(x, prec):\\n    a, b = x\\n    wp = prec+10\\n    c, s = mpi_cos_sin(a, wp)\\n    ch, sh = mpi_cosh_sinh(b, wp)\\n    re = mpi_mul(s, ch, prec)\\n    im = mpi_mul(c, sh, prec)\\n    return re, im\\n\\ndef mpci_abs(x, prec):\\n    a, b = x\\n    if a == mpi_zero:\\n        return mpi_abs(b)\\n    if b == mpi_zero:\\n        return mpi_abs(a)\\n    # Important: nonnegative\\n    a = mpi_square(a)\\n    b = mpi_square(b)\\n    t = mpi_add(a, b, prec+20)\\n    return mpi_sqrt(t, prec)\\n\\ndef mpi_atan2(y, x, prec):\\n    ya, yb = y\\n    xa, xb = x\\n    # Constrained to the real line\\n    if ya == yb == fzero:\\n        if mpf_ge(xa, fzero):\\n            return mpi_zero\\n        return mpi_pi(prec)\\n    # Right half-plane\\n    if mpf_ge(xa, fzero):\\n        if mpf_ge(ya, fzero):\\n            a = mpf_atan2(ya, xb, prec, round_floor)\\n        else:\\n            a = mpf_atan2(ya, xa, prec, round_floor)\\n        if mpf_ge(yb, fzero):\\n            b = mpf_atan2(yb, xa, prec, round_ceiling)\\n        else:\\n            b = mpf_atan2(yb, xb, prec, round_ceiling)\\n    # Upper half-plane\\n    elif mpf_ge(ya, fzero):\\n        b = mpf_atan2(ya, xa, prec, round_ceiling)\\n        if mpf_le(xb, fzero):\\n            a = mpf_atan2(yb, xb, prec, round_floor)\\n        else:\\n            a = mpf_atan2(ya, xb, prec, round_floor)\\n    # Lower half-plane\\n    elif mpf_le(yb, fzero):\\n        a = mpf_atan2(yb, xa, prec, round_floor)\\n        if mpf_le(xb, fzero):\\n            b = mpf_atan2(ya, xb, prec, round_ceiling)\\n        else:\\n            b = mpf_atan2(yb, xb, prec, round_ceiling)\\n    # Covering the origin\\n    else:\\n        b = mpf_pi(prec, round_ceiling)\\n        a = mpf_neg(b)\\n    return a, b\\n\\ndef mpci_arg(z, prec):\\n    x, y = z\\n    return mpi_atan2(y, x, prec)\\n\\ndef mpci_log(z, prec):\\n    x, y = z\\n    re = mpi_log(mpci_abs(z, prec+20), prec)\\n    im = mpci_arg(z, prec)\\n    return re, im\\n\\ndef mpci_pow(x, y, prec):\\n    # TODO: recognize/speed up real cases, integer y\\n    yre, yim = y\\n    if yim == mpi_zero:\\n        ya, yb = yre\\n        if ya == yb:\\n            sign, man, exp, bc = yb\\n            if man and exp >= 0:\\n                return mpci_pow_int(x, (-1)**sign * int(man<<exp), prec)\\n            # x^0\\n            if yb == fzero:\\n                return mpci_pow_int(x, 0, prec)\\n    wp = prec+20\\n    return mpci_exp(mpci_mul(y, mpci_log(x, wp), wp), prec)\\n\\ndef mpci_square(x, prec):\\n    a, b = x\\n    # (a+bi)^2 = (a^2-b^2) + 2abi\\n    re = mpi_sub(mpi_square(a), mpi_square(b), prec)\\n    im = mpi_mul(a, b, prec)\\n    im = mpi_shift(im, 1)\\n    return re, im\\n\\ndef mpci_pow_int(x, n, prec):\\n    if n < 0:\\n        return mpci_div((mpi_one,mpi_zero), mpci_pow_int(x, -n, prec+20), prec)\\n    if n == 0:\\n        return mpi_one, mpi_zero\\n    if n == 1:\\n        return mpci_pos(x, prec)\\n    if n == 2:\\n        return mpci_square(x, prec)\\n    wp = prec + 20\\n    result = (mpi_one, mpi_zero)\\n    while n:\\n        if n & 1:\\n            result = mpci_mul(result, x, wp)\\n            n -= 1\\n        x = mpci_square(x, wp)\\n        n >>= 1\\n    return mpci_pos(result, prec)\\n\\ngamma_min_a = from_float(1.46163214496)\\ngamma_min_b = from_float(1.46163214497)\\ngamma_min = (gamma_min_a, gamma_min_b)\\ngamma_mono_imag_a = from_float(-1.1)\\ngamma_mono_imag_b = from_float(1.1)\\n\\ndef mpi_overlap(x, y):\\n    a, b = x\\n    c, d = y\\n    if mpf_lt(d, a): return False\\n    if mpf_gt(c, b): return False\\n    return True\\n\\n# type = 0 -- gamma\\n# type = 1 -- factorial\\n# type = 2 -- 1/gamma\\n# type = 3 -- log-gamma\\n\\ndef mpi_gamma(z, prec, type=0):\\n    a, b = z\\n    wp = prec+20\\n\\n    if type == 1:\\n        return mpi_gamma(mpi_add(z, mpi_one, wp), prec, 0)\\n\\n    # increasing\\n    if mpf_gt(a, gamma_min_b):\\n        if type == 0:\\n            c = mpf_gamma(a, prec, round_floor)\\n            d = mpf_gamma(b, prec, round_ceiling)\\n        elif type == 2:\\n            c = mpf_rgamma(b, prec, round_floor)\\n            d = mpf_rgamma(a, prec, round_ceiling)\\n        elif type == 3:\\n            c = mpf_loggamma(a, prec, round_floor)\\n            d = mpf_loggamma(b, prec, round_ceiling)\\n    # decreasing\\n    elif mpf_gt(a, fzero) and mpf_lt(b, gamma_min_a):\\n        if type == 0:\\n            c = mpf_gamma(b, prec, round_floor)\\n            d = mpf_gamma(a, prec, round_ceiling)\\n        elif type == 2:\\n            c = mpf_rgamma(a, prec, round_floor)\\n            d = mpf_rgamma(b, prec, round_ceiling)\\n        elif type == 3:\\n            c = mpf_loggamma(b, prec, round_floor)\\n            d = mpf_loggamma(a, prec, round_ceiling)\\n    else:\\n        # TODO: reflection formula\\n        znew = mpi_add(z, mpi_one, wp)\\n        if type == 0: return mpi_div(mpi_gamma(znew, prec+2, 0), z, prec)\\n        if type == 2: return mpi_mul(mpi_gamma(znew, prec+2, 2), z, prec)\\n        if type == 3: return mpi_sub(mpi_gamma(znew, prec+2, 3), mpi_log(z, prec+2), prec)\\n    return c, d\\n\\ndef mpci_gamma(z, prec, type=0):\\n    (a1,a2), (b1,b2) = z\\n\\n    # Real case\\n    if b1 == b2 == fzero and (type != 3 or mpf_gt(a1,fzero)):\\n        return mpi_gamma(z, prec, type), mpi_zero\\n\\n    # Estimate precision\\n    wp = prec+20\\n    if type != 3:\\n        amag = a2[2]+a2[3]\\n        bmag = b2[2]+b2[3]\\n        if a2 != fzero:\\n            mag = max(amag, bmag)\\n        else:\\n            mag = bmag\\n        an = abs(to_int(a2))\\n        bn = abs(to_int(b2))\\n        absn = max(an, bn)\\n        gamma_size = max(0,absn*mag)\\n        wp += bitcount(gamma_size)\\n\\n    # Assume type != 1\\n    if type == 1:\\n        (a1,a2) = mpi_add((a1,a2), mpi_one, wp); z = (a1,a2), (b1,b2)\\n        type = 0\\n\\n    # Avoid non-monotonic region near the negative real axis\\n    if mpf_lt(a1, gamma_min_b):\\n        if mpi_overlap((b1,b2), (gamma_mono_imag_a, gamma_mono_imag_b)):\\n            # TODO: reflection formula\\n            #if mpf_lt(a2, mpf_shift(fone,-1)):\\n            #    znew = mpci_sub((mpi_one,mpi_zero),z,wp)\\n            #    ...\\n            # Recurrence:\\n            # gamma(z) = gamma(z+1)/z\\n            znew = mpi_add((a1,a2), mpi_one, wp), (b1,b2)\\n            if type == 0: return mpci_div(mpci_gamma(znew, prec+2, 0), z, prec)\\n            if type == 2: return mpci_mul(mpci_gamma(znew, prec+2, 2), z, prec)\\n            if type == 3: return mpci_sub(mpci_gamma(znew, prec+2, 3), mpci_log(z,prec+2), prec)\\n\\n    # Use monotonicity (except for a small region close to the\\n    # origin and near poles)\\n    # upper half-plane\\n    if mpf_ge(b1, fzero):\\n        minre = mpc_loggamma((a1,b2), wp, round_floor)\\n        maxre = mpc_loggamma((a2,b1), wp, round_ceiling)\\n        minim = mpc_loggamma((a1,b1), wp, round_floor)\\n        maxim = mpc_loggamma((a2,b2), wp, round_ceiling)\\n    # lower half-plane\\n    elif mpf_le(b2, fzero):\\n        minre = mpc_loggamma((a1,b1), wp, round_floor)\\n        maxre = mpc_loggamma((a2,b2), wp, round_ceiling)\\n        minim = mpc_loggamma((a2,b1), wp, round_floor)\\n        maxim = mpc_loggamma((a1,b2), wp, round_ceiling)\\n    # crosses real axis\\n    else:\\n        maxre = mpc_loggamma((a2,fzero), wp, round_ceiling)\\n        # stretches more into the lower half-plane\\n        if mpf_gt(mpf_neg(b1), b2):\\n            minre = mpc_loggamma((a1,b1), wp, round_ceiling)\\n        else:\\n            minre = mpc_loggamma((a1,b2), wp, round_ceiling)\\n        minim = mpc_loggamma((a2,b1), wp, round_floor)\\n        maxim = mpc_loggamma((a2,b2), wp, round_floor)\\n\\n    w = (minre[0], maxre[0]), (minim[1], maxim[1])\\n    if type == 3:\\n        return mpi_pos(w[0], prec), mpi_pos(w[1], prec)\\n    if type == 2:\\n        w = mpci_neg(w)\\n    return mpci_exp(w, prec)\\n\\ndef mpi_loggamma(z, prec): return mpi_gamma(z, prec, type=3)\\ndef mpci_loggamma(z, prec): return mpci_gamma(z, prec, type=3)\\n\\ndef mpi_rgamma(z, prec): return mpi_gamma(z, prec, type=2)\\ndef mpci_rgamma(z, prec): return mpci_gamma(z, prec, type=2)\\n\\ndef mpi_factorial(z, prec): return mpi_gamma(z, prec, type=1)\\ndef mpci_factorial(z, prec): return mpci_gamma(z, prec, type=1)\\n\\n\\n\\\"\\\"\\\"\\nLow-level functions for arbitrary-precision floating-point arithmetic.\\n\\\"\\\"\\\"\\n\\n__docformat__ = 'plaintext'\\n\\nimport math\\n\\nfrom bisect import bisect\\n\\nimport sys\\n\\n# Importing random is slow\\n#from random import getrandbits\\ngetrandbits = None\\n\\nfrom .backend import (MPZ, MPZ_TYPE, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE,\\n    BACKEND, STRICT, HASH_MODULUS, HASH_BITS, gmpy, sage, sage_utils)\\n\\nfrom .libintmath import (giant_steps,\\n    trailtable, bctable, lshift, rshift, bitcount, trailing,\\n    sqrt_fixed, numeral, isqrt, isqrt_fast, sqrtrem,\\n    bin_to_radix)\\n\\n# We don't pickle tuples directly for the following reasons:\\n#   1: pickle uses str() for ints, which is inefficient when they are large\\n#   2: pickle doesn't work for gmpy mpzs\\n# Both problems are solved by using hex()\\n\\nif BACKEND == 'sage':\\n    def to_pickable(x):\\n        sign, man, exp, bc = x\\n        return sign, hex(man), exp, bc\\nelse:\\n    def to_pickable(x):\\n        sign, man, exp, bc = x\\n        return sign, hex(man)[2:], exp, bc\\n\\ndef from_pickable(x):\\n    sign, man, exp, bc = x\\n    return (sign, MPZ(man, 16), exp, bc)\\n\\nclass ComplexResult(ValueError):\\n    pass\\n\\ntry:\\n    intern\\nexcept NameError:\\n    intern = lambda x: x\\n\\n# All supported rounding modes\\nround_nearest = intern('n')\\nround_floor = intern('f')\\nround_ceiling = intern('c')\\nround_up = intern('u')\\nround_down = intern('d')\\nround_fast = round_down\\n\\ndef prec_to_dps(n):\\n    \\\"\\\"\\\"Return number of accurate decimals that can be represented\\n    with a precision of n bits.\\\"\\\"\\\"\\n    return max(1, int(round(int(n)/3.3219280948873626)-1))\\n\\ndef dps_to_prec(n):\\n    \\\"\\\"\\\"Return the number of bits required to represent n decimals\\n    accurately.\\\"\\\"\\\"\\n    return max(1, int(round((int(n)+1)*3.3219280948873626)))\\n\\ndef repr_dps(n):\\n    \\\"\\\"\\\"Return the number of decimal digits required to represent\\n    a number with n-bit precision so that it can be uniquely\\n    reconstructed from the representation.\\\"\\\"\\\"\\n    dps = prec_to_dps(n)\\n    if dps == 15:\\n        return 17\\n    return dps + 3\\n\\n#----------------------------------------------------------------------------#\\n#                    Some commonly needed float values                       #\\n#----------------------------------------------------------------------------#\\n\\n# Regular number format:\\n# (-1)**sign * mantissa * 2**exponent, plus bitcount of mantissa\\nfzero = (0, MPZ_ZERO, 0, 0)\\nfnzero = (1, MPZ_ZERO, 0, 0)\\nfone = (0, MPZ_ONE, 0, 1)\\nfnone = (1, MPZ_ONE, 0, 1)\\nftwo = (0, MPZ_ONE, 1, 1)\\nften = (0, MPZ_FIVE, 1, 3)\\nfhalf = (0, MPZ_ONE, -1, 1)\\n\\n# Arbitrary encoding for special numbers: zero mantissa, nonzero exponent\\nfnan = (0, MPZ_ZERO, -123, -1)\\nfinf = (0, MPZ_ZERO, -456, -2)\\nfninf = (1, MPZ_ZERO, -789, -3)\\n\\n# Was 1e1000; this is broken in Python 2.4\\nmath_float_inf = 1e300 * 1e300\\n\\n\\n#----------------------------------------------------------------------------#\\n#                                  Rounding                                  #\\n#----------------------------------------------------------------------------#\\n\\n# This function can be used to round a mantissa generally. However,\\n# we will try to do most rounding inline for efficiency.\\ndef round_int(x, n, rnd):\\n    if rnd == round_nearest:\\n        if x >= 0:\\n            t = x >> (n-1)\\n            if t & 1 and ((t & 2) or (x & h_mask[n<300][n])):\\n                return (t>>1)+1\\n            else:\\n                return t>>1\\n        else:\\n            return -round_int(-x, n, rnd)\\n    if rnd == round_floor:\\n        return x >> n\\n    if rnd == round_ceiling:\\n        return -((-x) >> n)\\n    if rnd == round_down:\\n        if x >= 0:\\n            return x >> n\\n        return -((-x) >> n)\\n    if rnd == round_up:\\n        if x >= 0:\\n            return -((-x) >> n)\\n        return x >> n\\n\\n# These masks are used to pick out segments of numbers to determine\\n# which direction to round when rounding to nearest.\\nclass h_mask_big:\\n    def __getitem__(self, n):\\n        return (MPZ_ONE<<(n-1))-1\\n\\nh_mask_small = [0]+[((MPZ_ONE<<(_-1))-1) for _ in range(1, 300)]\\nh_mask = [h_mask_big(), h_mask_small]\\n\\n# The >> operator rounds to floor. shifts_down[rnd][sign]\\n# tells whether this is the right direction to use, or if the\\n# number should be negated before shifting\\nshifts_down = {round_floor:(1,0), round_ceiling:(0,1),\\n    round_down:(1,1), round_up:(0,0)}\\n\\n\\n#----------------------------------------------------------------------------#\\n#                          Normalization of raw mpfs                         #\\n#----------------------------------------------------------------------------#\\n\\n# This function is called almost every time an mpf is created.\\n# It has been optimized accordingly.\\n\\ndef _normalize(sign, man, exp, bc, prec, rnd):\\n    \\\"\\\"\\\"\\n    Create a raw mpf tuple with value (-1)**sign * man * 2**exp and\\n    normalized mantissa. The mantissa is rounded in the specified\\n    direction if its size exceeds the precision. Trailing zero bits\\n    are also stripped from the mantissa to ensure that the\\n    representation is canonical.\\n\\n    Conditions on the input:\\n    * The input must represent a regular (finite) number\\n    * The sign bit must be 0 or 1\\n    * The mantissa must be positive\\n    * The exponent must be an integer\\n    * The bitcount must be exact\\n\\n    If these conditions are not met, use from_man_exp, mpf_pos, or any\\n    of the conversion functions to create normalized raw mpf tuples.\\n    \\\"\\\"\\\"\\n    if not man:\\n        return fzero\\n    # Cut mantissa down to size if larger than target precision\\n    n = bc - prec\\n    if n > 0:\\n        if rnd == round_nearest:\\n            t = man >> (n-1)\\n            if t & 1 and ((t & 2) or (man & h_mask[n<300][n])):\\n                man = (t>>1)+1\\n            else:\\n                man = t>>1\\n        elif shifts_down[rnd][sign]:\\n            man >>= n\\n        else:\\n            man = -((-man)>>n)\\n        exp += n\\n        bc = prec\\n    # Strip trailing bits\\n    if not man & 1:\\n        t = trailtable[int(man & 255)]\\n        if not t:\\n            while not man & 255:\\n                man >>= 8\\n                exp += 8\\n                bc -= 8\\n            t = trailtable[int(man & 255)]\\n        man >>= t\\n        exp += t\\n        bc -= t\\n    # Bit count can be wrong if the input mantissa was 1 less than\\n    # a power of 2 and got rounded up, thereby adding an extra bit.\\n    # With trailing bits removed, all powers of two have mantissa 1,\\n    # so this is easy to check for.\\n    if man == 1:\\n        bc = 1\\n    return sign, man, exp, bc\\n\\ndef _normalize1(sign, man, exp, bc, prec, rnd):\\n    \\\"\\\"\\\"same as normalize, but with the added condition that\\n       man is odd or zero\\n    \\\"\\\"\\\"\\n    if not man:\\n        return fzero\\n    if bc <= prec:\\n        return sign, man, exp, bc\\n    n = bc - prec\\n    if rnd == round_nearest:\\n        t = man >> (n-1)\\n        if t & 1 and ((t & 2) or (man & h_mask[n<300][n])):\\n            man = (t>>1)+1\\n        else:\\n            man = t>>1\\n    elif shifts_down[rnd][sign]:\\n        man >>= n\\n    else:\\n        man = -((-man)>>n)\\n    exp += n\\n    bc = prec\\n    # Strip trailing bits\\n    if not man & 1:\\n        t = trailtable[int(man & 255)]\\n        if not t:\\n            while not man & 255:\\n                man >>= 8\\n                exp += 8\\n                bc -= 8\\n            t = trailtable[int(man & 255)]\\n        man >>= t\\n        exp += t\\n        bc -= t\\n    # Bit count can be wrong if the input mantissa was 1 less than\\n    # a power of 2 and got rounded up, thereby adding an extra bit.\\n    # With trailing bits removed, all powers of two have mantissa 1,\\n    # so this is easy to check for.\\n    if man == 1:\\n        bc = 1\\n    return sign, man, exp, bc\\n\\ntry:\\n    _exp_types = (int, long)\\nexcept NameError:\\n    _exp_types = (int,)\\n\\ndef strict_normalize(sign, man, exp, bc, prec, rnd):\\n    \\\"\\\"\\\"Additional checks on the components of an mpf. Enable tests by setting\\n       the environment variable MPMATH_STRICT to Y.\\\"\\\"\\\"\\n    assert type(man) == MPZ_TYPE\\n    assert type(bc) in _exp_types\\n    assert type(exp) in _exp_types\\n    assert bc == bitcount(man)\\n    return _normalize(sign, man, exp, bc, prec, rnd)\\n\\ndef strict_normalize1(sign, man, exp, bc, prec, rnd):\\n    \\\"\\\"\\\"Additional checks on the components of an mpf. Enable tests by setting\\n       the environment variable MPMATH_STRICT to Y.\\\"\\\"\\\"\\n    assert type(man) == MPZ_TYPE\\n    assert type(bc) in _exp_types\\n    assert type(exp) in _exp_types\\n    assert bc == bitcount(man)\\n    assert (not man) or (man & 1)\\n    return _normalize1(sign, man, exp, bc, prec, rnd)\\n\\nif BACKEND == 'gmpy' and '_mpmath_normalize' in dir(gmpy):\\n    _normalize = gmpy._mpmath_normalize\\n    _normalize1 = gmpy._mpmath_normalize\\n\\nif BACKEND == 'sage':\\n    _normalize = _normalize1 = sage_utils.normalize\\n\\nif STRICT:\\n    normalize = strict_normalize\\n    normalize1 = strict_normalize1\\nelse:\\n    normalize = _normalize\\n    normalize1 = _normalize1\\n\\n#----------------------------------------------------------------------------#\\n#                            Conversion functions                            #\\n#----------------------------------------------------------------------------#\\n\\ndef from_man_exp(man, exp, prec=None, rnd=round_fast):\\n    \\\"\\\"\\\"Create raw mpf from (man, exp) pair. The mantissa may be signed.\\n    If no precision is specified, the mantissa is stored exactly.\\\"\\\"\\\"\\n    man = MPZ(man)\\n    sign = 0\\n    if man < 0:\\n        sign = 1\\n        man = -man\\n    if man < 1024:\\n        bc = bctable[int(man)]\\n    else:\\n        bc = bitcount(man)\\n    if not prec:\\n        if not man:\\n            return fzero\\n        if not man & 1:\\n            if man & 2:\\n                return (sign, man >> 1, exp + 1, bc - 1)\\n            t = trailtable[int(man & 255)]\\n            if not t:\\n                while not man & 255:\\n                    man >>= 8\\n                    exp += 8\\n                    bc -= 8\\n                t = trailtable[int(man & 255)]\\n            man >>= t\\n            exp += t\\n            bc -= t\\n        return (sign, man, exp, bc)\\n    return normalize(sign, man, exp, bc, prec, rnd)\\n\\nint_cache = dict((n, from_man_exp(n, 0)) for n in range(-10, 257))\\n\\nif BACKEND == 'gmpy' and '_mpmath_create' in dir(gmpy):\\n    from_man_exp = gmpy._mpmath_create\\n\\nif BACKEND == 'sage':\\n    from_man_exp = sage_utils.from_man_exp\\n\\ndef from_int(n, prec=0, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from an integer. If no precision is specified,\\n    the mantissa is stored exactly.\\\"\\\"\\\"\\n    if not prec:\\n        if n in int_cache:\\n            return int_cache[n]\\n    return from_man_exp(n, 0, prec, rnd)\\n\\ndef to_man_exp(s):\\n    \\\"\\\"\\\"Return (man, exp) of a raw mpf. Raise an error if inf/nan.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if (not man) and exp:\\n        raise ValueError(\\\"mantissa and exponent are undefined for %s\\\" % man)\\n    return man, exp\\n\\ndef to_int(s, rnd=None):\\n    \\\"\\\"\\\"Convert a raw mpf to the nearest int. Rounding is done down by\\n    default (same as int(float) in Python), but can be changed. If the\\n    input is inf/nan, an exception is raised.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if (not man) and exp:\\n        raise ValueError(\\\"cannot convert inf or nan to int\\\")\\n    if exp >= 0:\\n        if sign:\\n            return (-man) << exp\\n        return man << exp\\n    # Make default rounding fast\\n    if not rnd:\\n        if sign:\\n            return -(man >> (-exp))\\n        else:\\n            return man >> (-exp)\\n    if sign:\\n        return round_int(-man, -exp, rnd)\\n    else:\\n        return round_int(man, -exp, rnd)\\n\\ndef mpf_round_int(s, rnd):\\n    sign, man, exp, bc = s\\n    if (not man) and exp:\\n        return s\\n    if exp >= 0:\\n        return s\\n    mag = exp+bc\\n    if mag < 1:\\n        if rnd == round_ceiling:\\n            if sign: return fzero\\n            else:    return fone\\n        elif rnd == round_floor:\\n            if sign: return fnone\\n            else:    return fzero\\n        elif rnd == round_nearest:\\n            if mag < 0 or man == MPZ_ONE: return fzero\\n            elif sign: return fnone\\n            else:      return fone\\n        else:\\n            raise NotImplementedError\\n    return mpf_pos(s, min(bc, mag), rnd)\\n\\ndef mpf_floor(s, prec=0, rnd=round_fast):\\n    v = mpf_round_int(s, round_floor)\\n    if prec:\\n        v = mpf_pos(v, prec, rnd)\\n    return v\\n\\ndef mpf_ceil(s, prec=0, rnd=round_fast):\\n    v = mpf_round_int(s, round_ceiling)\\n    if prec:\\n        v = mpf_pos(v, prec, rnd)\\n    return v\\n\\ndef mpf_nint(s, prec=0, rnd=round_fast):\\n    v = mpf_round_int(s, round_nearest)\\n    if prec:\\n        v = mpf_pos(v, prec, rnd)\\n    return v\\n\\ndef mpf_frac(s, prec=0, rnd=round_fast):\\n    return mpf_sub(s, mpf_floor(s), prec, rnd)\\n\\ndef from_float(x, prec=53, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from a Python float, rounding if necessary.\\n    If prec >= 53, the result is guaranteed to represent exactly the\\n    same number as the input. If prec is not specified, use prec=53.\\\"\\\"\\\"\\n    # frexp only raises an exception for nan on some platforms\\n    if x != x:\\n        return fnan\\n    # in Python2.5 math.frexp gives an exception for float infinity\\n    # in Python2.6 it returns (float infinity, 0)\\n    try:\\n        m, e = math.frexp(x)\\n    except:\\n        if x == math_float_inf: return finf\\n        if x == -math_float_inf: return fninf\\n        return fnan\\n    if x == math_float_inf: return finf\\n    if x == -math_float_inf: return fninf\\n    return from_man_exp(int(m*(1<<53)), e-53, prec, rnd)\\n\\ndef from_npfloat(x, prec=113, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from a numpy float, rounding if necessary.\\n    If prec >= 113, the result is guaranteed to represent exactly the\\n    same number as the input. If prec is not specified, use prec=113.\\\"\\\"\\\"\\n    y = float(x)\\n    if x == y: # ldexp overflows for float16\\n        return from_float(y, prec, rnd)\\n    import numpy as np\\n    if np.isfinite(x):\\n        m, e = np.frexp(x)\\n        return from_man_exp(int(np.ldexp(m, 113)), int(e-113), prec, rnd)\\n    if np.isposinf(x): return finf\\n    if np.isneginf(x): return fninf\\n    return fnan\\n\\ndef from_Decimal(x, prec=None, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from a Decimal, rounding if necessary.\\n    If prec is not specified, use the equivalent bit precision\\n    of the number of significant digits in x.\\\"\\\"\\\"\\n    if x.is_nan(): return fnan\\n    if x.is_infinite(): return fninf if x.is_signed() else finf\\n    if prec is None:\\n        prec = int(len(x.as_tuple()[1])*3.3219280948873626)\\n    return from_str(str(x), prec, rnd)\\n\\ndef to_float(s, strict=False, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Convert a raw mpf to a Python float. The result is exact if the\\n    bitcount of s is <= 53 and no underflow/overflow occurs.\\n\\n    If the number is too large or too small to represent as a regular\\n    float, it will be converted to inf or 0.0. Setting strict=True\\n    forces an OverflowError to be raised instead.\\n\\n    Warning: with a directed rounding mode, the correct nearest representable\\n    floating-point number in the specified direction might not be computed\\n    in case of overflow or (gradual) underflow.\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        if s == fzero: return 0.0\\n        if s == finf: return math_float_inf\\n        if s == fninf: return -math_float_inf\\n        return math_float_inf/math_float_inf\\n    if bc > 53:\\n        sign, man, exp, bc = normalize1(sign, man, exp, bc, 53, rnd)\\n    if sign:\\n        man = -man\\n    try:\\n        return math.ldexp(man, exp)\\n    except OverflowError:\\n        if strict:\\n            raise\\n        # Overflow to infinity\\n        if exp + bc > 0:\\n            if sign:\\n                return -math_float_inf\\n            else:\\n                return math_float_inf\\n        # Underflow to zero\\n        return 0.0\\n\\ndef from_rational(p, q, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from a rational number p/q, round if\\n    necessary.\\\"\\\"\\\"\\n    return mpf_div(from_int(p), from_int(q), prec, rnd)\\n\\ndef to_rational(s):\\n    \\\"\\\"\\\"Convert a raw mpf to a rational number. Return integers (p, q)\\n    such that s = p/q exactly.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if sign:\\n        man = -man\\n    if bc == -1:\\n        raise ValueError(\\\"cannot convert %s to a rational number\\\" % man)\\n    if exp >= 0:\\n        return man * (1<<exp), 1\\n    else:\\n        return man, 1<<(-exp)\\n\\ndef to_fixed(s, prec):\\n    \\\"\\\"\\\"Convert a raw mpf to a fixed-point big integer\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    offset = exp + prec\\n    if sign:\\n        if offset >= 0: return (-man) << offset\\n        else:           return (-man) >> (-offset)\\n    else:\\n        if offset >= 0: return man << offset\\n        else:           return man >> (-offset)\\n\\n\\n##############################################################################\\n##############################################################################\\n\\n#----------------------------------------------------------------------------#\\n#                       Arithmetic operations, etc.                          #\\n#----------------------------------------------------------------------------#\\n\\ndef mpf_rand(prec):\\n    \\\"\\\"\\\"Return a raw mpf chosen randomly from [0, 1), with prec bits\\n    in the mantissa.\\\"\\\"\\\"\\n    global getrandbits\\n    if not getrandbits:\\n        import random\\n        getrandbits = random.getrandbits\\n    return from_man_exp(getrandbits(prec), -prec, prec, round_floor)\\n\\ndef mpf_eq(s, t):\\n    \\\"\\\"\\\"Test equality of two raw mpfs. This is simply tuple comparison\\n    unless either number is nan, in which case the result is False.\\\"\\\"\\\"\\n    if not s[1] or not t[1]:\\n        if s == fnan or t == fnan:\\n            return False\\n    return s == t\\n\\ndef mpf_hash(s):\\n    # Duplicate the new hash algorithm introduces in Python 3.2.\\n    if sys.version_info >= (3, 2):\\n        ssign, sman, sexp, sbc = s\\n\\n        # Handle special numbers\\n        if not sman:\\n            if s == fnan: return sys.hash_info.nan\\n            if s == finf: return sys.hash_info.inf\\n            if s == fninf: return -sys.hash_info.inf\\n        h = sman % HASH_MODULUS\\n        if sexp >= 0:\\n            sexp = sexp % HASH_BITS\\n        else:\\n            sexp = HASH_BITS - 1 - ((-1 - sexp) % HASH_BITS)\\n        h = (h << sexp) % HASH_MODULUS\\n        if ssign: h = -h\\n        if h == -1: h = -2\\n        return int(h)\\n    else:\\n        try:\\n            # Try to be compatible with hash values for floats and ints\\n            return hash(to_float(s, strict=1))\\n        except OverflowError:\\n            # We must unfortunately sacrifice compatibility with ints here.\\n            # We could do hash(man << exp) when the exponent is positive, but\\n            # this would cause unreasonable inefficiency for large numbers.\\n            return hash(s)\\n\\ndef mpf_cmp(s, t):\\n    \\\"\\\"\\\"Compare the raw mpfs s and t. Return -1 if s < t, 0 if s == t,\\n    and 1 if s > t. (Same convention as Python's cmp() function.)\\\"\\\"\\\"\\n\\n    # In principle, a comparison amounts to determining the sign of s-t.\\n    # A full subtraction is relatively slow, however, so we first try to\\n    # look at the components.\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n\\n    # Handle zeros and special numbers\\n    if not sman or not tman:\\n        if s == fzero: return -mpf_sign(t)\\n        if t == fzero: return mpf_sign(s)\\n        if s == t: return 0\\n        # Follow same convention as Python's cmp for float nan\\n        if t == fnan: return 1\\n        if s == finf: return 1\\n        if t == fninf: return 1\\n        return -1\\n    # Different sides of zero\\n    if ssign != tsign:\\n        if not ssign: return 1\\n        return -1\\n    # This reduces to direct integer comparison\\n    if sexp == texp:\\n        if sman == tman:\\n            return 0\\n        if sman > tman:\\n            if ssign: return -1\\n            else:     return 1\\n        else:\\n            if ssign: return 1\\n            else:     return -1\\n    # Check position of the highest set bit in each number. If\\n    # different, there is certainly an inequality.\\n    a = sbc + sexp\\n    b = tbc + texp\\n    if ssign:\\n        if a < b: return 1\\n        if a > b: return -1\\n    else:\\n        if a < b: return -1\\n        if a > b: return 1\\n\\n    # Both numbers have the same highest bit. Subtract to find\\n    # how the lower bits compare.\\n    delta = mpf_sub(s, t, 5, round_floor)\\n    if delta[0]:\\n        return -1\\n    return 1\\n\\ndef mpf_lt(s, t):\\n    if s == fnan or t == fnan:\\n        return False\\n    return mpf_cmp(s, t) < 0\\n\\ndef mpf_le(s, t):\\n    if s == fnan or t == fnan:\\n        return False\\n    return mpf_cmp(s, t) <= 0\\n\\ndef mpf_gt(s, t):\\n    if s == fnan or t == fnan:\\n        return False\\n    return mpf_cmp(s, t) > 0\\n\\ndef mpf_ge(s, t):\\n    if s == fnan or t == fnan:\\n        return False\\n    return mpf_cmp(s, t) >= 0\\n\\ndef mpf_min_max(seq):\\n    min = max = seq[0]\\n    for x in seq[1:]:\\n        if mpf_lt(x, min): min = x\\n        if mpf_gt(x, max): max = x\\n    return min, max\\n\\ndef mpf_pos(s, prec=0, rnd=round_fast):\\n    \\\"\\\"\\\"Calculate 0+s for a raw mpf (i.e., just round s to the specified\\n    precision).\\\"\\\"\\\"\\n    if prec:\\n        sign, man, exp, bc = s\\n        if (not man) and exp:\\n            return s\\n        return normalize1(sign, man, exp, bc, prec, rnd)\\n    return s\\n\\ndef mpf_neg(s, prec=None, rnd=round_fast):\\n    \\\"\\\"\\\"Negate a raw mpf (return -s), rounding the result to the\\n    specified precision. The prec argument can be omitted to do the\\n    operation exactly.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        if exp:\\n            if s == finf: return fninf\\n            if s == fninf: return finf\\n        return s\\n    if not prec:\\n        return (1-sign, man, exp, bc)\\n    return normalize1(1-sign, man, exp, bc, prec, rnd)\\n\\ndef mpf_abs(s, prec=None, rnd=round_fast):\\n    \\\"\\\"\\\"Return abs(s) of the raw mpf s, rounded to the specified\\n    precision. The prec argument can be omitted to generate an\\n    exact result.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if (not man) and exp:\\n        if s == fninf:\\n            return finf\\n        return s\\n    if not prec:\\n        if sign:\\n            return (0, man, exp, bc)\\n        return s\\n    return normalize1(0, man, exp, bc, prec, rnd)\\n\\ndef mpf_sign(s):\\n    \\\"\\\"\\\"Return -1, 0, or 1 (as a Python int, not a raw mpf) depending on\\n    whether s is negative, zero, or positive. (Nan is taken to give 0.)\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        if s == finf: return 1\\n        if s == fninf: return -1\\n        return 0\\n    return (-1) ** sign\\n\\ndef mpf_add(s, t, prec=0, rnd=round_fast, _sub=0):\\n    \\\"\\\"\\\"\\n    Add the two raw mpf values s and t.\\n\\n    With prec=0, no rounding is performed. Note that this can\\n    produce a very large mantissa (potentially too large to fit\\n    in memory) if exponents are far apart.\\n    \\\"\\\"\\\"\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    tsign ^= _sub\\n    # Standard case: two nonzero, regular numbers\\n    if sman and tman:\\n        offset = sexp - texp\\n        if offset:\\n            if offset > 0:\\n                # Outside precision range; only need to perturb\\n                if offset > 100 and prec:\\n                    delta = sbc + sexp - tbc - texp\\n                    if delta > prec + 4:\\n                        offset = prec + 4\\n                        sman <<= offset\\n                        if tsign == ssign: sman += 1\\n                        else:              sman -= 1\\n                        return normalize1(ssign, sman, sexp-offset,\\n                            bitcount(sman), prec, rnd)\\n                # Add\\n                if ssign == tsign:\\n                    man = tman + (sman << offset)\\n                # Subtract\\n                else:\\n                    if ssign: man = tman - (sman << offset)\\n                    else:     man = (sman << offset) - tman\\n                    if man >= 0:\\n                        ssign = 0\\n                    else:\\n                        man = -man\\n                        ssign = 1\\n                bc = bitcount(man)\\n                return normalize1(ssign, man, texp, bc, prec or bc, rnd)\\n            elif offset < 0:\\n                # Outside precision range; only need to perturb\\n                if offset < -100 and prec:\\n                    delta = tbc + texp - sbc - sexp\\n                    if delta > prec + 4:\\n                        offset = prec + 4\\n                        tman <<= offset\\n                        if ssign == tsign: tman += 1\\n                        else:              tman -= 1\\n                        return normalize1(tsign, tman, texp-offset,\\n                            bitcount(tman), prec, rnd)\\n                # Add\\n                if ssign == tsign:\\n                    man = sman + (tman << -offset)\\n                # Subtract\\n                else:\\n                    if tsign: man = sman - (tman << -offset)\\n                    else:     man = (tman << -offset) - sman\\n                    if man >= 0:\\n                        ssign = 0\\n                    else:\\n                        man = -man\\n                        ssign = 1\\n                bc = bitcount(man)\\n                return normalize1(ssign, man, sexp, bc, prec or bc, rnd)\\n        # Equal exponents; no shifting necessary\\n        if ssign == tsign:\\n            man = tman + sman\\n        else:\\n            if ssign: man = tman - sman\\n            else:     man = sman - tman\\n            if man >= 0:\\n                ssign = 0\\n            else:\\n                man = -man\\n                ssign = 1\\n        bc = bitcount(man)\\n        return normalize(ssign, man, texp, bc, prec or bc, rnd)\\n    # Handle zeros and special numbers\\n    if _sub:\\n        t = mpf_neg(t)\\n    if not sman:\\n        if sexp:\\n            if s == t or tman or not texp:\\n                return s\\n            return fnan\\n        if tman:\\n            return normalize1(tsign, tman, texp, tbc, prec or tbc, rnd)\\n        return t\\n    if texp:\\n        return t\\n    if sman:\\n        return normalize1(ssign, sman, sexp, sbc, prec or sbc, rnd)\\n    return s\\n\\ndef mpf_sub(s, t, prec=0, rnd=round_fast):\\n    \\\"\\\"\\\"Return the difference of two raw mpfs, s-t. This function is\\n    simply a wrapper of mpf_add that changes the sign of t.\\\"\\\"\\\"\\n    return mpf_add(s, t, prec, rnd, 1)\\n\\ndef mpf_sum(xs, prec=0, rnd=round_fast, absolute=False):\\n    \\\"\\\"\\\"\\n    Sum a list of mpf values efficiently and accurately\\n    (typically no temporary roundoff occurs). If prec=0,\\n    the final result will not be rounded either.\\n\\n    There may be roundoff error or cancellation if extremely\\n    large exponent differences occur.\\n\\n    With absolute=True, sums the absolute values.\\n    \\\"\\\"\\\"\\n    man = 0\\n    exp = 0\\n    max_extra_prec = prec*2 or 1000000  # XXX\\n    special = None\\n    for x in xs:\\n        xsign, xman, xexp, xbc = x\\n        if xman:\\n            if xsign and not absolute:\\n                xman = -xman\\n            delta = xexp - exp\\n            if xexp >= exp:\\n                # x much larger than existing sum?\\n                # first: quick test\\n                if (delta > max_extra_prec) and \\\\\\n                    ((not man) or delta-bitcount(abs(man)) > max_extra_prec):\\n                    man = xman\\n                    exp = xexp\\n                else:\\n                    man += (xman << delta)\\n            else:\\n                delta = -delta\\n                # x much smaller than existing sum?\\n                if delta-xbc > max_extra_prec:\\n                    if not man:\\n                        man, exp = xman, xexp\\n                else:\\n                    man = (man << delta) + xman\\n                    exp = xexp\\n        elif xexp:\\n            if absolute:\\n                x = mpf_abs(x)\\n            special = mpf_add(special or fzero, x, 1)\\n    # Will be inf or nan\\n    if special:\\n        return special\\n    return from_man_exp(man, exp, prec, rnd)\\n\\ndef gmpy_mpf_mul(s, t, prec=0, rnd=round_fast):\\n    \\\"\\\"\\\"Multiply two raw mpfs\\\"\\\"\\\"\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    sign = ssign ^ tsign\\n    man = sman*tman\\n    if man:\\n        bc = bitcount(man)\\n        if prec:\\n            return normalize1(sign, man, sexp+texp, bc, prec, rnd)\\n        else:\\n            return (sign, man, sexp+texp, bc)\\n    s_special = (not sman) and sexp\\n    t_special = (not tman) and texp\\n    if not s_special and not t_special:\\n        return fzero\\n    if fnan in (s, t): return fnan\\n    if (not tman) and texp: s, t = t, s\\n    if t == fzero: return fnan\\n    return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]\\n\\ndef gmpy_mpf_mul_int(s, n, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Multiply by a Python integer.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        return mpf_mul(s, from_int(n), prec, rnd)\\n    if not n:\\n        return fzero\\n    if n < 0:\\n        sign ^= 1\\n        n = -n\\n    man *= n\\n    return normalize(sign, man, exp, bitcount(man), prec, rnd)\\n\\ndef python_mpf_mul(s, t, prec=0, rnd=round_fast):\\n    \\\"\\\"\\\"Multiply two raw mpfs\\\"\\\"\\\"\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    sign = ssign ^ tsign\\n    man = sman*tman\\n    if man:\\n        bc = sbc + tbc - 1\\n        bc += int(man>>bc)\\n        if prec:\\n            return normalize1(sign, man, sexp+texp, bc, prec, rnd)\\n        else:\\n            return (sign, man, sexp+texp, bc)\\n    s_special = (not sman) and sexp\\n    t_special = (not tman) and texp\\n    if not s_special and not t_special:\\n        return fzero\\n    if fnan in (s, t): return fnan\\n    if (not tman) and texp: s, t = t, s\\n    if t == fzero: return fnan\\n    return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]\\n\\ndef python_mpf_mul_int(s, n, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Multiply by a Python integer.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        return mpf_mul(s, from_int(n), prec, rnd)\\n    if not n:\\n        return fzero\\n    if n < 0:\\n        sign ^= 1\\n        n = -n\\n    man *= n\\n    # Generally n will be small\\n    if n < 1024:\\n        bc += bctable[int(n)] - 1\\n    else:\\n        bc += bitcount(n) - 1\\n    bc += int(man>>bc)\\n    return normalize(sign, man, exp, bc, prec, rnd)\\n\\n\\nif BACKEND == 'gmpy':\\n    mpf_mul = gmpy_mpf_mul\\n    mpf_mul_int = gmpy_mpf_mul_int\\nelse:\\n    mpf_mul = python_mpf_mul\\n    mpf_mul_int = python_mpf_mul_int\\n\\ndef mpf_shift(s, n):\\n    \\\"\\\"\\\"Quickly multiply the raw mpf s by 2**n without rounding.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if not man:\\n        return s\\n    return sign, man, exp+n, bc\\n\\ndef mpf_frexp(x):\\n    \\\"\\\"\\\"Convert x = y*2**n to (y, n) with abs(y) in [0.5, 1) if nonzero\\\"\\\"\\\"\\n    sign, man, exp, bc = x\\n    if not man:\\n        if x == fzero:\\n            return (fzero, 0)\\n        else:\\n            raise ValueError\\n    return mpf_shift(x, -bc-exp), bc+exp\\n\\ndef mpf_div(s, t, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Floating-point division\\\"\\\"\\\"\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    if not sman or not tman:\\n        if s == fzero:\\n            if t == fzero: raise ZeroDivisionError\\n            if t == fnan: return fnan\\n            return fzero\\n        if t == fzero:\\n            raise ZeroDivisionError\\n        s_special = (not sman) and sexp\\n        t_special = (not tman) and texp\\n        if s_special and t_special:\\n            return fnan\\n        if s == fnan or t == fnan:\\n            return fnan\\n        if not t_special:\\n            if t == fzero:\\n                return fnan\\n            return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)]\\n        return fzero\\n    sign = ssign ^ tsign\\n    if tman == 1:\\n        return normalize1(sign, sman, sexp-texp, sbc, prec, rnd)\\n    # Same strategy as for addition: if there is a remainder, perturb\\n    # the result a few bits outside the precision range before rounding\\n    extra = prec - sbc + tbc + 5\\n    if extra < 5:\\n        extra = 5\\n    quot, rem = divmod(sman<<extra, tman)\\n    if rem:\\n        quot = (quot<<1) + 1\\n        extra += 1\\n        return normalize1(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd)\\n    return normalize(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd)\\n\\ndef mpf_rdiv_int(n, t, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Floating-point division n/t with a Python integer as numerator\\\"\\\"\\\"\\n    sign, man, exp, bc = t\\n    if not n or not man:\\n        return mpf_div(from_int(n), t, prec, rnd)\\n    if n < 0:\\n        sign ^= 1\\n        n = -n\\n    extra = prec + bc + 5\\n    quot, rem = divmod(n<<extra, man)\\n    if rem:\\n        quot = (quot<<1) + 1\\n        extra += 1\\n        return normalize1(sign, quot, -exp-extra, bitcount(quot), prec, rnd)\\n    return normalize(sign, quot, -exp-extra, bitcount(quot), prec, rnd)\\n\\ndef mpf_mod(s, t, prec, rnd=round_fast):\\n    ssign, sman, sexp, sbc = s\\n    tsign, tman, texp, tbc = t\\n    if ((not sman) and sexp) or ((not tman) and texp):\\n        return fnan\\n    # Important special case: do nothing if t is larger\\n    if ssign == tsign and texp > sexp+sbc:\\n        return s\\n    # Another important special case: this allows us to do e.g. x % 1.0\\n    # to find the fractional part of x, and it will work when x is huge.\\n    if tman == 1 and sexp > texp+tbc:\\n        return fzero\\n    base = min(sexp, texp)\\n    sman = (-1)**ssign * sman\\n    tman = (-1)**tsign * tman\\n    man = (sman << (sexp-base)) % (tman << (texp-base))\\n    if man >= 0:\\n        sign = 0\\n    else:\\n        man = -man\\n        sign = 1\\n    return normalize(sign, man, base, bitcount(man), prec, rnd)\\n\\nreciprocal_rnd = {\\n  round_down : round_up,\\n  round_up : round_down,\\n  round_floor : round_ceiling,\\n  round_ceiling : round_floor,\\n  round_nearest : round_nearest\\n}\\n\\nnegative_rnd = {\\n  round_down : round_down,\\n  round_up : round_up,\\n  round_floor : round_ceiling,\\n  round_ceiling : round_floor,\\n  round_nearest : round_nearest\\n}\\n\\ndef mpf_pow_int(s, n, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Compute s**n, where s is a raw mpf and n is a Python integer.\\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n\\n    if (not man) and exp:\\n        if s == finf:\\n            if n > 0: return s\\n            if n == 0: return fnan\\n            return fzero\\n        if s == fninf:\\n            if n > 0: return [finf, fninf][n & 1]\\n            if n == 0: return fnan\\n            return fzero\\n        return fnan\\n\\n    n = int(n)\\n    if n == 0: return fone\\n    if n == 1: return mpf_pos(s, prec, rnd)\\n    if n == 2:\\n        _, man, exp, bc = s\\n        if not man:\\n            return fzero\\n        man = man*man\\n        if man == 1:\\n            return (0, MPZ_ONE, exp+exp, 1)\\n        bc = bc + bc - 2\\n        bc += bctable[int(man>>bc)]\\n        return normalize1(0, man, exp+exp, bc, prec, rnd)\\n    if n == -1: return mpf_div(fone, s, prec, rnd)\\n    if n < 0:\\n        inverse = mpf_pow_int(s, -n, prec+5, reciprocal_rnd[rnd])\\n        return mpf_div(fone, inverse, prec, rnd)\\n\\n    result_sign = sign & n\\n\\n    # Use exact integer power when the exact mantissa is small\\n    if man == 1:\\n        return (result_sign, MPZ_ONE, exp*n, 1)\\n    if bc*n < 1000:\\n        man **= n\\n        return normalize1(result_sign, man, exp*n, bitcount(man), prec, rnd)\\n\\n    # Use directed rounding all the way through to maintain rigorous\\n    # bounds for interval arithmetic\\n    rounds_down = (rnd == round_nearest) or \\\\\\n        shifts_down[rnd][result_sign]\\n\\n    # Now we perform binary exponentiation. Need to estimate precision\\n    # to avoid rounding errors from temporary operations. Roughly log_2(n)\\n    # operations are performed.\\n    workprec = prec + 4*bitcount(n) + 4\\n    _, pm, pe, pbc = fone\\n    while 1:\\n        if n & 1:\\n            pm = pm*man\\n            pe = pe+exp\\n            pbc += bc - 2\\n            pbc = pbc + bctable[int(pm >> pbc)]\\n            if pbc > workprec:\\n                if rounds_down:\\n                    pm = pm >> (pbc-workprec)\\n                else:\\n                    pm = -((-pm) >> (pbc-workprec))\\n                pe += pbc - workprec\\n                pbc = workprec\\n            n -= 1\\n            if not n:\\n                break\\n        man = man*man\\n        exp = exp+exp\\n        bc = bc + bc - 2\\n        bc = bc + bctable[int(man >> bc)]\\n        if bc > workprec:\\n            if rounds_down:\\n                man = man >> (bc-workprec)\\n            else:\\n                man = -((-man) >> (bc-workprec))\\n            exp += bc - workprec\\n            bc = workprec\\n        n = n // 2\\n\\n    return normalize(result_sign, pm, pe, pbc, prec, rnd)\\n\\n\\ndef mpf_perturb(x, eps_sign, prec, rnd):\\n    \\\"\\\"\\\"\\n    For nonzero x, calculate x + eps with directed rounding, where\\n    eps < prec relatively and eps has the given sign (0 for\\n    positive, 1 for negative).\\n\\n    With rounding to nearest, this is taken to simply normalize\\n    x to the given precision.\\n    \\\"\\\"\\\"\\n    if rnd == round_nearest:\\n        return mpf_pos(x, prec, rnd)\\n    sign, man, exp, bc = x\\n    eps = (eps_sign, MPZ_ONE, exp+bc-prec-1, 1)\\n    if sign:\\n        away = (rnd in (round_down, round_ceiling)) ^ eps_sign\\n    else:\\n        away = (rnd in (round_up, round_ceiling)) ^ eps_sign\\n    if away:\\n        return mpf_add(x, eps, prec, rnd)\\n    else:\\n        return mpf_pos(x, prec, rnd)\\n\\n\\n#----------------------------------------------------------------------------#\\n#                              Radix conversion                              #\\n#----------------------------------------------------------------------------#\\n\\ndef to_digits_exp(s, dps):\\n    \\\"\\\"\\\"Helper function for representing the floating-point number s as\\n    a decimal with dps digits. Returns (sign, string, exponent) where\\n    sign is '' or '-', string is the digit string, and exponent is\\n    the decimal exponent as an int.\\n\\n    If inexact, the decimal representation is rounded toward zero.\\\"\\\"\\\"\\n\\n    # Extract sign first so it doesn't mess up the string digit count\\n    if s[0]:\\n        sign = '-'\\n        s = mpf_neg(s)\\n    else:\\n        sign = ''\\n    _sign, man, exp, bc = s\\n\\n    if not man:\\n        return '', '0', 0\\n\\n    bitprec = int(dps * math.log(10,2)) + 10\\n\\n    # Cut down to size\\n    # TODO: account for precision when doing this\\n    exp_from_1 = exp + bc\\n    if abs(exp_from_1) > 3500:\\n        from .libelefun import mpf_ln2, mpf_ln10\\n        # Set b = int(exp * log(2)/log(10))\\n        # If exp is huge, we must use high-precision arithmetic to\\n        # find the nearest power of ten\\n        expprec = bitcount(abs(exp)) + 5\\n        tmp = from_int(exp)\\n        tmp = mpf_mul(tmp, mpf_ln2(expprec))\\n        tmp = mpf_div(tmp, mpf_ln10(expprec), expprec)\\n        b = to_int(tmp)\\n        s = mpf_div(s, mpf_pow_int(ften, b, bitprec), bitprec)\\n        _sign, man, exp, bc = s\\n        exponent = b\\n    else:\\n        exponent = 0\\n\\n    # First, calculate mantissa digits by converting to a binary\\n    # fixed-point number and then converting that number to\\n    # a decimal fixed-point number.\\n    fixprec = max(bitprec - exp - bc, 0)\\n    fixdps = int(fixprec / math.log(10,2) + 0.5)\\n    sf = to_fixed(s, fixprec)\\n    sd = bin_to_radix(sf, fixprec, 10, fixdps)\\n    digits = numeral(sd, base=10, size=dps)\\n\\n    exponent += len(digits) - fixdps - 1\\n    return sign, digits, exponent\\n\\ndef to_str(s, dps, strip_zeros=True, min_fixed=None, max_fixed=None,\\n    show_zero_exponent=False):\\n    \\\"\\\"\\\"\\n    Convert a raw mpf to a decimal floating-point literal with at\\n    most `dps` decimal digits in the mantissa (not counting extra zeros\\n    that may be inserted for visual purposes).\\n\\n    The number will be printed in fixed-point format if the position\\n    of the leading digit is strictly between min_fixed\\n    (default = min(-dps/3,-5)) and max_fixed (default = dps).\\n\\n    To force fixed-point format always, set min_fixed = -inf,\\n    max_fixed = +inf. To force floating-point format, set\\n    min_fixed >= max_fixed.\\n\\n    The literal is formatted so that it can be parsed back to a number\\n    by to_str, float() or Decimal().\\n    \\\"\\\"\\\"\\n\\n    # Special numbers\\n    if not s[1]:\\n        if s == fzero:\\n            if dps: t = '0.0'\\n            else:   t = '.0'\\n            if show_zero_exponent:\\n                t += 'e+0'\\n            return t\\n        if s == finf: return '+inf'\\n        if s == fninf: return '-inf'\\n        if s == fnan: return 'nan'\\n        raise ValueError\\n\\n    if min_fixed is None: min_fixed = min(-(dps//3), -5)\\n    if max_fixed is None: max_fixed = dps\\n\\n    # to_digits_exp rounds to floor.\\n    # This sometimes kills some instances of \\\"...00001\\\"\\n    sign, digits, exponent = to_digits_exp(s, dps+3)\\n\\n    # No digits: show only .0; round exponent to nearest\\n    if not dps:\\n        if digits[0] in '56789':\\n            exponent += 1\\n        digits = \\\".0\\\"\\n\\n    else:\\n        # Rounding up kills some instances of \\\"...99999\\\"\\n        if len(digits) > dps and digits[dps] in '56789':\\n            digits = digits[:dps]\\n            i = dps - 1\\n            while i >= 0 and digits[i] == '9':\\n                i -= 1\\n            if i >= 0:\\n                digits = digits[:i] + str(int(digits[i]) + 1) + '0' * (dps - i - 1)\\n            else:\\n                digits = '1' + '0' * (dps - 1)\\n                exponent += 1\\n        else:\\n            digits = digits[:dps]\\n\\n        # Prettify numbers close to unit magnitude\\n        if min_fixed < exponent < max_fixed:\\n            if exponent < 0:\\n                digits = (\\\"0\\\"*int(-exponent)) + digits\\n                split = 1\\n            else:\\n                split = exponent + 1\\n                if split > dps:\\n                    digits += \\\"0\\\"*(split-dps)\\n            exponent = 0\\n        else:\\n            split = 1\\n\\n        digits = (digits[:split] + \\\".\\\" + digits[split:])\\n\\n        if strip_zeros:\\n            # Clean up trailing zeros\\n            digits = digits.rstrip('0')\\n            if digits[-1] == \\\".\\\":\\n                digits += \\\"0\\\"\\n\\n    if exponent == 0 and dps and not show_zero_exponent: return sign + digits\\n    if exponent >= 0: return sign + digits + \\\"e+\\\" + str(exponent)\\n    if exponent < 0: return sign + digits + \\\"e\\\" + str(exponent)\\n\\ndef str_to_man_exp(x, base=10):\\n    \\\"\\\"\\\"Helper function for from_str.\\\"\\\"\\\"\\n    x = x.lower().rstrip('l')\\n    # Verify that the input is a valid float literal\\n    float(x)\\n    # Split into mantissa, exponent\\n    parts = x.split('e')\\n    if len(parts) == 1:\\n        exp = 0\\n    else: # == 2\\n        x = parts[0]\\n        exp = int(parts[1])\\n    # Look for radix point in mantissa\\n    parts = x.split('.')\\n    if len(parts) == 2:\\n        a, b = parts[0], parts[1].rstrip('0')\\n        exp -= len(b)\\n        x = a + b\\n    x = MPZ(int(x, base))\\n    return x, exp\\n\\nspecial_str = {'inf':finf, '+inf':finf, '-inf':fninf, 'nan':fnan}\\n\\ndef from_str(x, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Create a raw mpf from a decimal literal, rounding in the\\n    specified direction if the input number cannot be represented\\n    exactly as a binary floating-point number with the given number of\\n    bits. The literal syntax accepted is the same as for Python\\n    floats.\\n\\n    TODO: the rounding does not work properly for large exponents.\\n    \\\"\\\"\\\"\\n    x = x.lower().strip()\\n    if x in special_str:\\n        return special_str[x]\\n\\n    if '/' in x:\\n        p, q = x.split('/')\\n        p, q = p.rstrip('l'), q.rstrip('l')\\n        return from_rational(int(p), int(q), prec, rnd)\\n\\n    man, exp = str_to_man_exp(x, base=10)\\n\\n    # XXX: appropriate cutoffs & track direction\\n    # note no factors of 5\\n    if abs(exp) > 400:\\n        s = from_int(man, prec+10)\\n        s = mpf_mul(s, mpf_pow_int(ften, exp, prec+10), prec, rnd)\\n    else:\\n        if exp >= 0:\\n            s = from_int(man * 10**exp, prec, rnd)\\n        else:\\n            s = from_rational(man, 10**-exp, prec, rnd)\\n    return s\\n\\n# Binary string conversion. These are currently mainly used for debugging\\n# and could use some improvement in the future\\n\\ndef from_bstr(x):\\n    man, exp = str_to_man_exp(x, base=2)\\n    man = MPZ(man)\\n    sign = 0\\n    if man < 0:\\n        man = -man\\n        sign = 1\\n    bc = bitcount(man)\\n    return normalize(sign, man, exp, bc, bc, round_floor)\\n\\ndef to_bstr(x):\\n    sign, man, exp, bc = x\\n    return ['','-'][sign] + numeral(man, size=bitcount(man), base=2) + (\\\"e%i\\\" % exp)\\n\\n\\n#----------------------------------------------------------------------------#\\n#                                Square roots                                #\\n#----------------------------------------------------------------------------#\\n\\n\\ndef mpf_sqrt(s, prec, rnd=round_fast):\\n    \\\"\\\"\\\"\\n    Compute the square root of a nonnegative mpf value. The\\n    result is correctly rounded.\\n    \\\"\\\"\\\"\\n    sign, man, exp, bc = s\\n    if sign:\\n        raise ComplexResult(\\\"square root of a negative number\\\")\\n    if not man:\\n        return s\\n    if exp & 1:\\n        exp -= 1\\n        man <<= 1\\n        bc += 1\\n    elif man == 1:\\n        return normalize1(sign, man, exp//2, bc, prec, rnd)\\n    shift = max(4, 2*prec-bc+4)\\n    shift += shift & 1\\n    if rnd in 'fd':\\n        man = isqrt(man<<shift)\\n    else:\\n        man, rem = sqrtrem(man<<shift)\\n        # Perturb up\\n        if rem:\\n            man = (man<<1)+1\\n            shift += 2\\n    return from_man_exp(man, (exp-shift)//2, prec, rnd)\\n\\ndef mpf_hypot(x, y, prec, rnd=round_fast):\\n    \\\"\\\"\\\"Compute the Euclidean norm sqrt(x**2 + y**2) of two raw mpfs\\n    x and y.\\\"\\\"\\\"\\n    if y == fzero: return mpf_abs(x, prec, rnd)\\n    if x == fzero: return mpf_abs(y, prec, rnd)\\n    hypot2 = mpf_add(mpf_mul(x,x), mpf_mul(y,y), prec+4)\\n    return mpf_sqrt(hypot2, prec, rnd)\\n\\n\\nif BACKEND == 'sage':\\n    try:\\n        import sage.libs.mpmath.ext_libmp as ext_lib\\n        mpf_add = ext_lib.mpf_add\\n        mpf_sub = ext_lib.mpf_sub\\n        mpf_mul = ext_lib.mpf_mul\\n        mpf_div = ext_lib.mpf_div\\n        mpf_sqrt = ext_lib.mpf_sqrt\\n    except ImportError:\\n        pass\\n\\n\\nfrom .libmpf import (prec_to_dps, dps_to_prec, repr_dps,\\n  round_down, round_up, round_floor, round_ceiling, round_nearest,\\n  to_pickable, from_pickable, ComplexResult,\\n  fzero, fnzero, fone, fnone, ftwo, ften, fhalf, fnan, finf, fninf,\\n  math_float_inf, round_int, normalize, normalize1,\\n  from_man_exp, from_int, to_man_exp, to_int, mpf_ceil, mpf_floor,\\n  mpf_nint, mpf_frac,\\n  from_float, from_npfloat, from_Decimal, to_float, from_rational, to_rational, to_fixed,\\n  mpf_rand, mpf_eq, mpf_hash, mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_ge,\\n  mpf_pos, mpf_neg, mpf_abs, mpf_sign, mpf_add, mpf_sub, mpf_sum,\\n  mpf_mul, mpf_mul_int, mpf_shift, mpf_frexp,\\n  mpf_div, mpf_rdiv_int, mpf_mod, mpf_pow_int,\\n  mpf_perturb,\\n  to_digits_exp, to_str, str_to_man_exp, from_str, from_bstr, to_bstr,\\n  mpf_sqrt, mpf_hypot)\\n\\nfrom .libmpc import (mpc_one, mpc_zero, mpc_two, mpc_half,\\n  mpc_is_inf, mpc_is_infnan, mpc_to_str, mpc_to_complex, mpc_hash,\\n  mpc_conjugate, mpc_is_nonzero, mpc_add, mpc_add_mpf,\\n  mpc_sub, mpc_sub_mpf, mpc_pos, mpc_neg, mpc_shift, mpc_abs,\\n  mpc_arg, mpc_floor, mpc_ceil,  mpc_nint, mpc_frac, mpc_mul, mpc_square,\\n  mpc_mul_mpf, mpc_mul_imag_mpf, mpc_mul_int,\\n  mpc_div, mpc_div_mpf, mpc_reciprocal, mpc_mpf_div,\\n  complex_int_pow, mpc_pow, mpc_pow_mpf, mpc_pow_int,\\n  mpc_sqrt, mpc_nthroot, mpc_cbrt, mpc_exp, mpc_log, mpc_cos, mpc_sin,\\n  mpc_tan, mpc_cos_pi, mpc_sin_pi, mpc_cosh, mpc_sinh, mpc_tanh,\\n  mpc_atan, mpc_acos, mpc_asin, mpc_asinh, mpc_acosh, mpc_atanh,\\n  mpc_fibonacci, mpf_expj, mpf_expjpi, mpc_expj, mpc_expjpi,\\n  mpc_cos_sin, mpc_cos_sin_pi)\\n\\nfrom .libelefun import (ln2_fixed, mpf_ln2, ln10_fixed, mpf_ln10,\\n  pi_fixed, mpf_pi, e_fixed, mpf_e, phi_fixed, mpf_phi,\\n  degree_fixed, mpf_degree,\\n  mpf_pow, mpf_nthroot, mpf_cbrt, log_int_fixed, agm_fixed,\\n  mpf_log, mpf_log_hypot, mpf_exp, mpf_cos_sin, mpf_cos, mpf_sin, mpf_tan,\\n  mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi, mpf_cosh_sinh,\\n  mpf_cosh, mpf_sinh, mpf_tanh, mpf_atan, mpf_atan2, mpf_asin,\\n  mpf_acos, mpf_asinh, mpf_acosh, mpf_atanh, mpf_fibonacci)\\n\\nfrom .libhyper import (NoConvergence, make_hyp_summator,\\n  mpf_erf, mpf_erfc, mpf_ei, mpc_ei, mpf_e1, mpc_e1, mpf_expint,\\n  mpf_ci_si, mpf_ci, mpf_si, mpc_ci, mpc_si, mpf_besseljn,\\n  mpc_besseljn, mpf_agm, mpf_agm1, mpc_agm, mpc_agm1,\\n  mpf_ellipk, mpc_ellipk, mpf_ellipe, mpc_ellipe)\\n\\nfrom .gammazeta import (catalan_fixed, mpf_catalan,\\n  khinchin_fixed, mpf_khinchin, glaisher_fixed, mpf_glaisher,\\n  apery_fixed, mpf_apery, euler_fixed, mpf_euler, mertens_fixed,\\n  mpf_mertens, twinprime_fixed, mpf_twinprime,\\n  mpf_bernoulli, bernfrac, mpf_gamma_int,\\n  mpf_factorial, mpc_factorial, mpf_gamma, mpc_gamma,\\n  mpf_loggamma, mpc_loggamma, mpf_rgamma, mpc_rgamma,\\n  mpf_harmonic, mpc_harmonic, mpf_psi0, mpc_psi0,\\n  mpf_psi, mpc_psi, mpf_zeta_int, mpf_zeta, mpc_zeta,\\n  mpf_altzeta, mpc_altzeta, mpf_zetasum, mpc_zetasum)\\n\\nfrom .libmpi import (mpi_str,\\n  mpi_from_str, mpi_to_str,\\n  mpi_eq, mpi_ne,\\n  mpi_lt, mpi_le, mpi_gt, mpi_ge,\\n  mpi_add, mpi_sub, mpi_delta, mpi_mid,\\n  mpi_pos, mpi_neg, mpi_abs, mpi_mul, mpi_div, mpi_exp,\\n  mpi_log, mpi_sqrt, mpi_pow_int, mpi_pow, mpi_cos_sin,\\n  mpi_cos, mpi_sin, mpi_tan, mpi_cot,\\n  mpi_atan, mpi_atan2,\\n  mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow,\\n  mpci_abs, mpci_pow, mpci_exp, mpci_log, mpci_cos, mpci_sin,\\n  mpi_gamma, mpci_gamma, mpi_loggamma, mpci_loggamma,\\n  mpi_rgamma, mpci_rgamma, mpi_factorial, mpci_factorial)\\n\\nfrom .libintmath import (trailing, bitcount, numeral, bin_to_radix,\\n  isqrt, isqrt_small, isqrt_fast, sqrt_fixed, sqrtrem, ifib, ifac,\\n  list_primes, isprime, moebius, gcd, eulernum, stirling1, stirling2)\\n\\nfrom .backend import (gmpy, sage, BACKEND, STRICT, MPZ, MPZ_TYPE,\\n  MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_THREE, MPZ_FIVE, int_types,\\n  HASH_MODULUS, HASH_BITS)\\n\\n\\nimport os\\nimport sys\\n\\n#----------------------------------------------------------------------------#\\n# Support GMPY for high-speed large integer arithmetic.                      #\\n#                                                                            #\\n# To allow an external module to handle arithmetic, we need to make sure     #\\n# that all high-precision variables are declared of the correct type. MPZ    #\\n# is the constructor for the high-precision type. It defaults to Python's    #\\n# long type but can be assinged another type, typically gmpy.mpz.            #\\n#                                                                            #\\n# MPZ must be used for the mantissa component of an mpf and must be used     #\\n# for internal fixed-point operations.                                       #\\n#                                                                            #\\n# Side-effects                                                               #\\n# 1) \\\"is\\\" cannot be used to test for special values. Must use \\\"==\\\".          #\\n# 2) There are bugs in GMPY prior to v1.02 so we must use v1.03 or later.    #\\n#----------------------------------------------------------------------------#\\n\\n# So we can import it from this module\\ngmpy = None\\nsage = None\\nsage_utils = None\\n\\nif sys.version_info[0] < 3:\\n    python3 = False\\nelse:\\n    python3 = True\\n\\nBACKEND = 'python'\\n\\nif not python3:\\n    MPZ = long\\n    xrange = xrange\\n    basestring = basestring\\n\\n    def exec_(_code_, _globs_=None, _locs_=None):\\n        \\\"\\\"\\\"Execute code in a namespace.\\\"\\\"\\\"\\n        if _globs_ is None:\\n            frame = sys._getframe(1)\\n            _globs_ = frame.f_globals\\n            if _locs_ is None:\\n                _locs_ = frame.f_locals\\n            del frame\\n        elif _locs_ is None:\\n            _locs_ = _globs_\\n        exec(\\\"\\\"\\\"exec _code_ in _globs_, _locs_\\\"\\\"\\\")\\nelse:\\n    MPZ = int\\n    xrange = range\\n    basestring = str\\n\\n    import builtins\\n    exec_ = getattr(builtins, \\\"exec\\\")\\n\\n# Define constants for calculating hash on Python 3.2.\\nif sys.version_info >= (3, 2):\\n    HASH_MODULUS = sys.hash_info.modulus\\n    if sys.hash_info.width == 32:\\n        HASH_BITS = 31\\n    else:\\n        HASH_BITS = 61\\nelse:\\n    HASH_MODULUS = None\\n    HASH_BITS = None\\n\\nif 'MPMATH_NOGMPY' not in os.environ:\\n    try:\\n        try:\\n            import gmpy2 as gmpy\\n        except ImportError:\\n            try:\\n                import gmpy\\n            except ImportError:\\n                raise ImportError\\n        if gmpy.version() >= '1.03':\\n            BACKEND = 'gmpy'\\n            MPZ = gmpy.mpz\\n    except:\\n        pass\\n\\nif ('MPMATH_NOSAGE' not in os.environ and 'SAGE_ROOT' in os.environ or\\n        'MPMATH_SAGE' in os.environ):\\n    try:\\n        import sage.all\\n        import sage.libs.mpmath.utils as _sage_utils\\n        sage = sage.all\\n        sage_utils = _sage_utils\\n        BACKEND = 'sage'\\n        MPZ = sage.Integer\\n    except:\\n        pass\\n\\nif 'MPMATH_STRICT' in os.environ:\\n    STRICT = True\\nelse:\\n    STRICT = False\\n\\nMPZ_TYPE = type(MPZ(0))\\nMPZ_ZERO = MPZ(0)\\nMPZ_ONE = MPZ(1)\\nMPZ_TWO = MPZ(2)\\nMPZ_THREE = MPZ(3)\\nMPZ_FIVE = MPZ(5)\\n\\ntry:\\n    if BACKEND == 'python':\\n        int_types = (int, long)\\n    else:\\n        int_types = (int, long, MPZ_TYPE)\\nexcept NameError:\\n    if BACKEND == 'python':\\n        int_types = (int,)\\n    else:\\n        int_types = (int, MPZ_TYPE)\",\"difficulty\":\"easy\",\"domain\":\"Code Repository Understanding\",\"length\":\"long\",\"question\":\"In the function that calculates the derivative of given functions, which of the following keyword arguments are all recognized?\",\"sub_domain\":\"Code repo QA\"}","display_format":"text","language":"","answer_status":"published","assets":[],"source_url":"https://huggingface.co/datasets/zai-org/LongBench-v2","history":"initial import","indexing_mode":"noindex","subproblems":[],"grids":[]}