Esempio n. 1
0
def test_gosper_sum():
    assert gosper_sum(1, (k, 0, n)) == 1 + n
    assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2
    assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6
    assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4

    assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1

    assert gosper_sum(factorial(k), (k, 0, n)) is None
    assert gosper_sum(binomial(n, k), (k, 0, n)) is None

    assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None
    assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None

    assert gosper_sum(k*factorial(k), k) == factorial(k)
    assert gosper_sum(
        k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1

    assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0
    assert gosper_sum((
        -1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n

    assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \
        (2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1)

    # issue 6033:
    assert gosper_sum(
        n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \
        (n, 0, m)) == -a*b*(exp(m*log(a))*exp(m*log(b))*factorial(a)* \
        factorial(b) - factorial(a + m)*factorial(b + m))/(factorial(a)* \
        factorial(b)*factorial(a + m)*factorial(b + m))
Esempio n. 2
0
def test_gosper_sum_AeqB_part1():
    f1a = n**4
    f1b = n**3*2**n
    f1c = 1/(n**2 + sqrt(5)*n - 1)
    f1d = n**4*4**n/binomial(2*n, n)
    f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
    f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
    f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
    f1h = n*factorial(n - S(1)/2)**2/factorial(n + 1)**2

    g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
    g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)

    g = gosper_sum(f1a, (n, 0, m))
    assert g is not None and simplify(g - g1a) == 0
    g = gosper_sum(f1b, (n, 0, m))
    assert g is not None and simplify(g - g1b) == 0
    g = gosper_sum(f1c, (n, 0, m))
    assert g is not None # and simplify(g - g1c) == 0
    g = gosper_sum(f1d, (n, 0, m))
    assert g is not None # and simplify(g - g1d) == 0
    g = gosper_sum(f1e, (n, 0, m))
    assert g is not None # and simplify(g - g1e) == 0
    g = gosper_sum(f1f, (n, 0, m))
    assert g is not None # and simplify(g - g1f) == 0
    g = gosper_sum(f1g, (n, 0, m))
    assert g is not None # and simplify(g - g1g) == 0
    g = gosper_sum(f1h, (n, 0, m))
    assert g is not None # and simplify(g - g1h) == 0
Esempio n. 3
0
def test_gosper_sum_AeqB_part2():
    f2a = n**2*a**n
    f2b = (n - r/2)*binomial(r, n)
    f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))

    g2a = -a*(a + 1)/(a - 1)**3 + a**(
        m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
    g2b = (m - r)*binomial(r, m)/2
    ff = factorial(1 - x)*factorial(1 + x)
    g2c = 1/ff*(
        1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))

    g = gosper_sum(f2a, (n, 0, m))
    assert g is not None and simplify(g - g2a) == 0
    g = gosper_sum(f2b, (n, 0, m))
    assert g is not None and simplify(g - g2b) == 0
    g = gosper_sum(f2c, (n, 1, m))
    assert g is not None and simplify(g - g2c) == 0

    # delete these lines and unXFAIL the nan test below when it passes
    f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
    g2d = 1/(factorial(a - 1)*factorial(
        b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
    assert simplify(
        sum(f2d.subs(n, i) for i in range(3)) - g2d.subs(m, 2)) == 0
Esempio n. 4
0
def test_binomial_rewrite():
    n = Symbol("n", integer=True)
    k = Symbol("k", integer=True)

    assert binomial(n, k).rewrite(factorial) == factorial(n) / (factorial(k) * factorial(n - k))
    assert binomial(n, k).rewrite(gamma) == gamma(n + 1) / (gamma(k + 1) * gamma(n - k + 1))
    assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
Esempio n. 5
0
def test_limit_seq():
    assert limit(Sum(1/x, (x, 1, y)) - log(y), y, oo) == EulerGamma
    assert limit(Sum(1/x, (x, 1, y)) - 1/y, y, oo) == S.Infinity
    assert (limit(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x, oo) ==
            S(3) / 4)
    assert (limit(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) /
                  (2**x*x), x, oo) == 4)
Esempio n. 6
0
def test_issue_9699():
    n, k = symbols('n k', real=True)
    x, y = symbols('x, y')
    assert combsimp((n + 1)*factorial(n)) == factorial(n + 1)
    assert combsimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y)
    assert combsimp(factorial(n)/n) == factorial(n - 1)
    assert combsimp(rf(x + n, k)*binomial(n, k)) == binomial(n, k)*gamma(k + n + x)/gamma(n + x)
Esempio n. 7
0
def test_limitseq_sum():
    from sympy.abc import x, y, z
    assert limit_seq(Sum(1/x, (x, 1, y)) - log(y), y) == S.EulerGamma
    assert limit_seq(Sum(1/x, (x, 1, y)) - 1/y, y) == S.Infinity
    assert (limit_seq(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x) ==
            S(3) / 4)
    assert (limit_seq(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) /
                  (2**x*x), x) == 4)
Esempio n. 8
0
 def dict(self):
     N, m, n = self.N, self.m, self.n
     N, m, n = list(map(sympify, (N, m, n)))
     density = dict((sympify(k),
                     Rational(binomial(m, k) * binomial(N - m, n - k),
                              binomial(N, n)))
                     for k in range(max(0, n + m - N), min(m, n) + 1))
     return density
Esempio n. 9
0
def pxbar2( i, nup, bp ):
    bp2 = float(nup)/float(numX)
    if (nup==0):    
        if (i==0):
            return 1
        else:
            return 0
    return sp.binomial(Ns,i) * bp2**i* (1-bp2)**(Ns-i)* tdown(i/float(Ns)) / sum(sp.binomial(Ns,j) * bp2**j* (1-bp2)**(Ns-j)* tdown(j/float(Ns)) for j in xrange(0,Ns+1) )
Esempio n. 10
0
def test_issue_2787():
    n, k = symbols('n k', positive=True, integer=True)
    p = symbols('p', positive=True)
    binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
    s = Sum(binomial_dist*k, (k, 0, n))
    res = s.doit().simplify()
    assert res == Piecewise((n*p, And(Or(-n + 1 < 0, -n + 1 >= 0),
        Or(-n + 1 < 0, Ne(p/(p - 1), 1)), p*Abs(1/(p - 1)) <= 1)),
        (Sum(k*p**k*(-p + 1)**(-k)*(-p + 1)**n*binomial(n, k), (k, 0, n)), True))
Esempio n. 11
0
def test_issue_2787():
    n, k = symbols('n k', positive=True, integer=True)
    p = symbols('p', positive=True)
    binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
    s = Sum(binomial_dist*k, (k, 0, n))
    res = s.doit().simplify()
    assert res == Piecewise(
        (n*p, p/Abs(p - 1) <= 1),
        ((-p + 1)**n*Sum(k*p**k*(-p + 1)**(-k)*binomial(n, k), (k, 0, n)),
        True))
Esempio n. 12
0
def test_gosper_sum_iterated():
    f1 = binomial(2*k, k)/4**k
    f2 = (1 + 2*n)*binomial(2*n, n)/4**n
    f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n)
    f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n)
    f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n)

    assert gosper_sum(f1, (k, 0, n)) == f2
    assert gosper_sum(f2, (n, 0, n)) == f3
    assert gosper_sum(f3, (n, 0, n)) == f4
    assert gosper_sum(f4, (n, 0, n)) == f5
