def pmf_dict(colors, nsample):
    """
    Returns a dictionary of the PMF of the multivariate hypergeometric distr.

    The keys are the points in the support, and the values are the
    corresponding probabilities.

    Example
    -------
    >>> pmf = multivariate_hypergeometric.pmf_dict([4, 5, 6], 6)
    >>> len(pmf)
    24
    >>> float(pmf[2, 2, 2])
    0.1798201798201798
    """
    _validate_params(colors, nsample)
    total = sum(colors)
    denom = mpmath.binomial(total, nsample)
    pmf = {}
    for coords in support(colors, nsample):
        numer = 1
        for color, k in zip(colors, coords):
            numer *= mpmath.binomial(color, k)
        prob = numer/denom
        pmf[tuple(coords)] = prob
    return pmf
Esempio n. 2
0
def getNthDelannoyNumber( n ):
    result = 0

    for k in arange( 0, fadd( real( n ), 1 ) ):
        result = fadd( result, fmul( binomial( n, k ), binomial( fadd( n, k ), k ) ) )

    return result
Esempio n. 3
0
 def mhyper(self,q,m,n,k):
     u = min(self.tag_length ,n)-1
     A = binomial(m,q)*binomial(n,k-q)
     B = hyper([1,q-k,q-m],[1+q,1-k+n+q], 1)
     C = -binomial(m,1+u)*binomial(n,k-1-u)
     D = hyper([1,1-k+u,1-m+u],[2+u,2-k+n+u], 1)
     return mathlog(float((A*B + C*D) / binomial(m+n, k)))
Esempio n. 4
0
 def __compute_surprise_weighted_by_quadrature(self, mi, pi, m, p):
     f = lambda i: mpmath.binomial(
         self.pi, i) * mpmath.binomial(self.p - self.pi, self.m - i) / \
         mpmath.binomial(self.p, self.m)
     # +- 0.5 is because of the continuity correction
     return float(
         -mpmath.log10(mpmath.quad(f, [self.mi - 0.5, self.m + 0.5])))
Esempio n. 5
0
def getNthAperyNumber( n ):
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
Esempio n. 6
0
def getNthMotzkinNumber( n ):
    result = 0

    for j in arange( 0, floor( fdiv( real( n ), 3 ) ) + 1 ):
        result = fadd( result, fprod( [ power( -1, j ), binomial( fadd( n, 1 ), j ),
                                      binomial( fsub( fmul( 2, n ), fmul( 3, j ) ), n ) ] ) )

    return fdiv( result, fadd( n, 1 ) )
Esempio n. 7
0
 def __compute_surprise_weighted(self, mi, pi, m, p):
     b1 = mpmath.binomial(pi, mi)
     b2 = mpmath.binomial(p - pi, m - mi)
     b3 = mpmath.binomial(p, m)
     h3f2 = mpmath.hyp3f2(1, mi - m, mi - pi, mi + 1, -m + mi + p - pi + 1,
                          1)
     #h3f2 = hyper1([mpf(1),mi-m, mi-pi], [mpf(1),mpf(1)+mi, mi+p-pi-m+mpf(1)], 10, 10)
     log10cdf = mpmath.log10(b1) + mpmath.log10(b2) + mpmath.log10(
         h3f2) - mpmath.log10(b3)
     return -float(log10cdf)
Esempio n. 8
0
def binomial(A, B):
    """
    A ! B
    """
    try:
        if isinstance(A, int) and isinstance(B, int):
            return int(mpmath.binomial(B, A))

        return float(mpmath.binomial(B, A))
    except ValueError:
        assertError("DOMAIN ERROR")
Esempio n. 9
0
def sf(k, ntotal, ngood, nsample):
    """
    Survival function of the hypergeometric distribution.
    """
    _validate(ntotal, ngood, nsample)
    h = mpmath.hyp3f2(1, k + 1 - ngood, k + 1 - nsample, k + 2,
                      ntotal + k + 2 - ngood - nsample, 1)
    num = (mpmath.binomial(nsample, k + 1) *
           mpmath.binomial(ntotal - nsample, ngood - k - 1))
    den = mpmath.binomial(ntotal, ngood)
    sf = (num / den) * h
    return sf
