Exemple #1
0
    def _entry(self, i, j, expand=True):
        coeff, matrices = self.as_coeff_matrices()

        if len(matrices) == 1:  # situation like 2*X, matmul is just X
            return coeff * matrices[0][i, j]

        head, tail = matrices[0], matrices[1:]
        if len(tail) == 0:
            raise ValueError("lenth of tail cannot be 0")
        X = head
        Y = MatMul(*tail)

        from sympy.core.symbol import Dummy
        from sympy.concrete.summations import Sum
        from sympy.matrices import ImmutableMatrix
        k = Dummy('k', integer=True)
        if X.has(ImmutableMatrix) or Y.has(ImmutableMatrix):
            return coeff*Add(*[X[i, k]*Y[k, j] for k in range(X.cols)])
        result = Sum(coeff*X[i, k]*Y[k, j], (k, 0, X.cols - 1))
        try:
            if not X.cols.is_number:
                # Don't waste time in result.doit() if the sum bounds are symbolic
                expand = False
        except AttributeError:
            pass
        return result.doit() if expand else result
Exemple #2
0
def test_evalf_sum():
    assert Sum(n, (n, 1, 2)).evalf() == 3.
    assert Sum(n, (n, 1, 2)).doit().evalf() == 3.
    # the next test should return instantly
    assert Sum(1 / n, (n, 1, 2)).evalf() == 1.5

    # issue 8219
    assert Sum(E / factorial(n), (n, 0, oo)).evalf() == (E * E).evalf()
    # issue 8254
    assert Sum(2**n * n / factorial(n),
               (n, 0, oo)).evalf() == (2 * E * E).evalf()
    # issue 8411
    s = Sum(1 / x**2, (x, 100, oo))
    assert s.n() == s.doit().n()
Exemple #3
0
 def fdiff(self, argindex=2):
     from sympy.concrete.summations import Sum
     if argindex == 2:
         x, p = self.args
         k = Dummy("k")
         return self.func(x, p) * Sum(polygamma(0, x + (1 - k) / 2),
                                      (k, 1, p))
     else:
         raise ArgumentIndexError(self, argindex)
Exemple #4
0
 def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs):
     from sympy.concrete.summations import Sum
     # Make sure n \in N_0
     if n.is_negative or n.is_integer is False:
         raise ValueError("Error: n should be a non-negative integer.")
     k = Dummy("k")
     kern = RisingFactorial(
         -n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k
     return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n))
Exemple #5
0
def _check_varsh_sum_871_2(e):
    a = Wild('a')
    alpha = symbols('alpha')
    c = Wild('c')
    match = e.match(
        Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
    if match is not None and len(match) == 2:
        return (sqrt(2 * a + 1) * KroneckerDelta(c, 0)).subs(match)
    return e
Exemple #6
0
 def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs):
     from sympy.concrete.summations import Sum
     # Make sure n \in N
     if n.is_negative or n.is_integer is False:
         raise ValueError("Error: n should be a non-negative integer.")
     k = Dummy("k")
     kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) /
             factorial(k) * ((1 - x)/2)**k)
     return 1 / factorial(n) * Sum(kern, (k, 0, n))
Exemple #7
0
def test_Indexed():
    # Issue #10934
    if not numpy:
        skip("numpy not installed")

    a = IndexedBase('a')
    i, j = symbols('i j')
    b = numpy.array([[1, 2], [3, 4]])
    assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
Exemple #8
0
 def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs):
     from sympy.concrete.summations import Sum
     n = Dummy("n", integer=True)
     rfap = Tuple(*[RisingFactorial(a, n) for a in ap])
     rfbq = Tuple(*[RisingFactorial(b, n) for b in bq])
     coeff = Mul(*rfap) / Mul(*rfbq)
     return Piecewise((Sum(coeff * z**n / factorial(n),
                           (n, 0, oo)), self.convergence_statement),
                      (self, True))