Esempio n. 13
0
def test_evalf_fast_series():
    # Euler transformed series for sqrt(1+x)
    assert NS(Sum(
        fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)

    # Some series for exp(1)
    estr = NS(E, 100)
    assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
    assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
    assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
    assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr

    pistr = NS(pi, 100)
    # Ramanujan series for pi
    assert NS(9801/sqrt(8)/Sum(fac(
        4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
    assert NS(1/Sum(
        binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
    # Machin's formula for pi
    assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
        4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr

    # Apery's constant
    astr = NS(zeta(3), 100)
    P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
        n + 12463
    assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
        n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
    assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
              fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
Esempio n. 14
0
def _estimate_gradients_2d_global():

    #
    # Compute
    #
    #

    f1, f2, df1, df2, x = symbols(['f1', 'f2', 'df1', 'df2', 'x'])
    c = [f1, (df1 + 3*f1)/3, (df2 + 3*f2)/3, f2]

    w = 0
    for k in range(4):
        w += binomial(3, k) * c[k] * x**k*(1-x)**(3-k)

    wpp = w.diff(x, 2).expand()
    intwpp2 = (wpp**2).integrate((x, 0, 1)).expand()

    A = Matrix([[intwpp2.coeff(df1**2), intwpp2.coeff(df1*df2)/2],
                [intwpp2.coeff(df1*df2)/2, intwpp2.coeff(df2**2)]])

    B = Matrix([[intwpp2.coeff(df1).subs(df2, 0)],
                [intwpp2.coeff(df2).subs(df1, 0)]]) / 2

    print("A")
    print(A)
    print("B")
    print(B)
    print("solution")
    print(A.inv() * B)
Esempio n. 15
0
    def map_substitution(self, expr):
        assert isinstance(expr.child, prim.Derivative)
        call = expr.child.child

        if (isinstance(call.function, prim.Variable)
                and call.function.name in ["hankel_1", "bessel_j"]):
            function = call.function
            order, _ = call.parameters
            arg, = expr.values

            n_derivs = len(expr.child.variables)
            import sympy as sp

            # AS (9.1.31)
            # http://dlmf.nist.gov/10.6.7
            if order >= 0:
                order_str = str(order)
            else:
                order_str = "m"+str(-order)
            k = n_derivs
            return prim.CommonSubexpression(
                    2**(-k)*sum(
                        (-1)**idx*int(sp.binomial(k, idx)) * function(i, arg)
                        for idx, i in enumerate(range(order-k, order+k+1, 2))),
                    "d%d_%s_%s" % (n_derivs, function.name, order_str))
        else:
            return IdentityMapper.map_substitution(self, expr)
def vasicek_base(N, k, p, rho):
    """

    :param N:
    :param k:
    :param p:
    :param rho:
    :return:
    """

    zmin = - settings.SCALE
    zmax = settings.SCALE
    grid = settings.GRID_POINTS

    dz = float(zmax - zmin) / float(grid - 1)
    a = stats.norm.ppf(p, loc=0.0, scale=1.0)
    integral = 0
    for i in range(1, grid):
        z = zmin + dz * i
        arg = (a - rho * z) / math.sqrt(1 - rho * rho)
        phi_den = stats.norm.pdf(z, loc=0.0, scale=1.0)
        phi_cum = stats.norm.cdf(arg, loc=0.0, scale=1.0)
        integrant = phi_den * math.pow(phi_cum, k) * math.pow(1 - phi_cum, N - k) * binomial(N, k)
        integral = integral + integrant
    return dz * integral
def test_assoc_laguerre():
    n = Symbol("n")
    m = Symbol("m")
    alpha = Symbol("alpha")

    # generalized Laguerre polynomials:
    assert assoc_laguerre(0, alpha, x) == 1
    assert assoc_laguerre(1, alpha, x) == -x + alpha + 1
    assert assoc_laguerre(2, alpha, x).expand() == \
        (x**2/2 - (alpha + 2)*x + (alpha + 2)*(alpha + 1)/2).expand()
    assert assoc_laguerre(3, alpha, x).expand() == \
        (-x**3/6 + (alpha + 3)*x**2/2 - (alpha + 2)*(alpha + 3)*x/2 +
        (alpha + 1)*(alpha + 2)*(alpha + 3)/6).expand()

    # Test the lowest 10 polynomials with laguerre_poly, to make sure it works:
    for i in range(10):
        assert assoc_laguerre(i, 0, x).expand() == laguerre_poly(i, x)

    X = assoc_laguerre(n, m, x)
    assert isinstance(X, assoc_laguerre)

    assert assoc_laguerre(n, 0, x) == laguerre(n, x)
    assert assoc_laguerre(n, alpha, 0) == binomial(alpha + n, alpha)

    assert diff(assoc_laguerre(n, alpha, x), x) == \
        -assoc_laguerre(n - 1, alpha + 1, x)

    assert conjugate(assoc_laguerre(n, alpha, x)) == \
        assoc_laguerre(n, conjugate(alpha), conjugate(x))

    raises(ValueError, lambda: assoc_laguerre(-2.1, alpha, x))
Esempio n. 18
0
def test_uniformsum():
    n = Symbol("n", integer=True)
    _k = Symbol("k")

    X = UniformSum('x', n)
    assert density(X)(x) == (Sum((-1)**_k*(-_k + x)**(n - 1)
                        *binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1))
Esempio n. 19
0
    def translate_from(self, src_expansion, src_coeff_exprs, src_rscale,
            dvec, tgt_rscale):
        if not isinstance(src_expansion, type(self)):
            raise RuntimeError("do not know how to translate %s to "
                    "Taylor multipole expansion"
                               % type(src_expansion).__name__)

        if not self.use_rscale:
            src_rscale = 1
            tgt_rscale = 1

        logger.info("building translation operator: %s(%d) -> %s(%d): start"
                % (type(src_expansion).__name__,
                    src_expansion.order,
                    type(self).__name__,
                    self.order))

        from sumpy.tools import mi_factorial

        src_mi_to_index = dict((mi, i) for i, mi in enumerate(
            src_expansion.get_coefficient_identifiers()))

        for i, mi in enumerate(src_expansion.get_coefficient_identifiers()):
            src_coeff_exprs[i] *= mi_factorial(mi)

        result = [0] * len(self.get_full_coefficient_identifiers())
        from pytools import generate_nonnegative_integer_tuples_below as gnitb

        for i, tgt_mi in enumerate(
                self.get_full_coefficient_identifiers()):

            tgt_mi_plus_one = tuple(mi_i + 1 for mi_i in tgt_mi)

            for src_mi in gnitb(tgt_mi_plus_one):
                try:
                    src_index = src_mi_to_index[src_mi]
                except KeyError:
                    # Omitted coefficients: not life-threatening
                    continue

                contrib = src_coeff_exprs[src_index]

                for idim in range(self.dim):
                    n = tgt_mi[idim]
                    k = src_mi[idim]
                    assert n >= k
                    from sympy import binomial
                    contrib *= (binomial(n, k)
                            * sym.UnevaluatedExpr(dvec[idim]/tgt_rscale)**(n-k))

                result[i] += (
                        contrib
                        * sym.UnevaluatedExpr(src_rscale/tgt_rscale)**sum(src_mi))

            result[i] /= mi_factorial(tgt_mi)

        logger.info("building translation operator: done")
        return (
            self.derivative_wrangler.get_stored_mpole_coefficients_from_full(
                result, tgt_rscale))
Esempio n. 20
0
    def __init__(self, states, interval, differential_order):
        """
        :param states: tuple of states in beginning and end of interval
        :param interval: time interval (tuple)
        :param differential_order: grade of differential flatness :math:`\\gamma`
        """
        self.yd = states
        self.t0 = interval[0]
        self.t1 = interval[1]
        self.dt = interval[1] - interval[0]
        gamma = differential_order  # + 1 # TODO check this against notes

        # setup symbolic expressions
        tau, k = sp.symbols('tau, k')

        alpha = sp.factorial(2 * gamma + 1)

        f = sp.binomial(gamma, k) * (-1) ** k * tau ** (gamma + k + 1) / (gamma + k + 1)
        phi = alpha / sp.factorial(gamma) ** 2 * sp.summation(f, (k, 0, gamma))

        # differentiate phi(tau), index in list corresponds to order
        dphi_sym = [phi]  # init with phi(tau)
        for order in range(differential_order):
            dphi_sym.append(dphi_sym[-1].diff(tau))

        # lambdify
        self.dphi_num = []
        for der in dphi_sym:
            self.dphi_num.append(sp.lambdify(tau, der, 'numpy'))
Esempio n. 21
0
def test_rf_eval_apply():
    x, y = symbols('x,y')
    n, k = symbols('n k', integer=True)
    m = Symbol('m', integer=True, nonnegative=True)

    assert rf(nan, y) == nan
    assert rf(x, nan) == nan

    assert rf(x, y) == rf(x, y)

    assert rf(oo, 0) == 1
    assert rf(-oo, 0) == 1

    assert rf(oo, 6) == oo
    assert rf(-oo, 7) == -oo

    assert rf(oo, -6) == oo
    assert rf(-oo, -7) == oo

    assert rf(x, 0) == 1
    assert rf(x, 1) == x
    assert rf(x, 2) == x*(x + 1)
    assert rf(x, 3) == x*(x + 1)*(x + 2)
    assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)

    assert rf(x, -1) == 1/(x - 1)
    assert rf(x, -2) == 1/((x - 1)*(x - 2))
    assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))

    assert rf(1, 100) == factorial(100)

    assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
    assert isinstance(rf(x**2 + 3*x, 2), Mul)
    assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))

    assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
    assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
    raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
    assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
    raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))

    assert rf(x, m).is_integer is None
    assert rf(n, k).is_integer is None
    assert rf(n, m).is_integer is True
    assert rf(n, k + pi).is_integer is False
    assert rf(n, m + pi).is_integer is False
    assert rf(pi, m).is_integer is False

    assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
    assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
    assert rf(n, k).rewrite(factorial) == \
        factorial(n + k - 1) / factorial(n - 1)

    import random
    from mpmath import rf as mpmath_rf
    for i in range(100):
        x = -500 + 500 * random.random()
        k = -500 + 500 * random.random()
        assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