Esempio n. 10
0
def getNthAperyNumber( n ):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
Esempio n. 11
0
def getNthMotzkinNumber( n ):
    '''
    http://oeis.org/A001006

    a(n) = sum((-1)^j*binomial(n+1, j)*binomial(2n-3j, n), j=0..floor(n/3))/(n+1)
    '''
    result = 0

    for j in arange( 0, floor( fdiv( real( n ), 3 ) ) + 1 ):
        result = fadd( result, fprod( [ power( -1, j ), binomial( fadd( n, 1 ), j ),
                                      binomial( fsub( fmul( 2, n ), fmul( 3, j ) ), n ) ] ) )

    return fdiv( result, fadd( n, 1 ) )
def pmf(k, ntotal, ngood, untilnbad):
    """
    Probability mass function of the negative hypergeometric distribution.
    """
    _validate(ntotal, ngood, untilnbad)

    if k < 0 or k > ngood:
        return mpmath.mp.zero

    with mpmath.extradps(5):
        b1 = mpmath.binomial(k + untilnbad - 1, k)
        b2 = mpmath.binomial(ntotal - untilnbad - k, ngood - k)
        b3 = mpmath.binomial(ntotal, ngood)
        return b1 * (b2 / b3)
def test_Wigner_coefficient():
    import mpmath
    mpmath.mp.dps = 4 * sf.ell_max
    i = 0
    for twoell in range(2*sf.ell_max + 1):
        for twomp in range(-twoell, twoell + 1, 2):
            for twom in range(-twoell, twoell + 1, 2):
                tworho_min = max(0, twomp - twom)
                a = sf._Wigner_coefficient(twoell, twomp, twom)
                b = float(mpmath.sqrt(mpmath.fac((twoell + twom)//2) * mpmath.fac((twoell - twom)//2)
                                      / (mpmath.fac((twoell + twomp)//2) * mpmath.fac((twoell - twomp)//2)))
                          * mpmath.binomial((twoell + twomp)//2, tworho_min//2)
                          * mpmath.binomial((twoell - twomp)//2, (twoell - twom - tworho_min)//2))
                assert np.allclose(a, b), (twoell, twomp, twom, i, sf._Wigner_index(twoell, twomp, twom))
                i += 1
Esempio n. 14
0
def getNthDelannoyNumber(n):
    if n == 1:
        return 3

    precision = int(fmul(n, 0.8))

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for k in arange(0, fadd(n, 1)):
        result = fadd(result, fmul(binomial(n, k), binomial(fadd(n, k), k)))

    return result
Esempio n. 15
0
 def binomial(n, k):
     if abs(k) > 1e8*(abs(n) + 1):
         # The binomial is rapidly oscillating in this region,
         # and the function is numerically ill-defined. Don't
         # compare values here.
         return np.nan
     return mpmath.binomial(n, k)
Esempio n. 16
0
def round5_fp_fast(n, h, q, p, t, f, mu, B, add_coeff=False, verbose=False):
    ## use this for full precision
    ###   dif = mp_zeros(q)
    ###   dif[0] = mp.mpf(1.0)
    ## use this for double precision
    dif = np.zeros(q)
    dif[0] = 1.0
    # determine number of times to convolve the term differences in term s*e.
    #If prime cyclotomic, it is h, if ring swithing or scaler, just h/2.
    # Only h(2h) convolutions as we start with probability gen function
    # for difference between two random variables with q-p rounding noise
    # This can be done as we consider balanced secrets
    w = h
    if add_coeff:
        w = 2 * w
    # computation of convolution of w variables (we have the sum of w variables)
    for i in range(w):
        dif = spec_conv_comb_qp(dif, q, p)
    # convert to mpf if we were double
    dif = np.array([mp.mpf(dif[i]) for i in range(len(dif))])
    # normalize, just in case
    dif /= dif.sum()
    # second convolution with the p to t noise. Single time to account for coefficient compression from p to t.
    dif = spec_conv_comb_pt(dif, q, p, t)
    # Decryption failure ranges for case when parameter B>1
    up_fail = (q + (1 << B)) // (1 << (B + 1))
    down_fail = (q * ((1 << (B + 1)) - 1) + (1 << B)) // (1 << (B + 1))
    # Bit failure probability (bfp). Distribution goes from 0 to q-1, highly provable values are centered around 0, thus, we sum the central part.
    bfp = dif[up_fail:down_fail].sum()
    # Failure probability after error correction
    ffp = mp.mpf(0)
    for j in range(f + 1, mu + 1):
        ffp += (mp.binomial(mu, j) * mp.power(bfp, j) *
                mp.power(mp.mpf(1) - bfp, (mu - j)))
    return float(mp.log(ffp, 2))
def daubechies(N):
    # make polynomial
    q_y = [mpmath.binomial(N - 1 + k, k) for k in reversed(range(N))]

    # get polynomial roots y[k]
    y = mpmath.mp.polyroots(q_y, maxsteps=200, extraprec=64)

    z = []
    for yk in y:
        # subustitute y = -1/4z + 1/2 - 1/4/z to factor f(y) = y - y[k]
        f = [mpmath.mpf('-1/4'), mpmath.mpf('1/2') - yk, mpmath.mpf('-1/4')]

        # get polynomial roots z[k] within unit circle
        z += [zk for zk in mpmath.mp.polyroots(f) if mpmath.fabs(zk) < 1]

    # make polynomial using the roots
    h0z = mpmath.sqrt('2')
    for zk in z:
        h0z *= sympy.sympify('(z-zk)/(1-zk)').subs('zk', zk)

    # adapt vanishing moments
    hz = (sympy.sympify('(1+z)/2')**N * h0z).expand()

    # get scaling coefficients
    return [sympy.re(hz.coeff('z', k)) for k in reversed(range(N * 2))]
Esempio n. 18
0
def sign_test_precision(preds_system_A, preds_system_B, ground_truth, q=0.5):
    ties = 0
    plus = 0
    minus = 0

    for i, gt in enumerate(ground_truth):
        if preds_system_A[i] == preds_system_B[i]:
            ties += 1
            continue

        else:
            if preds_system_A[i] == gt:
                plus += 1
                continue

            else:
                minus += 1
                continue

    all_samples = len(ground_truth)
    k = np.ceil(ties / 2) + min(plus, minus)

    N = 2 * np.ceil(ties / 2) + plus + minus

    print("The k is: ", k)
    print("The N is: ", N)

    res = 0
    for idx in range(0, int(k)):
        res += (mpmath.binomial(N, idx) * mpmath.power(q, idx) * mpmath.power(
            (1 - q), (N - idx)))
        #res += (nCr(N, idx)*pow(q, idx)*pow((1-q), (N-idx)))

    return (2 * res)
Esempio n. 19
0
def getNthSchroederNumber( n ):
    if real( n ) == 1:
        return 1

    if n < 0:
        raise ValueError( '\'nth_schroeder\' expects a non-negative argument' )

    n = fsub( n, 1 )

    result = 0

    for k in arange( 0, fadd( n, 1 ) ):
        result = fadd( result, fdiv( fprod( [ power( 2, k ), binomial( n, k ),
                                              binomial( n, fsub( k, 1 ) ) ] ), n ) )

    return result
Esempio n. 20
0
def daubechies(N):
    # p vanishing moments.
    p = int(N / 2)
    # make polynomial; see Mallat, 7.96
    Py = [sm.binomial(p - 1 + k, k) for k in reversed(range(p))]

    # get polynomial roots y[k]
    Py_roots = sm.mp.polyroots(Py, maxsteps=200, extraprec=64)

    z = []
    for yk in Py_roots:
        # substitute y = -1/4z + 1/2 - 1/4/z to factor f(y) = y - y[k]
        # We've found the roots of P(y). We need the roots of Q(z) = P((1-z-1/z)/4)
        f = [sm.mpf('-1/4'), sm.mpf('1/2') - yk, sm.mpf('-1/4')]

        # get polynomial roots z[k]
        z += sm.mp.polyroots(f)

    # make polynomial using the roots within unit circle
    h0z = sm.sqrt('2')
    for zk in z:
        if sm.fabs(zk) < 1:
            # This calculation is superior to Mallat, (equation between 7.96 and 7.97)
            h0z *= sympy.sympify('(z-zk)/(1-zk)').subs('zk', zk)

    # adapt vanishing moments
    hz = (sympy.sympify('(1+z)/2')**p * h0z).expand()

    # get scaling coefficients
    return [sympy.re(hz.coeff('z', k)) for k in reversed(range(p * 2))]
Esempio n. 21
0
def get_prob_correct_sync(k, pc):
    """prob = \sum_{l=0}^{ceil(k/2)-1} (k_choose_l) * (pc)^l * (1 - pc)^(k-l)
    """
    retval = 0
    lmax = mpmath.ceil(float(k)/2) - 1
    for l in range(0, lmax + 1):
        retval += mpmath.binomial(k,l) * mpmath.power(pc, l) * \
            mpmath.power(1 - pc, k - l)
    return retval
Esempio n. 22
0
def getNthDelannoyNumber( n ):
    if real_int( n ) == 1:
        return 3

    if n < 0:
        raise ValueError( '\'nth_delannoy\' expects a non-negative argument' )

    precision = int( fmul( n, 0.8 ) )

    if ( mp.dps < precision ):
        mp.dps = precision

    result = 0

    for k in arange( 0, fadd( real( n ), 1 ) ):
        result = fadd( result, fmul( binomial( n, k ), binomial( fadd( n, k ), k ) ) )

    return result
Esempio n. 23
0
def get_prob_correct_async(k, pc, rprime):
    """prob = \sum_{l=0}^{k-rprime} (k_choose_l) * (pc)^l * (1 - pc)^(k-l)
    """
    retval = 0
    lmax = k - rprime
    for l in range(0, lmax + 1):
        retval += mpmath.binomial(k,l) * mpmath.power(pc, l) * \
            mpmath.power(1 - pc, k - l)
    return retval
Esempio n. 24
0
def round5_fp_fast(d, n, h, q, p, t, f, mu, B, add_coeff=False, verbose=False):

    #   dif = mp_zeros(q)                   # full precision
    #   dif[0] = mp.mpf(1.0)

    dif = np.zeros(q)  # double precision approximation
    dif[0] = 1.0

    scale = 0
    for w in h:  # w = weight of +-scale
        scale += 1
        if add_coeff:
            w = 2 * w  # closer to 2 * w - 1 if h ~= w/2
        w *= 2  # double it here; can use floats
        if verbose:
            print "\nw" + str(scale), "=", w

        for i in range(w):
            dif = conv_comb_qp(dif, q, p, scale)
            if verbose:
                sys.stdout.write('.')
                sys.stdout.flush()
    if verbose:
        print "done"

    # convert to mpf if we were double
    dif = np.array([mp.mpf(dif[i]) for i in range(len(dif))])
    dif /= dif.sum()  # normalize, just in case

    if verbose:
        print "eqp*R + eqp'*S".ljust(16) + str_stats(dif)

    dif = conv_comb_pt(dif, q, p, t)
    if verbose:
        print "rounded p->t".ljust(16) + str_stats(dif)

    # Decryption failure ranges for case when parameter B>1
    up_fail = (q + (1 << B)) // (1 << (B + 1))
    down_fail = (q * ((1 << (B + 1)) - 1) + (1 << B)) // (1 << (B + 1))

    bfp = dif[up_fail:down_fail].sum()

    if verbose:
        print "per bit failure probability:", str_log2(bfp)
        print bfp

    ffp = mp.mpf(0)
    for j in range(f + 1, mu + 1):
        ffp += (mp.binomial(mu, j) * mp.power(bfp, j) *
                mp.power(mp.mpf(1) - bfp, (mu - j)))

    if verbose:
        print "more than", f, "errors in", mu, "bits:", str_log2(ffp)
        print ffp

    return float(mp.log(ffp, 2))
Esempio n. 25
0
def pmf(k, n, p):
    """
    Probability mass function of the binomial distribution.
    """
    _validate_np(n, p)
    with mpmath.extradps(5):
        p = mpmath.mpf(p)
        return (mpmath.binomial(n, k) *
                mpmath.power(p, k) *
                mpmath.power(1 - p, n - k))
Esempio n. 26
0
def u_binom(N):
  out = np.zeros((len(x),len(t)))
  out = out + 0.5*W(0)[...,None]*np.ones(len(t))
  with mpmath.workdps(workdps):
    for n in range(1,N):
      coeff = np.zeros(len(x))    
      for m in range(n):     
        coeff = coeff + (-1)**((n-1)-m)*mpmath.binomial(n-1,m)*W(m+1)
      out = out + coeff[...,None]*((t/(2*tau))**n)/mpmath.factorial(n)       
  return out
Esempio n. 27
0
def getNthMenageNumber( n ):
    if n < 0:
        raise ValueError( '\'menage\' requires a non-negative argument' )
    elif n in [ 1, 2 ]:
        return 0
    elif n in [ 0, 3 ]:
        return 1
    else:
        return nsum( lambda k: fdiv( fprod( [ power( -1, k ), fmul( 2, n ), binomial( fsub( fmul( 2, n ), k ), k ),
                                            fac( fsub( n, k ) ) ] ), fsub( fmul( 2, n ), k ) ), [ 0, n ] )
Esempio n. 28
0
def getNthAperyNumber(n):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    precision = int(fmul(n, 1.6))

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for k in arange(0, n + 1):
        result = fadd(
            result,
            fmul(power(binomial(n, k), 2), power(binomial(fadd(n, k), k), 2)))

    return result
Esempio n. 29
0
def estimate_S_from_counts(dfA, dfB):
    """
    Give an unbiased estimate for the value of S given the counts. 
    dfA & dfB need to have a column "read_count" & "cdr3_nt"
    """
    cAs = dfA.groupby("cdr3_nt").read_count.sum().to_frame()
    cBs = dfB.groupby("cdr3_nt").read_count.sum().to_frame()
    cs = cAs.merge(cBs, left_index=True, right_index=True,
                   how='outer', suffixes={'_A', '_B'})
    cs = cs.fillna(0)
    cs["read_count"] = cs["read_count_A"] + cs["read_count_B"]
    M2 = len(cBs)
    M1 = len(cAs)
    # The formula below remove the bias associated with sampling
    Sest = sum([1 + (mpmath.binomial(0, int(c)) 
                  - mpmath.binomial(M2, int(c))
                  - mpmath.binomial(M1, int(c)))
             /mpmath.binomial(M1+M2, int(c))  
             for c in cs["read_count"].values if int(c) != 0])
    return float(Sest)
Esempio n. 30
0
 def iterate(rest, n_rest):
     if rest and n_rest > 0:
         for k in range(n_rest + 1):
             for coeff, next in iterate(rest[1:], n_rest - k):
                 if k == 0:
                     this_factor = []
                 else:
                     this_factor = [Expression('Power', rest[0], Integer(k))]
                 yield (int(mpmath.binomial(n_rest, k) * coeff), this_factor + next)
     elif n_rest == 0:
         yield (sympy.Integer(1), [])
Esempio n. 31
0
def getNthAperyNumber( n ):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    if n < 0:
        raise ValueError( '\'nth_apery\' expects a non-negative argument' )

    precision = int( fmul( n, 1.6 ) )

    if ( mp.dps < precision ):
        mp.dps = precision

    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
Esempio n. 32
0
def getNthSchroederNumber(n):
    if n == 1:
        return 1

    n = fsub(n, 1)

    result = 0

    precision = int(fmul(n, 0.8))

    if mp.dps < precision:
        mp.dps = precision

    for k in arange(0, fadd(n, 1)):
        result = fadd(
            result,
            fdiv(fprod([power(2, k),
                        binomial(n, k),
                        binomial(n, fsub(k, 1))]), n))

    return result
Esempio n. 33
0
 def apply_inexact(self, n, k, evaluation):
     'Binomial[n_?InexactNumberQ, k_?NumberQ]'
     
     with workprec(min_prec(n, k)):
         n = gmpy2mpmath(n.value)
         k = gmpy2mpmath(k.value)
         result = mpmath.binomial(n, k)
         try:
             result = mpmath2gmpy(result)
         except SpecialValueError, exc:
             return Symbol(exc.name)
         number = Number.from_mp(result)
         return number
Esempio n. 34
0
    def apply_inexact(self, n, k, evaluation):
        'Binomial[n_?InexactNumberQ, k_?NumberQ]'

        with workprec(min_prec(n, k)):
            n = gmpy2mpmath(n.value)
            k = gmpy2mpmath(k.value)
            result = mpmath.binomial(n, k)
            try:
                result = mpmath2gmpy(result)
            except SpecialValueError, exc:
                return Symbol(exc.name)
            number = Number.from_mp(result)
            return number
Esempio n. 35
0
def test_Wigner_coefficient():
    import mpmath
    mpmath.mp.dps = 4 * sf.ell_max
    i = 0
    for twoell in range(2 * sf.ell_max + 1):
        for twomp in range(-twoell, twoell + 1, 2):
            for twom in range(-twoell, twoell + 1, 2):
                tworho_min = max(0, twomp - twom)
                a = sf._Wigner_coefficient(twoell, twomp, twom)
                b = float(
                    mpmath.sqrt(
                        mpmath.fac((twoell + twom) // 2) * mpmath.fac(
                            (twoell - twom) // 2) /
                        (mpmath.fac((twoell + twomp) // 2) * mpmath.fac(
                            (twoell - twomp) // 2))) * mpmath.binomial(
                                (twoell + twomp) // 2, tworho_min // 2) *
                    mpmath.binomial((twoell - twomp) // 2,
                                    (twoell - twom - tworho_min) // 2))
                assert np.allclose(a,
                                   b), (twoell, twomp, twom, i,
                                        sf._Wigner_index(twoell, twomp, twom))
                i += 1
Esempio n. 36
0
 def binomial(n, k, nonzero=False):
     if abs(k) > 1e8*(abs(n) + 1):
         # The binomial is rapidly oscillating in this region,
         # and the function is numerically ill-defined. Don't
         # compare values here.
         return np.nan
     if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15:
         # close to a zero of the function: mpmath and scipy
         # will not round here the same, so the test needs to be
         # run with an absolute tolerance
         if nonzero:
             bad_points.append((float(n), float(k)))
             return np.nan
     return mpmath.binomial(n, k)
Esempio n. 37
0
 def binomial(n, k, nonzero=False):
     if abs(k) > 1e8 * (abs(n) + 1):
         # The binomial is rapidly oscillating in this region,
         # and the function is numerically ill-defined. Don't
         # compare values here.
         return np.nan
     if n < k and abs(float(n - k) - np.round(float(n - k))) < 1e-15:
         # close to a zero of the function: mpmath and scipy
         # will not round here the same, so the test needs to be
         # run with an absolute tolerance
         if nonzero:
             bad_points.append((float(n), float(k)))
             return np.nan
     return mpmath.binomial(n, k)
Esempio n. 38
0
def getNthMotzkinNumber(n):
    '''
    http://oeis.org/A001006

    a(n) = sum((-1)^j*binomial(n+1, j)*binomial(2n-3j, n), j=0..floor(n/3))/(n+1)
    '''
    precision = int(n)

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for j in arange(0, floor(fdiv(n, 3)) + 1):
        result = fadd(
            result,
            fprod([
                power(-1, j),
                binomial(fadd(n, 1), j),
                binomial(fsub(fmul(2, n), fmul(3, j)), n)
            ]))

    return fdiv(result, fadd(n, 1))
Esempio n. 39
0
 def iterate(rest, n_rest):
     if rest and n_rest > 0:
         for k in range(n_rest + 1):
             for coeff, next in iterate(
                     rest[1:], n_rest - k):
                 if k == 0:
                     this_factor = []
                 else:
                     this_factor = [
                         Expression('Power', rest[0],
                                    Integer(k))
                     ]
                 yield (int(
                     mpmath.binomial(n_rest, k) * coeff),
                        this_factor + next)
     elif n_rest == 0:
         yield (sympy.Integer(1), [])
Esempio n. 40
0
def moment(a, i, j):
    '''
    Calculates the j-th moment of phi_i

    Wavelet Analysis: The Scalable Structure of Information (2002)
    Howard L. Resnikoff, Raymond O.Jr. Wells
    page 262
    '''
    N = a.size

    assert j > -1

    if j == 0:
        return 1 if i == 0 else 0

    if i == 0:
        return moment_i0(a, j)

    return mpmath.nsum(lambda k: binomial(j,k)*mpmath.power(i, (j-k))*moment_i0(a, k), [0, j])
Esempio n. 41
0
def getNthMenageNumber(n):
    '''https://oeis.org/A000179'''
    if n == 1:
        return -1

    if n == 2:
        return 0

    if n in [0, 3]:
        return 1

    return nsum(
        lambda k: fdiv(
            fprod([
                power(-1, k),
                fmul(2, n),
                binomial(fsub(fmul(2, n), k), k),
                fac(fsub(n, k))
            ]), fsub(fmul(2, n), k)), [0, n])
Esempio n. 42
0
def moment_i0(a, j):
    '''
    Calculates the j-th moment of phi_0

    Wavelet Analysis: The Scalable Structure of Information (2002)
    Howard L. Resnikoff, Raymond O.Jr. Wells
    page 262
    '''
    N = a.size

    if j == 0:
        return 1

    s = mpmath.nsum(lambda k: binomial(j,k)*moment_i0(a, k)*
            mpmath.nsum(lambda i: a[int(i)]*mpmath.power(i, j-k),
                        [0, N-1]),
            [0, j-1])

    _2 = mp.mpmathify(2)
    return s/(_2*(mpmath.power(_2, j)-1))
def AIntegrand(r,s,t,i):
    f = mpmath.gamma
    g = mpmath.factorial
    x = mpmath.binomial(s,i)*(f(i+1/2)/g(r+i))*(f(1/2+r+i)/f(3/2+r+t+i))
    return x
Esempio n. 44
0
def getBinomial( n, k ):
    return binomial( n, k )
Esempio n. 45
0
def getBinomialOperator(n, k):
    return binomial(n, k)
 def summand(l):
     return mp.binomial(s, l) * ( fallingFactorial(4, r+l) / mp.power(4, K+l) ) * lambdaMergerRate(b, K+l)
Esempio n. 47
0
def getLahNumber( n, k ):
    return fmul( power( -1, n ), fdiv( fmul( binomial( real( n ), real( k ) ), fac( fsub( n, 1 ) ) ), fac( fsub( k, 1 ) ) ) )
Esempio n. 48
0
def getNarayanaNumber( n, k ):
    return fdiv( fmul( binomial( n, k ), binomial( n, fsub( k, 1 ) ) ), n )
Esempio n. 49
0
def multinomial_mpm(params):
    """High precision version of the multinomial function"""
    if len(params) == 1:
        return 1
    return mpm.binomial(sum(params), params[-1]) * multinomial_mpm(params[:-1])
Esempio n. 50
0
def getNthCatalanNumberOperator(n):
    return fdiv(binomial(fmul(2, n), n), fadd(n, 1))
Esempio n. 51
0
import mpmath as mp
s = 0
for r in range(1, 16):
    s += mp.binomial(15, r) * r**2 / mp.binomial(15, r - 1)
print s
r = 15
print(-2 * r**3 + 45 * r**2 + 47 * r) / 6
from spherical_functions import ell_max

# The coefficients were originally produced with the following code,
# though obviously this doesn't need to be run each time.

import numpy as np
import mpmath

mpmath.mp.dps = 4 * ell_max

_binomial_coefficients = np.empty((((2 * ell_max + 1) * (2 * ell_max + 2)) // 2,), dtype=float)
i = 0
for n in range(2 * ell_max + 1):
    for k in range(n + 1):
        _binomial_coefficients[i] = float(mpmath.binomial(n, k))
        i += 1
print(i, _binomial_coefficients.shape)
np.save('binomial_coefficients', _binomial_coefficients)

_ladder_operator_coefficients = np.empty((((2*ell_max + 3) * ell_max + 1),), dtype=float)
i = 0
for twoell in range(2*ell_max + 1):
    for twom in range(-twoell, twoell + 1, 2):
        _ladder_operator_coefficients[i] = mpmath.sqrt((twoell * (twoell + 2) - twom * (twom + 2))/4)
        i += 1
print(i, _ladder_operator_coefficients.shape)
np.save('ladder_operator_coefficients', _ladder_operator_coefficients)

# _Wigner_coefficients = np.empty(((4 * ell_max ** 3 + 12 * ell_max ** 2 + 11 * ell_max + 3) // 3,), dtype=float)
# i = 0
# for ell in range(ell_max + 1):
Esempio n. 53
0
def getNthPascalLine( n ):
    for i in arange( 0, real( n ) ):
        yield binomial( n - 1, i )
Esempio n. 54
0
def getNthCatalanNumber( n ):
    return fdiv( binomial( fmul( 2, real( n ) ), n ), fadd( n, 1 ) )