Exemple #9
0
def test_matrix_expression_to_indices():
    i, j = symbols("i, j")
    i1, i2, i3 = symbols("i_1:4")

    def replace_dummies(expr):
        repl = {i: Symbol(i.name) for i in expr.atoms(Dummy)}
        return expr.xreplace(repl)

    expr = W*X*Z
    assert replace_dummies(expr._entry(i, j)) == \
        Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
    assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr

    expr = Z.T*X.T*W.T
    assert replace_dummies(expr._entry(i, j)) == \
        Sum(W[j, i2]*X[i2, i1]*Z[i1, i], (i1, 0, m-1), (i2, 0, l-1))
    assert MatrixExpr.from_index_summation(expr._entry(i, j), i) == expr

    expr = W*X*Z + W*Y*Z
    assert replace_dummies(expr._entry(i, j)) == \
        Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
        Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
    assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr

    expr = 2*W*X*Z + 3*W*Y*Z
    assert replace_dummies(expr._entry(i, j)) == \
        2*Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
        3*Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
    assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr

    expr = W*(X + Y)*Z
    assert replace_dummies(expr._entry(i, j)) == \
            Sum(W[i, i1]*(X[i1, i2] + Y[i1, i2])*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
    assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr

    expr = A*B**2*A
    #assert replace_dummies(expr._entry(i, j)) == \
    #        Sum(A[i, i1]*B[i1, i2]*B[i2, i3]*A[i3, j], (i1, 0, 1), (i2, 0, 1), (i3, 0, 1))

    # Check that different dummies are used in sub-multiplications:
    expr = (X1*X2 + X2*X1)*X3
    assert replace_dummies(expr._entry(i, j)) == \
           Sum((Sum(X1[i, i2] * X2[i2, i1], (i2, 0, m - 1)) + Sum(X1[i3, i1] * X2[i, i3], (i3, 0, m - 1))) * X3[
               i1, j], (i1, 0, m - 1))
Exemple #10
0
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)
    p = Symbol("p", positive=True)
    assert assoc_laguerre(p, alpha, oo) == (-1)**p * oo
    assert assoc_laguerre(p, alpha, -oo) is oo

    assert diff(assoc_laguerre(n, alpha, x), x) == \
        -assoc_laguerre(n - 1, alpha + 1, x)
    _k = Dummy('k')
    assert diff(assoc_laguerre(n, alpha, x), alpha).dummy_eq(
        Sum(assoc_laguerre(_k, alpha, x) / (-alpha + n), (_k, 0, n - 1)))

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

    assert assoc_laguerre(n, alpha, x).rewrite('polynomial').dummy_eq(
        gamma(alpha + n + 1) * Sum(
            x**_k * RisingFactorial(-n, _k) /
            (factorial(_k) * gamma(_k + alpha + 1)),
            (_k, 0, n)) / factorial(n))
    raises(ValueError, lambda: assoc_laguerre(-2.1, alpha, x))
    raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(1))
    raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(4))
Exemple #11
0
    def _eval_expand_log(self, deep=True, **hints):
        from sympy.concrete import Sum, Product
        force = hints.get('force', False)
        factor = hints.get('factor', False)
        if (len(self.args) == 2):
            return expand_log(self.func(*self.args), deep=deep, force=force)
        arg = self.args[0]
        if arg.is_Integer:
            # remove perfect powers
            p = perfect_power(arg)
            logarg = None
            coeff = 1
            if p is not False:
                arg, coeff = p
                logarg = self.func(arg)
            # expand as product of its prime factors if factor=True
            if factor:
                p = factorint(arg)
                if arg not in p.keys():
                    logarg = sum(n*log(val) for val, n in p.items())
            if logarg is not None:
                return coeff*logarg
        elif arg.is_Rational:
            return log(arg.p) - log(arg.q)
        elif arg.is_Mul:
            expr = []
            nonpos = []
            for x in arg.args:
                if force or x.is_positive or x.is_polar:
                    a = self.func(x)
                    if isinstance(a, log):
                        expr.append(self.func(x)._eval_expand_log(**hints))
                    else:
                        expr.append(a)
                elif x.is_negative:
                    a = self.func(-x)
                    expr.append(a)
                    nonpos.append(S.NegativeOne)
                else:
                    nonpos.append(x)
            return Add(*expr) + log(Mul(*nonpos))
        elif arg.is_Pow or isinstance(arg, exp):
            if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
                .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
                b = arg.base
                e = arg.exp
                a = self.func(b)
                if isinstance(a, log):
                    return unpolarify(e) * a._eval_expand_log(**hints)
                else:
                    return unpolarify(e) * a
        elif isinstance(arg, Product):
            if force or arg.function.is_positive:
                return Sum(log(arg.function), *arg.limits)

        return self.func(arg)