Esempio n. 22
0
def Bernstein_series(N): 
  # FIXME: check if a normalization constant is common in the definition 
  # advantage is that the basis is always positive 
  psi = []
  for k in range(0,N+1): 
    psi_k = sym.binomial(N, k)*x**k*(1-x)**(N-k)  
    psi.append(psi_k)
  return psi
Esempio n. 23
0
def test_uniformsum():
    n = Symbol("n", integer=True)
    x = Symbol("x")
    _k = Symbol("k")

    X = UniformSum(n, symbol=x)
    assert Density(X) == (Lambda(_x, Sum((-1)**_k*(-_k + _x)**(n - 1)
                         *binomial(n, _k), (_k, 0, floor(_x)))/factorial(n - 1)))
Esempio n. 24
0
def sumFibPower(n, p, viaPowers = True):
    """Sum Fib(i)^p, i = 0..n"""
    #Expand power, sum each element, then convert to fibonacci numbers
    s = 0
    for i in range(0, p+1):
        si = sumGeomAB( p-i, i, 0, n, viaPowers=viaPowers )
        s = s + binomial(p,i) * (-1)**(i) * si
    return s / (sqrts(5))**p
Esempio n. 25
0
 def _eval_wignerd(self):
     j = sympify(self.j)
     m = sympify(self.m)
     mp = sympify(self.mp)
     alpha = sympify(self.alpha)
     beta = sympify(self.beta)
     gamma = sympify(self.gamma)
     if not j.is_number:
         raise ValueError("j parameter must be numerical to evaluate, got %s", j)
     r = 0
     if beta == pi / 2:
         # Varshalovich Equation (5), Section 4.16, page 113, setting
         # alpha=gamma=0.
         for k in range(2 * j + 1):
             if k > j + mp or k > j - m or k < mp - m:
                 continue
             r += (-S(1)) ** k * binomial(j + mp, k) * binomial(j - mp, k + m - mp)
         r *= (
             (-S(1)) ** (m - mp)
             / 2 ** j
             * sqrt(factorial(j + m) * factorial(j - m) / (factorial(j + mp) * factorial(j - mp)))
         )
     else:
         # Varshalovich Equation(5), Section 4.7.2, page 87, where we set
         # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
         # then we use the Eq. (1), Section 4.4. page 79, to simplify:
         # d(j, m, mp, beta+pi) = (-1)**(j-mp) * d(j, m, -mp, beta)
         # This happens to be almost the same as in Eq.(10), Section 4.16,
         # except that we need to substitute -mp for mp.
         size, mvals = m_values(j)
         for mpp in mvals:
             r += (
                 Rotation.d(j, m, mpp, pi / 2).doit()
                 * (cos(-mpp * beta) + I * sin(-mpp * beta))
                 * Rotation.d(j, mpp, -mp, pi / 2).doit()
             )
         # Empirical normalization factor so results match Varshalovich
         # Tables 4.3-4.12
         # Note that this exact normalization does not follow from the
         # above equations
         r = r * I ** (2 * j - m - mp) * (-1) ** (2 * m)
         # Finally, simplify the whole expression
         r = simplify(r)
     r *= exp(-I * m * alpha) * exp(-I * mp * gamma)
     return r
Esempio n. 26
0
    def __new__(cls, n, symbol=None):
        n = sympify(n)

        x = symbol or SingleContinuousPSpace.create_symbol()
        k = Dummy("k")
        pdf =1/factorial(n-1)*Sum((-1)**k*binomial(n,k)*(x-k)**(n-1), (k,0,floor(x)))

        obj = SingleContinuousPSpace.__new__(cls, x, pdf, set=Interval(0,n))
        return obj
Esempio n. 27
0
def test_gosper_sum_AeqB_part2():
    f2a = n**2*a**n
    f2b = (n - r/2)*binomial(r, n)
    f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))

    g2a = -a*(a + 1)/(a - 1)**3 + a**(
        m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
    g2b = (m - r)*binomial(r, m)/2
    ff = factorial(1 - x)*factorial(1 + x)
    g2c = 1/ff*(
        1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))

    g = gosper_sum(f2a, (n, 0, m))
    assert g is not None and simplify(g - g2a) == 0
    g = gosper_sum(f2b, (n, 0, m))
    assert g is not None and simplify(g - g2b) == 0
    g = gosper_sum(f2c, (n, 1, m))
    assert g is not None and simplify(g - g2c) == 0
Esempio n. 28
0
def tdown( x ):
    alpha1 = alpha*1.0/(1.0+exp(-(x-xthresh)/thresh))
    if x > 0.0625:
        alpha1=alpha
    else:
        alpha1 = 0
    alpha1 = alpha*(1.0-exp(-x/0.1))        
    xx = 1.0-(1.0-alpha1)*(1.0-x)
    return (x) * (1 -  sum(sp.binomial(K,j) * xx**j * (1-xx)**(K-j) * psw(j) for j in xrange(0,K+1)))
Esempio n. 29
0
def S(n, k):
    if k == 0:
        return n
    elif k == 1:
        return n * (n + 1) // 2
    elif k == 2:
        return (n) * (n + 1) * (2 * n + 1) // 6
    elif k >= 3:
        return ((1 + n) ** (k + 1) - 1 - sum(binomial(k + 1, i) * S(n, i) for i in range(0, k))) // (k + 1)
Esempio n. 30
0
def ncr(n, r):
    """Number of ways to choose r elements from n

    This is in as a reminder of how the sympy api works

    >>> ncr(10, 5)
    252
    """
    return sympy.binomial(n, r)
Esempio n. 31
0
def test_rsolve():
    f = y(n + 2) - y(n + 1) - y(n)
    h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
        - sqrt(5)*(S.Half - S.Half*sqrt(5))**n

    assert rsolve(f, y(n)) in [
        C0 * (S.Half - S.Half * sqrt(5))**n + C1 *
        (S.Half + S.Half * sqrt(5))**n,
        C1 * (S.Half - S.Half * sqrt(5))**n + C0 *
        (S.Half + S.Half * sqrt(5))**n,
    ]

    assert rsolve(f, y(n), [0, 5]) == h
    assert rsolve(f, y(n), {0: 0, 1: 5}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
    assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
    assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * y(n + 2) - (n**2 + 3 * n - 2) * y(n + 1) + 2 * n * (n +
                                                                      1) * y(n)
    g = C1 * factorial(n) + C0 * 2**n
    h = -3 * factorial(n) + 3 * 2**n

    assert rsolve(f, y(n)) == g
    assert rsolve(f, y(n), []) == g
    assert rsolve(f, y(n), {}) == g

    assert rsolve(f, y(n), [0, 3]) == h
    assert rsolve(f, y(n), {0: 0, 1: 3}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - y(n - 1) - 2

    assert rsolve(f, y(n), {y(0): 0}) == 2 * n
    assert rsolve(f, y(n), {y(0): 1}) == 2 * n + 1
    assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = 3 * y(n - 1) - y(n) - 1

    assert rsolve(f, y(n), {y(0): 0}) == -3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 1}) == 3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 2}) == 3 * 3**n / 2 + S.Half

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1)
    assert rsolve(f, y(n)) == C0 / factorial(n)
    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1) - 1
    assert rsolve(f, y(n)) is None

    f = 2 * y(n - 1) + (1 - n) * y(n) / n

    assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1) * n
    assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1) * n * 2
    assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1) * n * 3

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * (n - 2) * y(n + 2) - (n + 1) * (n + 2) * y(n)

    assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n * (n - 1) * (n - 2)
    assert rsolve(f, y(n), {
        y(3): 6,
        y(4): -24
    }) == -n * (n - 1) * (n - 2) * (-1)**(n)

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    assert rsolve(Eq(y(n + 1), a * y(n)), y(n), {y(1): a}).simplify() == a**n

    assert rsolve(y(n) - a*y(n-2),y(n), \
            {y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \
            a**(n/2)*(-(-1)**n*b + a)

    f = (-16 * n**2 + 32 * n - 12) * y(n - 1) + (4 * n**2 - 12 * n + 9) * y(n)

    assert expand_func(rsolve(f, y(n), \
            {y(1): binomial(2*n + 1, 3)}).rewrite(gamma)).simplify() == \
        2**(2*n)*n*(2*n - 1)*(4*n**2 - 1)/12

    assert (rsolve(y(n) + a * (y(n + 1) + y(n - 1)) / 2, y(n)) -
            (C0 * ((sqrt(-a**2 + 1) - 1) / a)**n + C1 *
             ((-sqrt(-a**2 + 1) - 1) / a)**n)).simplify() == 0

    assert rsolve((k + 1) * y(k), y(k)) is None
    assert (rsolve((k + 1) * y(k) + (k + 3) * y(k + 1) +
                   (k + 5) * y(k + 2), y(k)) is None)
Esempio n. 32
0
def convert_binom(binom):
    expr_n = convert_expr(binom.n)
    expr_k = convert_expr(binom.k)
    return sympy.binomial(expr_n, expr_k, evaluate=False)
Esempio n. 33
0
def test_hypergeometric_sums():
    assert summation(binomial(2 * k, k) / 4**k,
                     (k, 0, n)) == (1 + 2 * n) * binomial(2 * n, n) / 4**n
Esempio n. 34
0
def test_euler_failing():
    # depends on dummy variables being implemented https://github.com/sympy/sympy/issues/5665
    assert euler(2 * n).rewrite(Sum) == I * Sum(
        Sum((-1)**_j * 2**(-_k) * I**(-_k) *
            (-2 * _j + _k)**(2 * n + 1) * binomial(_k, _j) / _k, (_j, 0, _k)),
        (_k, 1, 2 * n + 1))
Esempio n. 35
0
 def pmf(self, k):
     n, a, b = self.n, self.alpha, self.beta
     return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b)
Esempio n. 36
0
 def dict(self):
     n, p, succ, fail = self.n, self.p, self.succ, self.fail
     n = as_int(n)
     return dict((k * succ + (n - k) * fail,
                  binomial(n, k) * p**k * (1 - p)**(n - k))
                 for k in range(0, n + 1))
Esempio n. 37
0
def count_cnr_bigger(n, min_n):
    bin_gen = (binomial(i, j) for i in range(1, n + 1)
               for j in range(1, i + 1))
    return sum(1 for x in bin_gen if x > min_n)
Esempio n. 38
0
def test_issue_10801():
    # make sure limits work with binomial
    assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi
Esempio n. 39
0
def med_hamm1(n, k):
    res = 0
    for i in range(1, k + 1):
        res += 2*i*binomial(k, i)*binomial(n-k,i)
    return (res / binomial(n, k))
Esempio n. 40
0
def test_binomial_Mod_slow():
    p, q = 10**5 + 3, 10**9 + 33 # prime modulo
    r, s = 10**7 + 5, 33333333 # composite modulo

    n, k, m = symbols('n k m')
    assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
    assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
    assert (binomial(9, k) % 7).subs(k, 2) == 1

    # Lucas Theorem
    assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
    assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
    assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)

    # factorial Mod
    assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
    assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
    assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)

    # binomial factorize
    assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
    assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
    assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
    assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
    assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