Exemple #12
0
def test_as_dummy():
    u, v, x, y, z, _0, _1 = symbols('u v x y z _0 _1')
    assert Lambda(x, x + 1).as_dummy() == Lambda(_0, _0 + 1)
    assert Lambda(x, x + _0).as_dummy() == Lambda(_1, _0 + _1)
    eq = (1 + Sum(x, (x, 1, x)))
    ans = 1 + Sum(_0, (_0, 1, x))
    once = eq.as_dummy()
    assert once == ans
    twice = once.as_dummy()
    assert twice == ans
    assert Integral(x + _0, (x, x + 1),
                    (_0, 1, 2)).as_dummy() == Integral(_0 + _1, (_0, x + 1),
                                                       (_1, 1, 2))
    for T in (Symbol, Dummy):
        d = T('x', real=True)
        D = d.as_dummy()
        assert D != d and D.func == Dummy and D.is_real is None
    assert Dummy().as_dummy().is_commutative
    assert Dummy(commutative=False).as_dummy().is_commutative is False
Exemple #13
0
 def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
     from sympy.concrete.summations import Sum
     # Make sure n \in N_0
     if n.is_negative:
         return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs)
     if n.is_integer is False:
         raise ValueError("Error: n should be an integer.")
     k = Dummy("k")
     kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k
     return Sum(kern, (k, 0, n))
Exemple #14
0
def test_mix_expression():
    Y, E = Poisson('Y', 1), Exponential('E', 1)
    k = Dummy('k')
    expr1 = Integral(
        Sum(
            exp(-1) * Integral(exp(-k) * DiracDelta(k - 2),
                               (k, 0, oo)) / factorial(k), (k, 0, oo)),
        (k, -oo, 0))
    expr2 = Integral(
        Sum(
            exp(-1) * Integral(exp(-k) * DiracDelta(k - 2),
                               (k, 0, oo)) / factorial(k), (k, 0, oo)),
        (k, 0, oo))
    assert P(Eq(Y + E, 1)) == 0
    assert P(Ne(Y + E, 2)) == 1
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert P(E + Y < 2, evaluate=False).rewrite(Integral).dummy_eq(expr1)
        assert P(E + Y > 2, evaluate=False).rewrite(Integral).dummy_eq(expr2)
Exemple #15
0
def test_exp_rewrite():
    from sympy.concrete.summations import Sum
    assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
    assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
    assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
    assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
    assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
    assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
    assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
    assert exp(pi*I/3).rewrite(sqrt) == S(1)/2 + sqrt(3)*I/2
    assert exp(x*log(y)).rewrite(Pow) == y**x
    assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
    assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y

    n = Symbol('n', integer=True)

    assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == S(4)/5 + 2*I/5
    assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
    assert Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(S(3)/4 - sqrt(3)*I/4)
Exemple #16
0
def _check_varsh_sum_872_4(e):
    alpha = symbols('alpha')
    beta = symbols('beta')
    a = Wild('a')
    b = Wild('b')
    c = Wild('c')
    cp = Wild('cp')
    gamma = Wild('gamma')
    gammap = Wild('gammap')
    cg1 = CG(a, alpha, b, beta, c, gamma)
    cg2 = CG(a, alpha, b, beta, cp, gammap)
    match1 = e.match(Sum(cg1 * cg2, (alpha, -a, a), (beta, -b, b)))
    if match1 is not None and len(match1) == 6:
        return (KroneckerDelta(c, cp) *
                KroneckerDelta(gamma, gammap)).subs(match1)
    match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
    if match2 is not None and len(match2) == 4:
        return S.One
    return e
Exemple #17
0
def test_mul_index():
    assert (A*y)[0, 0] == A[0, 0]*y[0, 0] + A[0, 1]*y[1, 0]
    assert (A*B).as_mutable() == (A.as_mutable() * B.as_mutable())
    X = MatrixSymbol('X', n, m)
    Y = MatrixSymbol('Y', m, k)

    result = (X*Y)[4,2]
    expected = Sum(X[4, i]*Y[i, 2], (i, 0, m - 1))
    assert result.args[0].dummy_eq(expected.args[0], i)
    assert result.args[1][1:] == expected.args[1][1:]
Exemple #18
0
def test_hyper_rewrite_sum():
    from sympy.concrete.summations import Sum
    from sympy.core.symbol import Dummy
    from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
    _k = Dummy("k")
    assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \
        Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) /
            RisingFactorial(3, _k), (_k, 0, oo))

    assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \
        hyper((1, 2, 3), (-1, 3), z)
Exemple #19
0
def test_legendre():
    assert legendre(0, x) == 1
    assert legendre(1, x) == x
    assert legendre(2, x) == ((3 * x**2 - 1) / 2).expand()
    assert legendre(3, x) == ((5 * x**3 - 3 * x) / 2).expand()
    assert legendre(4, x) == ((35 * x**4 - 30 * x**2 + 3) / 8).expand()
    assert legendre(5, x) == ((63 * x**5 - 70 * x**3 + 15 * x) / 8).expand()
    assert legendre(6, x) == ((231 * x**6 - 315 * x**4 + 105 * x**2 - 5) /
                              16).expand()

    assert legendre(10, -1) == 1
    assert legendre(11, -1) == -1
    assert legendre(10, 1) == 1
    assert legendre(11, 1) == 1
    assert legendre(10, 0) != 0
    assert legendre(11, 0) == 0

    assert legendre(-1, x) == 1
    k = Symbol('k')
    assert legendre(5 - k, x).subs(k, 2) == ((5 * x**3 - 3 * x) / 2).expand()

    assert roots(legendre(4, x), x) == {
        sqrt(Rational(3, 7) - Rational(2, 35) * sqrt(30)): 1,
        -sqrt(Rational(3, 7) - Rational(2, 35) * sqrt(30)): 1,
        sqrt(Rational(3, 7) + Rational(2, 35) * sqrt(30)): 1,
        -sqrt(Rational(3, 7) + Rational(2, 35) * sqrt(30)): 1,
    }

    n = Symbol("n")

    X = legendre(n, x)
    assert isinstance(X, legendre)
    assert unchanged(legendre, n, x)

    assert legendre(n,
                    0) == sqrt(pi) / (gamma(S.Half - n / 2) * gamma(n / 2 + 1))
    assert legendre(n, 1) == 1
    assert legendre(n, oo) is oo
    assert legendre(-n, x) == legendre(n - 1, x)
    assert legendre(n, -x) == (-1)**n * legendre(n, x)
    assert unchanged(legendre, -n + k, x)

    assert conjugate(legendre(n, x)) == legendre(n, conjugate(x))

    assert diff(legendre(n, x), x) == \
        n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
    assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n)

    _k = Dummy('k')
    assert legendre(n, x).rewrite("polynomial").dummy_eq(
        Sum((-1)**_k * (S.Half - x / 2)**_k * (x / 2 + S.Half)**(-_k + n) *
            binomial(n, _k)**2, (_k, 0, n)))
    raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(1))
    raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(3))
Exemple #20
0
 def pdf(self, x):
     x = sympify(x)
     if x.is_number:
         if x.is_Integer and x >= 1 and x <= self.sides:
             return Rational(1, self.sides)
         return S.Zero
     if x.is_Symbol:
         i = Dummy('i', integer=True, positive=True)
         return Sum(KroneckerDelta(x, i)/self.sides, (i, 1, self.sides))
     raise ValueError("'x' expected as an argument of type 'number' or 'symbol', "
                     "not %s" % (type(x)))
Exemple #21
0
 def cdf(self, other):
     assert isinstance(other, dict)
     rvs = other.keys()
     _set = self.domain.set
     expr = self.pdf(tuple(i.args[0] for i in self.symbols))
     for i in range(len(other)):
         if rvs[i].is_Continuous:
             density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]]))
         elif rvs[i].is_Discrete:
             density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]]))
     return density
def test_hyperexpand():
    # Luke, Y. L. (1969), The Special Functions and Their Approximations,
    # Volume 1, section 6.2

    assert hyperexpand(hyper([], [], z)) == exp(z)
    assert hyperexpand(hyper([1, 1], [2], -z)*z) == log(1 + z)
    assert hyperexpand(hyper([], [S.Half], -z**2/4)) == cos(z)
    assert hyperexpand(z*hyper([], [S('3/2')], -z**2/4)) == sin(z)
    assert hyperexpand(hyper([S('1/2'), S('1/2')], [S('3/2')], z**2)*z) \
        == asin(z)
    assert isinstance(Sum(binomial(2, z)*z**2, (z, 0, a)).doit(), Expr)