Esempio n. 41
0
def wigner_d_small(J, beta):
    """Return the small Wigner d matrix for angular momentum J.

    Explanation
    ===========

    J : An integer, half-integer, or sympy symbol for the total angular
        momentum of the angular momentum space being rotated.
    beta : A real number representing the Euler angle of rotation about
        the so-called line of nodes. See [Edmonds74]_.

    Returns
    =======

    A matrix representing the corresponding Euler angle rotation( in the basis
    of eigenvectors of `J_z`).

    .. math ::
        \\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)

    The components are calculated using the general form [Edmonds74]_,
    equation 4.1.15.

    Examples
    ========

    >>> from sympy import Integer, symbols, pi, pprint
    >>> from sympy.physics.wigner import wigner_d_small
    >>> half = 1/Integer(2)
    >>> beta = symbols("beta", real=True)
    >>> pprint(wigner_d_small(half, beta), use_unicode=True)
    ⎡   ⎛β⎞      ⎛β⎞⎤
    ⎢cos⎜─⎟   sin⎜─⎟⎥
    ⎢   ⎝2⎠      ⎝2⎠⎥
    ⎢               ⎥
    ⎢    ⎛β⎞     ⎛β⎞⎥
    ⎢-sin⎜─⎟  cos⎜─⎟⎥
    ⎣    ⎝2⎠     ⎝2⎠⎦

    >>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
    ⎡        2⎛β⎞              ⎛β⎞    ⎛β⎞           2⎛β⎞     ⎤
    ⎢     cos ⎜─⎟        √2⋅sin⎜─⎟⋅cos⎜─⎟        sin ⎜─⎟     ⎥
    ⎢         ⎝2⎠              ⎝2⎠    ⎝2⎠            ⎝2⎠     ⎥
    ⎢                                                        ⎥
    ⎢       ⎛β⎞    ⎛β⎞       2⎛β⎞      2⎛β⎞        ⎛β⎞    ⎛β⎞⎥
    ⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟  - sin ⎜─⎟ + cos ⎜─⎟  √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
    ⎢       ⎝2⎠    ⎝2⎠        ⎝2⎠       ⎝2⎠        ⎝2⎠    ⎝2⎠⎥
    ⎢                                                        ⎥
    ⎢        2⎛β⎞               ⎛β⎞    ⎛β⎞          2⎛β⎞     ⎥
    ⎢     sin ⎜─⎟        -√2⋅sin⎜─⎟⋅cos⎜─⎟       cos ⎜─⎟     ⎥
    ⎣         ⎝2⎠               ⎝2⎠    ⎝2⎠           ⎝2⎠     ⎦

    From table 4 in [Edmonds74]_

    >>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True)
    ⎡ √2   √2⎤
    ⎢ ──   ──⎥
    ⎢ 2    2 ⎥
    ⎢        ⎥
    ⎢-√2   √2⎥
    ⎢────  ──⎥
    ⎣ 2    2 ⎦

    >>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}),
    ... use_unicode=True)
    ⎡       √2      ⎤
    ⎢1/2    ──   1/2⎥
    ⎢       2       ⎥
    ⎢               ⎥
    ⎢-√2         √2 ⎥
    ⎢────   0    ── ⎥
    ⎢ 2          2  ⎥
    ⎢               ⎥
    ⎢      -√2      ⎥
    ⎢1/2   ────  1/2⎥
    ⎣       2       ⎦

    >>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}),
    ... use_unicode=True)
    ⎡ √2    √6    √6   √2⎤
    ⎢ ──    ──    ──   ──⎥
    ⎢ 4     4     4    4 ⎥
    ⎢                    ⎥
    ⎢-√6   -√2    √2   √6⎥
    ⎢────  ────   ──   ──⎥
    ⎢ 4     4     4    4 ⎥
    ⎢                    ⎥
    ⎢ √6   -√2   -√2   √6⎥
    ⎢ ──   ────  ────  ──⎥
    ⎢ 4     4     4    4 ⎥
    ⎢                    ⎥
    ⎢-√2    √6   -√6   √2⎥
    ⎢────   ──   ────  ──⎥
    ⎣ 4     4     4    4 ⎦

    >>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}),
    ... use_unicode=True)
    ⎡             √6            ⎤
    ⎢1/4   1/2    ──   1/2   1/4⎥
    ⎢             4             ⎥
    ⎢                           ⎥
    ⎢-1/2  -1/2   0    1/2   1/2⎥
    ⎢                           ⎥
    ⎢ √6                     √6 ⎥
    ⎢ ──    0    -1/2   0    ── ⎥
    ⎢ 4                      4  ⎥
    ⎢                           ⎥
    ⎢-1/2  1/2    0    -1/2  1/2⎥
    ⎢                           ⎥
    ⎢             √6            ⎥
    ⎢1/4   -1/2   ──   -1/2  1/4⎥
    ⎣             4             ⎦

    """
    M = [J-i for i in range(2*J+1)]
    d = zeros(2*J+1)
    for i, Mi in enumerate(M):
        for j, Mj in enumerate(M):

            # We get the maximum and minimum value of sigma.
            sigmamax = max([-Mi-Mj, J-Mj])
            sigmamin = min([0, J-Mi])

            dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
                       factorial(J+Mj)/factorial(J-Mj))
            terms = [(-1)**(J-Mi-s) *
                     binomial(J+Mj, J-Mi-s) *
                     binomial(J-Mj, s) *
                     cos(beta/2)**(2*s+Mi+Mj) *
                     sin(beta/2)**(2*J-2*s-Mj-Mi)
                     for s in range(sigmamin, sigmamax+1)]

            d[i, j] = dij*Add(*terms)

    return ImmutableMatrix(d)
Esempio n. 42
0
def _binomial(n, k):
    return binomial(n, k, evaluate=False)
Esempio n. 43
0
def test_binomial():
    n = Symbol('n', integer=True)
    k = Symbol('k', integer=True)
    u = Symbol('v', negative=True)
    v = Symbol('m', positive=True)

    assert binomial(0, 0) == 1
    assert binomial(1, 1) == 1
    assert binomial(10, 10) == 1
    assert binomial(1, 2) == 0
    assert binomial(1, -1) == 0
    assert binomial(-1, 1) == -1
    assert binomial(-10, 1) == -10
    assert binomial(-10, 7) == -11440
    assert binomial(n, -1) == 0
    assert binomial(n, 0) == 1
    assert expand_func(binomial(n, 1)) == n
    assert expand_func(binomial(n, 2)) == n * (n - 1) / 2
    assert expand_func(binomial(n, n - 2)) == n * (n - 1) / 2
    assert expand_func(binomial(n, n - 1)) == n
    assert binomial(n, 3).func == binomial
    assert binomial(n, 3).expand(func=True) == n**3 / 6 - n**2 / 2 + n / 3
    assert expand_func(binomial(n, 3)) == n * (n - 2) * (n - 1) / 6
    assert binomial(n, n) == 1
    assert binomial(n, n + 1) == 0
    assert binomial(n, u) == 0
    assert binomial(n, v).func == binomial
    assert binomial(n, k).func == binomial
    assert binomial(n, n + v) == 0

    assert expand_func(binomial(n, n - 3)) == n * (n - 2) * (n - 1) / 6

    assert binomial(n, k).is_integer
Esempio n. 44
0
def test_issue_14528():
    p = symbols("p", integer=True, positive=True)
    assert combsimp(binomial(1, p)) == 1 / (factorial(p) * factorial(1 - p))
    assert combsimp(factorial(2 - p)) == factorial(2 - p)
Esempio n. 45
0
def test_ff_eval_apply():
    x, y = symbols('x,y')
    n, k = symbols('n k', integer=True)
    m = Symbol('m', integer=True, nonnegative=True)

    assert ff(nan, y) == nan
    assert ff(x, nan) == nan

    assert ff(x, y) == ff(x, y)

    assert ff(oo, 0) == 1
    assert ff(-oo, 0) == 1

    assert ff(oo, 6) == oo
    assert ff(-oo, 7) == -oo
    assert ff(-oo, 6) == oo

    assert ff(oo, -6) == oo
    assert ff(-oo, -7) == oo

    assert ff(x, 0) == 1
    assert ff(x, 1) == x
    assert ff(x, 2) == x*(x - 1)
    assert ff(x, 3) == x*(x - 1)*(x - 2)
    assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)

    assert ff(x, -1) == 1/(x + 1)
    assert ff(x, -2) == 1/((x + 1)*(x + 2))
    assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))

    assert ff(100, 100) == factorial(100)

    assert ff(2*x**2 - 5*x, 2) == (2*x**2  - 5*x)*(2*x**2 - 5*x - 1)
    assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
    assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))

    assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
    assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
    raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
    assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
    raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))


    assert ff(x, m).is_integer is None
    assert ff(n, k).is_integer is None
    assert ff(n, m).is_integer is True
    assert ff(n, k + pi).is_integer is False
    assert ff(n, m + pi).is_integer is False
    assert ff(pi, m).is_integer is False

    assert isinstance(ff(x, x), ff)
    assert ff(n, n) == factorial(n)

    assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
    assert ff(x, k).rewrite(gamma) == (-1)**k*gamma(k - x) / gamma(-x)
    assert ff(n, k).rewrite(factorial) == factorial(n) / factorial(n - k)
    assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
    assert ff(x, y).rewrite(factorial) == ff(x, y)
    assert ff(x, y).rewrite(binomial) == ff(x, y)

    import random
    from mpmath import ff as mpmath_ff
    for i in range(100):
        x = -500 + 500 * random.random()
        k = -500 + 500 * random.random()
        assert (abs(mpmath_ff(x, k) - ff(x, k)) < 10**(-15))
Esempio n. 46
0
def lattice_path(n):
    return binomial(2 * n, n)
Esempio n. 47
0
 def pmf(self, k):
     N, m, n = self.N, self.m, self.n
     return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n)
def test_gammasimp():
    R = Rational

    # was part of test_combsimp_gamma() in test_combsimp.py
    assert gammasimp(gamma(x)) == gamma(x)
    assert gammasimp(gamma(x + 1) / x) == gamma(x)
    assert gammasimp(gamma(x) / (x - 1)) == gamma(x - 1)
    assert gammasimp(x * gamma(x)) == gamma(x + 1)
    assert gammasimp((x + 1) * gamma(x + 1)) == gamma(x + 2)
    assert gammasimp(gamma(x + y) * (x + y)) == gamma(x + y + 1)
    assert gammasimp(x / gamma(x + 1)) == 1 / gamma(x)
    assert gammasimp((x + 1)**2 / gamma(x + 2)) == (x + 1) / gamma(x + 1)
    assert gammasimp(x*gamma(x) + gamma(x + 3)/(x + 2)) == \
        (x + 2)*gamma(x + 1)

    assert gammasimp(gamma(2 * x) * x) == gamma(2 * x + 1) / 2
    assert gammasimp(gamma(2 * x) / (x - S(1) / 2)) == 2 * gamma(2 * x - 1)

    assert gammasimp(gamma(x) * gamma(1 - x)) == pi / sin(pi * x)
    assert gammasimp(gamma(x) * gamma(-x)) == -pi / (x * sin(pi * x))
    assert gammasimp(1/gamma(x + 3)/gamma(1 - x)) == \
        sin(pi*x)/(pi*x*(x + 1)*(x + 2))

    assert gammasimp(factorial(n + 2)) == gamma(n + 3)
    assert gammasimp(binomial(n, k)) == \
        gamma(n + 1)/(gamma(k + 1)*gamma(-k + n + 1))

    assert powsimp(gammasimp(
        gamma(x)*gamma(x + S(1)/2)*gamma(y)/gamma(x + y))) == \
        2**(-2*x + 1)*sqrt(pi)*gamma(2*x)*gamma(y)/gamma(x + y)
    assert gammasimp(1/gamma(x)/gamma(x - S(1)/3)/gamma(x + S(1)/3)) == \
        3**(3*x - S(3)/2)/(2*pi*gamma(3*x - 1))
    assert simplify(
        gamma(S(1) / 2 + x / 2) * gamma(1 + x / 2) / gamma(1 + x) / sqrt(pi) *
        2**x) == 1
    assert gammasimp(gamma(S(-1) / 4) *
                     gamma(S(-3) / 4)) == 16 * sqrt(2) * pi / 3

    assert powsimp(gammasimp(gamma(2*x)/gamma(x))) == \
        2**(2*x - 1)*gamma(x + S(1)/2)/sqrt(pi)

    # issue 6792
    e = (-gamma(k) * gamma(k + 2) + gamma(k + 1)**2) / gamma(k)**2
    assert gammasimp(e) == -k
    assert gammasimp(1 / e) == -1 / k
    e = (gamma(x) + gamma(x + 1)) / gamma(x)
    assert gammasimp(e) == x + 1
    assert gammasimp(1 / e) == 1 / (x + 1)
    e = (gamma(x) + gamma(x + 2)) * (gamma(x - 1) + gamma(x)) / gamma(x)
    assert gammasimp(e) == (x**2 + x + 1) * gamma(x + 1) / (x - 1)
    e = (-gamma(k) * gamma(k + 2) + gamma(k + 1)**2) / gamma(k)**2
    assert gammasimp(e**2) == k**2
    assert gammasimp(e**2 / gamma(k + 1)) == k / gamma(k)
    a = R(1, 2) + R(1, 3)
    b = a + R(1, 3)
    assert gammasimp(gamma(2 * k) / gamma(k) * gamma(k + a) * gamma(k + b))
    3 * 2**(2 * k + 1) * 3**(-3 * k - 2) * sqrt(pi) * gamma(3 * k +
                                                            R(3, 2)) / 2

    # issue 9699
    assert gammasimp(
        (x + 1) * factorial(x) / gamma(y)) == gamma(x + 2) / gamma(y)
    assert gammasimp(rf(x + n, k) *
                     binomial(n, k)) == gamma(n + 1) * gamma(k + n + x) / (
                         gamma(k + 1) * gamma(n + x) * gamma(-k + n + 1))

    A, B = symbols('A B', commutative=False)
    assert gammasimp(e * B * A) == gammasimp(e) * B * A

    # check iteration
    assert gammasimp(gamma(2 * k) / gamma(k) *
                     gamma(-k - R(1, 2))) == (-2**(2 * k + 1) * sqrt(pi) /
                                              (2 *
                                               ((2 * k + 1) * cos(pi * k))))
    assert gammasimp(
        gamma(k) * gamma(k + R(1, 3)) * gamma(k + R(2, 3)) /
        gamma(3 * k / 2)) == (3 * 2**(3 * k + 1) * 3**(-3 * k - S.Half) *
                              sqrt(pi) * gamma(3 * k / 2 + S.Half) / 2)

    # issue 6153
    assert gammasimp(gamma(S(1) / 4) / gamma(S(5) / 4)) == 4

    # was part of test_combsimp() in test_combsimp.py
    assert gammasimp(binomial(n + 2, k + S(1)/2)) == gamma(n + 3)/ \
        (gamma(k + 3/2)*gamma(-k + n + 5/2))
    assert gammasimp(binomial(n + 2, k + 2.0)) == \
        gamma(n + 3)/(gamma(k + 3.0)*gamma(-k + n + 1))

    # issue 11548
    assert gammasimp(binomial(0, x)) == sin(pi * x) / (pi * x)

    e = gamma(n + S(1) / 3) * gamma(n + S(2) / 3)
    assert gammasimp(e) == e
    assert gammasimp(gamma(4*n + S(1)/2)/gamma(2*n - S(3)/4)) == \
        2**(4*n - S(5)/2)*(8*n - 3)*gamma(2*n + S(3)/4)/sqrt(pi)

    i, m = symbols('i m', integer=True)
    e = gamma(exp(i))
    assert gammasimp(e) == e
    e = gamma(m + 3)
    assert gammasimp(e) == e
    e = gamma(m + 1) / (gamma(i + 1) * gamma(-i + m + 1))
    assert gammasimp(e) == e
Esempio n. 49
0
def test_F2():
    assert expand_func(binomial(n, 3)) == n * (n - 1) * (n - 2) / 6