Exemple #23
0
    def _entry(self, i, j, expand=True):
        coeff, matrices = self.as_coeff_matrices()

        if len(matrices) == 1:  # situation like 2*X, matmul is just X
            return coeff * matrices[0][i, j]

        head, tail = matrices[0], matrices[1:]
        assert len(tail) != 0

        X = head
        Y = MatMul(*tail)

        from sympy.core.symbol import Dummy
        from sympy.concrete.summations import Sum
        from sympy.matrices import ImmutableMatrix, MatrixBase
        k = Dummy('k', integer=True)
        if X.has(ImmutableMatrix) or Y.has(ImmutableMatrix):
            return coeff*Add(*[X[i, k]*Y[k, j] for k in range(X.cols)])
        result = Sum(coeff*X[i, k]*Y[k, j], (k, 0, X.cols - 1))
        return result.doit() if expand else result
Exemple #24
0
    def _entry(self, i, j, expand=True):
        coeff, matrices = self.as_coeff_matrices()

        if len(matrices) == 1:  # situation like 2*X, matmul is just X
            return coeff * matrices[0][i, j]

        head, tail = matrices[0], matrices[1:]
        if len(tail) == 0:
            raise ValueError("lenth of tail cannot be 0")
        X = head
        Y = MatMul(*tail)

        from sympy.core.symbol import Dummy
        from sympy.concrete.summations import Sum
        from sympy.matrices import ImmutableMatrix
        k = Dummy('k', integer=True)
        if X.has(ImmutableMatrix) or Y.has(ImmutableMatrix):
            return coeff * Add(*[X[i, k] * Y[k, j] for k in range(X.cols)])
        result = Sum(coeff * X[i, k] * Y[k, j], (k, 0, X.cols - 1))
        return result.doit() if expand else result
Exemple #25
0
def test_plot_and_save_5():
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    y = Symbol('y')

    with TemporaryDirectory(prefix='sympy_') as tmpdir:
        s = Sum(1/x**y, (x, 1, oo))
        p = plot(s, (y, 2, 10))
        filename = 'test_advanced_inf_sum.png'
        p.save(os.path.join(tmpdir, filename))
        p._backend.close()

        p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
        p[0].only_integers = True
        p[0].steps = True
        filename = 'test_advanced_fin_sum.png'
        p.save(os.path.join(tmpdir, filename))
        p._backend.close()
def test_product_spaces():
    X1 = Geometric('X1', S.Half)
    X2 = Geometric('X2', Rational(1, 3))
    #assert str(P(X1 + X2 < 3, evaluate=False)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """\
    #    + """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, -oo, -1))"""
    n = Dummy('n')
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert P(X1 + X2 < 3, evaluate=False).rewrite(Sum).dummy_eq(
            Sum(Piecewise((2**(-n) / 4, n + 2 >= 1), (0, True)),
                (n, -oo, -1)) / 3)
    #assert str(P(X1 + X2 > 3)) == """Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, """ +\
    #    """(-X2 + n + 3 >= 1) & (-X2 + n + 3 < oo)), (0, True)), (X2, 1, oo), (n, 1, oo))"""
    assert P(X1 + X2 > 3).dummy_eq(
        Sum(
            Piecewise((2**(X2 - n - 2) *
                       (Rational(2, 3))**(X2 - 1) / 6, -X2 + n + 3 >= 1),
                      (0, True)), (X2, 1, oo), (n, 1, oo)))
    #    assert str(P(Eq(X1 + X2, 3))) == """Sum(Piecewise((2**(X2 - 2)*(2/3)**(X2 - 1)/6, """ +\
    #        """X2 <= 2), (0, True)), (X2, 1, oo))"""
    assert P(Eq(X1 + X2, 3)) == Rational(1, 12)