Esempio n. 50
0
def test_issue_15943():
    s = Sum(binomial(n, k) * factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
    assert s == -E * (n + 1) * gamma(n + 1) * lowergamma(
        n + 1, 1) / gamma(n + 2) + E * gamma(n + 1)
    assert s.simplify() == E * (factorial(n) - lowergamma(n + 1, 1))
Esempio n. 51
0
def test_binomial():
    n = Symbol('n', integer=True)
    nz = Symbol('nz', integer=True, nonzero=True)
    k = Symbol('k', integer=True)
    kp = Symbol('kp', integer=True, positive=True)
    u = Symbol('v', negative=True)
    p = Symbol('p', positive=True)

    assert binomial(0, 0) == 1
    assert binomial(1, 1) == 1
    assert binomial(10, 10) == 1
    assert binomial(1, 2) == 0
    assert binomial(1, -1) == 0
    assert binomial(-1, 1) == -1
    assert binomial(-1, -1) == 1
    assert binomial(S.Half, S.Half) == 1
    assert binomial(-10, 1) == -10
    assert binomial(-10, 7) == -11440
    assert binomial(n, -1).func == binomial
    assert binomial(kp, -1) == 0
    assert binomial(nz, 0) == 1
    assert binomial(n, 0).func == binomial
    assert expand_func(binomial(n, 1)) == n
    assert expand_func(binomial(n, 2)) == n * (n - 1) / 2
    assert expand_func(binomial(n, n - 2)) == n * (n - 1) / 2
    assert expand_func(binomial(n, n - 1)) == n
    assert binomial(n, 3).func == binomial
    assert binomial(n, 3).expand(func=True) == n**3 / 6 - n**2 / 2 + n / 3
    assert expand_func(binomial(n, 3)) == n * (n - 2) * (n - 1) / 6
    assert binomial(n, n) == 1
    assert binomial(n, n + 1).func == binomial  # e.g. (-1, 0) == 1
    assert binomial(kp, kp + 1) == 0
    assert binomial(n, u).func == binomial
    assert binomial(kp, u) == 0
    assert binomial(n, p).func == binomial
    assert binomial(n, k).func == binomial
    assert binomial(n, n + p).func == binomial
    assert binomial(kp, kp + p) == 0

    assert expand_func(binomial(n, n - 3)) == n * (n - 2) * (n - 1) / 6

    assert binomial(n, k).is_integer
Esempio n. 52
0
 def create_mgf_expr(self, coal_rates, migration_rates, initial_config):
     """ Generates the mgf, only should be called by __init__
     Arguments:
     coal_rates      -- a list giving the coalescent rate in each deme
                        ex: [1, 1]
     migration_rates -- a matrix giving the migration rates from each deme to each other deme
                        ex: sympy.Matrix([[0, 1], [1, 0]])
     initial_config  -- a list giving the starting configuration of the lineages
                        ex: [ [[1], [2]], [[3]] ]
     """
     Eqns = []
     num_demes = len(coal_rates)
     # Get all partitions of starting lineages aka all coalescent states
     indv_partitions = list(partition(self.lineages))
     indv_partitions.remove([[
         individual for lineage in self.lineages for individual in lineage
     ]])
     deme_partitions = [
         deme_part for indv_partition in indv_partitions
         for deme_part in deme_partition(indv_partition, num_demes)
     ]
     print("There are " + str(len(deme_partitions)) + " possible states.")
     print("Setting up a system of " + str(len(deme_partitions)) +
           " equations...")
     deme_part_symbols = []
     all_symbols = []
     for deme_part in deme_partitions:
         print("Working with partition: " + str(deme_part))
         deme_part_symbol = deme_part_to_symbol(deme_part)
         deme_part_symbols.append(deme_part_symbol)
         all_symbols.append(deme_part_symbol)
         # Make the factor for this partition
         print("Creating the factor for this partition")
         deme_part_factor = sympy.Integer(0)
         for deme_idx, deme in enumerate(deme_part):
             n_deme_lineages = len(deme)
             deme_part_factor += sympy.binomial(n_deme_lineages,
                                                2) * coal_rates[deme_idx]
             for other_deme_idx in range(num_demes):
                 if deme_idx != other_deme_idx:
                     deme_part_factor += n_deme_lineages * migration_rates[
                         deme_idx, other_deme_idx]
             for lineage in deme:
                 deme_part_factor -= sympy.symbols(
                     's_' + '.'.join([str(tip) for tip in sorted(lineage)]))
         # Add the left side in (sign is negative, see eq 8 Lohse et al.)
         deme_part_eqn = -deme_part_factor * deme_part_symbol
         # sympy.pprint(deme_part_eqn)
         # Add the transfer rates to coalescent states
         print("Adding rates to other coal states")
         for deme_idx, deme in enumerate(deme_part):
             for pair in itertools.combinations(deme, 2):
                 # If only two lineages left, the next coal event reduces us to one
                 if sum([len(deme_lins) for deme_lins in deme_part]) == 2:
                     symbol_after_coal = sympy.Integer(1)
                 else:
                     symbol_after_coal = deme_part_symbol_after_coal(
                         deme_part, pair)
                     all_symbols.append(symbol_after_coal)
                 deme_part_eqn += coal_rates[deme_idx] * symbol_after_coal
         # Add the transfer rates for migration events
         print("Adding rates to other migration states")
         for deme_idx, deme in enumerate(deme_part):
             # For each lineage in the deme add a term for the probability of that lineage
             # immigrating to each other deme
             for lin in deme:
                 for deme_to_idx in range(num_demes):
                     deme_part_eqn += (
                         migration_rates[deme_idx, deme_to_idx] *
                         deme_part_symbol_after_migr(
                             deme_part, lin, deme_idx, deme_to_idx))
                     all_symbols.append(
                         deme_part_symbol_after_migr(
                             deme_part, lin, deme_idx, deme_to_idx))
         print("Done! Adding this to the list of equations")
         Eqns.append(deme_part_eqn)
     print("The terms being solved for are:")
     for deme_part_symbol in deme_part_symbols:
         sympy.pprint(deme_part_symbol)
     all_symbols = set(all_symbols)
     print("There are " + str(len(all_symbols)) +
           " terms in the system of equation")
     for symbol in all_symbols:
         sympy.pprint(symbol)
     starting_part = deme_part_to_symbol(initial_config)
     starting_idx = deme_part_symbols.index(starting_part)
     print('Solving system of equations...')
     mgf_solution = sympy.linsolve(Eqns, *deme_part_symbols)
     return list(mgf_solution)[0][starting_idx]
Esempio n. 53
0
def solve():
    return sum(
        int(binomial(n, r)) > 1_000_000 for n in range(1, LIMIT + 1)
        for r in range(1, n))
Esempio n. 54
0
def test_combsimp():
    k, m, n = symbols('k m n', integer=True)

    assert combsimp(factorial(n)) == factorial(n)
    assert combsimp(binomial(n, k)) == binomial(n, k)

    assert combsimp(factorial(n) / factorial(n - 3)) == n * (-1 + n) * (-2 + n)
    assert combsimp(binomial(n + 1, k + 1) /
                    binomial(n, k)) == (1 + n) / (1 + k)

    assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \
        Rational(3, 2)*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3)))

    assert combsimp(factorial(n)**2/factorial(n - 3)) == \
        factorial(n)*n*(-1 + n)*(-2 + n)
    assert combsimp(factorial(n)*binomial(n + 1, k + 1)/binomial(n, k)) == \
        factorial(n + 1)/(1 + k)

    assert combsimp(gamma(n + 3)) == factorial(n + 2)

    assert combsimp(factorial(x)) == gamma(x + 1)

    # issue 9699
    assert combsimp((n + 1) * factorial(n)) == factorial(n + 1)
    assert combsimp(factorial(n) / n) == factorial(n - 1)

    # issue 6658
    assert combsimp(binomial(n, n - k)) == binomial(n, k)

    # issue 6341, 7135
    assert combsimp(factorial(n)/(factorial(k)*factorial(n - k))) == \
        binomial(n, k)
    assert combsimp(factorial(k)*factorial(n - k)/factorial(n)) == \
        1/binomial(n, k)
    assert combsimp(factorial(2 * n) / factorial(n)**2) == binomial(2 * n, n)
    assert combsimp(
        factorial(2 * n) * factorial(k) * factorial(n - k) /
        factorial(n)**3) == binomial(2 * n, n) / binomial(n, k)

    assert combsimp(factorial(n * (1 + n) - n**2 - n)) == 1

    assert combsimp(6*FallingFactorial(-4, n)/factorial(n)) == \
        (-1)**n*(n + 1)*(n + 2)*(n + 3)
    assert combsimp(6*FallingFactorial(-4, n - 1)/factorial(n - 1)) == \
        (-1)**(n - 1)*n*(n + 1)*(n + 2)
    assert combsimp(6*FallingFactorial(-4, n - 3)/factorial(n - 3)) == \
        (-1)**(n - 3)*n*(n - 1)*(n - 2)
    assert combsimp(6*FallingFactorial(-4, -n - 1)/factorial(-n - 1)) == \
        -(-1)**(-n - 1)*n*(n - 1)*(n - 2)

    assert combsimp(6*RisingFactorial(4, n)/factorial(n)) == \
        (n + 1)*(n + 2)*(n + 3)
    assert combsimp(6*RisingFactorial(4, n - 1)/factorial(n - 1)) == \
        n*(n + 1)*(n + 2)
    assert combsimp(6*RisingFactorial(4, n - 3)/factorial(n - 3)) == \
        n*(n - 1)*(n - 2)
    assert combsimp(6*RisingFactorial(4, -n - 1)/factorial(-n - 1)) == \
        -n*(n - 1)*(n - 2)