Exemple #27
0
def test_multiple_sums():
    if not np:
        skip("NumPy not installed")

    s = Sum((x + j) * i, (i, a, b), (j, c, d))
    f = lambdify((a, b, c, d, x), s, 'numpy')

    a_, b_ = 0, 10
    c_, d_ = 11, 21
    x_ = np.linspace(-1, +1, 10)
    assert np.allclose(f(a_, b_, c_, d_, x_),
                       sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
Exemple #28
0
def test_log_product():
    from sympy.abc import n, m
    i, j = symbols('i,j', positive=True, integer=True)
    x, y = symbols('x,y', positive=True)
    from sympy.concrete import Product, Sum
    f, g = Function('f'), Function('g')
    assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
    assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
            log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))

    expr = log(Product(-2, (n, 0, 4)))
    assert simplify(expr) == expr
Exemple #29
0
def test_exp_rewrite():
    from sympy.concrete.summations import Sum
    assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
    assert exp(x * I).rewrite(cos) == cos(x) + I * sin(x)
    assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
    assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
    assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
    assert exp(x).rewrite(tanh) == (1 + tanh(x / 2)) / (1 - tanh(x / 2))
    assert exp(pi * I / 4).rewrite(sqrt) == sqrt(2) / 2 + sqrt(2) * I / 2
    assert exp(pi * I / 3).rewrite(sqrt) == 1 / 2 + sqrt(3) * I / 2

    n = Symbol('n', integer=True)

    assert Sum((exp(pi * I / 2) / 2)**n,
               (n, 0, oo)).rewrite(sqrt).doit() == 4 / 5 + 2 * I / 5
    assert Sum(
        (exp(pi * I / 4) / 2)**n,
        (n, 0, oo)).rewrite(sqrt).doit() == 1 / (1 - sqrt(2) * (1 + I) / 4)
    assert Sum(
        (exp(pi * I / 3) / 2)**n,
        (n, 0, oo)).rewrite(sqrt).doit() == 1 / (3 / 4 - sqrt(3) * I / 4)
Exemple #30
0
 def pdf(self, *y):
     d, v, l, mu = self.delta, self.v, self.lamda, self.mu
     n = Symbol('n', negative=False, integer=True)
     k = len(l)
     sterm1 = Pow((1 - d), n)/\
             ((gamma(v + n)**(k - 1))*gamma(v)*gamma(n + 1))
     sterm2 = Mul.fromiter(mui*li**(-v - n) for mui, li in zip(mu, l))
     term1 = sterm1 * sterm2
     sterm3 = (v + n) * sum([mui * yi for mui, yi in zip(mu, y)])
     sterm4 = sum([exp(mui * yi)/li for (mui, yi, li) in zip(mu, y, l)])
     term2 = exp(sterm3 - sterm4)
     return Pow(d, v) * Sum(term1 * term2, (n, 0, S.Infinity))
Exemple #31
0
def test_log_product():
    from sympy.abc import n, m

    i, j = symbols('i,j', positive=True, integer=True)
    x, y = symbols('x,y', positive=True)
    z = symbols('z', real=True)
    w = symbols('w')

    expr = log(Product(x**i, (i, 1, n)))
    assert simplify(expr) == expr
    assert expr.expand() == Sum(i * log(x), (i, 1, n))
    expr = log(Product(x**i * y**j, (i, 1, n), (j, 1, m)))
    assert simplify(expr) == expr
    assert expr.expand() == Sum(i * log(x) + j * log(y), (i, 1, n), (j, 1, m))

    expr = log(Product(-2, (n, 0, 4)))
    assert simplify(expr) == expr
    assert expr.expand() == expr
    assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))

    expr = log(Product(exp(z * i), (i, 0, n)))
    assert expr.expand() == Sum(z * i, (i, 0, n))

    expr = log(Product(exp(w * i), (i, 0, n)))
    assert expr.expand() == expr
    assert expr.expand(force=True) == Sum(w * i, (i, 0, n))

    expr = log(Product(i**2 * abs(j), (i, 1, n), (j, 1, m)))
    assert expr.expand() == Sum(2 * log(i) + log(j), (i, 1, n), (j, 1, m))
Exemple #32
0
 def cdf(self, other):
     if not isinstance(other, dict):
         raise ValueError("%s should be of type dict, got %s" %
                          (other, type(other)))
     rvs = other.keys()
     _set = self.domain.set.sets
     expr = self.pdf(tuple(i.args[0] for i in self.symbols))
     for i in range(len(other)):
         if rvs[i].is_Continuous:
             density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]]))
         elif rvs[i].is_Discrete:
             density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]]))
     return density