Esempio n. 55
0
def convert_binom(binom):
    expr_top = convert_expr(binom.upper)
    expr_bot = convert_expr(binom.lower)
    return sympy.binomial(expr_top, expr_bot)
Esempio n. 56
0
def test_issue_16722():
    z = symbols('z', positive=True)
    assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
    z = symbols('z', positive=True, integer=True)
    assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
Esempio n. 57
0
def main():

    tokens = [
        Expression(1),
        Expression(2),
        Expression(3),
        Expression(5),
        Expression(-1),
        Expression(I),
        Expression(E),
        Expression(PI),
        Operation('Add', lambda x, y: sympy.Add(x, y)),
        Operation('Sub',
                  lambda x, y: sympy.Add(x, sympy.Mul(sympy.Integer(-1), y))),
        Operation('Mul', lambda x, y: sympy.Mul(x, y)),
        Operation('Div',
                  lambda x, y: sympy.Mul(x, sympy.Pow(y, sympy.Integer(-1)))),
        Operation('Pow', lambda x, y: sympy.Pow(x, y)),
    ]

    # increment this to expand the search...
    # small increases in this explode the search space
    stack_size = 3

    # the number we're looking for
    target = 14.134725141734693790457251983562470270784257115699243175685567460149963429809256764949010393171561012779202971548797436766142691469882254582505363239447137780413381237205970549621955865860200555566725836010773700205410982661507542780517442591306254481978651072304938725629738321577420395215725674809332140034990468034346267314420920377385487141378317356396995365428113079680531491688529067820822980492643386667346233200787587617920056048680543568014444246510655975686659032286865105448594443206240727270320942745222130487487209241238514183514605427901524478338354254533440044879368067616973008190007313938549837362150130451672696838920039176285123212854220523969133425832275335164060169763527563758969537674920336127209259991730427075683087951184453489180086300826483125169112710682910523759617977431815170713545316775495153828937849036474709727019948485532209253574357909226125247736595518016975233461213977316005354125926747455725877801472609830808978600712532087509395997966660675378381214891908864977277554420656532052405

    # cant forget to optimize -- keep a hash table of already-computed answers
    memoize_dict = {}

    # keep a list of the best guesses
    best_guesses = []
    max_best_guesses = 10

    # test to make sure phi works
    phi = 1.6180339887498948482
    test_args = [
        Expression(2),
        Expression(1),
        Expression(2),
        Expression(1),
        Operation('Div',
                  lambda x, y: sympy.Mul(x, sympy.Pow(y, sympy.Integer(-1)))),
        Expression(5),
        Operation('Pow', lambda x, y: sympy.Pow(x, y)),
        Operation('Add', lambda x, y: sympy.Add(x, y)),
        Operation('Div',
                  lambda x, y: sympy.Mul(x, sympy.Pow(y, sympy.Integer(-1)))),
    ]
    test = reduce(test_args[::-1])
    test_tolerance = 0.000000001
    assert (test - phi < test_tolerance)

    # brute force the maths
    # ... forever
    while True:

        # we want updates to know how far along we are
        total_iters = binomial(len(tokens) + stack_size - 1,
                               stack_size) * sympy.factorial(stack_size)
        i = 0
        last_percent = 0.0

        for args in itertools.combinations_with_replacement(
                tokens, stack_size):
            for perms in itertools.permutations(args):

                # update our progress, if we've made enough progress
                percent_done = float(i) / float(total_iters)
                if (percent_done) - last_percent > 0.01:
                    print('[{} / %{:02}] {}'.format(
                        stack_size, int(percent_done * 100),
                        best_guesses[0] if best_guesses else 'No Guesses'))
                    last_percent = percent_done

                i += 1

                if str(perms) in memoize_dict:
                    continue

                if not is_valid_rpn(perms):
                    memoize_dict[str(perms)] = 'INVALID'
                    continue

                try:
                    expression = reduce(list(perms))
                except:
                    continue

                if str(expression) in memoize_dict:
                    # check to see if we've already done the work
                    guess = memoize_dict[str(perms)]
                else:
                    # otherwise, calculate the result and record the answer
                    guess = expression.evalf()
                    memoize_dict[str(perms)] = guess

                # how good of a guess was this?
                delta = sympy.Abs(guess - target)

                try:
                    best_guesses = sorted(
                        best_guesses + [(delta, guess, perms)],
                        key=lambda x: x[0])[:max_best_guesses]
                except:
                    continue

        print('done after: {}'.format(i))
        print('stack size: {}'.format(stack_size))
        pprint.pprint(best_guesses)
        stack_size += 1

    return
Esempio n. 58
0
    def pdf(self, k):
        r = self.r
        p = self.p

        return binomial(k + r - 1, k) * (1 - p)**r * p**k
Esempio n. 59
0
def test_combsimp():
    from sympy.abc import n, k

    assert combsimp(factorial(n)) == factorial(n)
    assert combsimp(binomial(n, k)) == binomial(n, k)

    assert combsimp(factorial(n) / factorial(n - 3)) == n * (-1 + n) * (-2 + n)
    assert combsimp(binomial(n + 1, k + 1) /
                    binomial(n, k)) == (1 + n) / (1 + k)

    assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \
        S(3)/2*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3)))

    assert combsimp(factorial(n)**2 /
                    factorial(n - 3)) == factorial(n) * n * (-1 + n) * (-2 + n)
    assert combsimp(factorial(n) * binomial(n + 1, k + 1) /
                    binomial(n, k)) == factorial(n) * (1 + n) / (1 + k)

    assert combsimp(binomial(n - 1, k)) == -((-n + k) * binomial(n, k)) / n

    assert combsimp(binomial(n + 2, k + S(1)/2)) == \
        4*((n + 1)*(n + 2)*binomial(n, k + S(1)/2))/((2*k - 2*n - 1)*(2*k - 2*n - 3))
    assert combsimp(binomial(n + 2, k + 2.0)) == \
        -((1.0*n + 2.0)*binomial(n + 1.0, k + 2.0))/(k - n)
Esempio n. 60
0
#!/usr/bin/env python3.6
"""
PROBLEM: 015
AUTHOR:  Dirk Meijer
STATUS:  done
EXPLANATION:
    library solution
"""

from Euler.tictoc import *
from sympy import binomial

if __name__ == "__main__":
    tic()
    print(binomial(40, 20))
    toc()
    exit()