Esempio n. 1
0
def test_sympyissue_7638():
    f = pi/log(sqrt(2))
    assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f)
    # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the
    # sign will be +/-1; for the previous "small arg" case, it didn't matter
    # that this could not be proved
    assert (1 + I)**(4*I*f) == cbrt((1 + I)**(12*I*f))

    assert cbrt((1 + I)**(I*(1 + 7*f))).exp == Rational(1, 3)
    r = symbols('r', extended_real=True)
    assert sqrt(r**2) == abs(r)
    assert cbrt(r**3) != r
    assert sqrt(Pow(2*I, Rational(5, 2))) != (2*I)**Rational(5, 4)
    p = symbols('p', positive=True)
    assert cbrt(p**2) == p**(2/Integer(3))
    assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I'
    assert sqrt(1/(1 + I)) == sqrt((1 - I)/2)  # or 1/sqrt(1 + I)
    e = 1/(1 - sqrt(2))
    assert sqrt(e) == I/sqrt(-1 + sqrt(2))
    assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2))
    assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp == Rational(1, 2)
    assert sqrt(r**(4/Integer(3))) != r**(2/Integer(3))
    assert sqrt((p + I)**(4/Integer(3))) == (p + I)**(2/Integer(3))
    assert sqrt((p - p**2*I)**2) == p - p**2*I
    assert sqrt((p + r*I)**2) != p + r*I
    e = (1 + I/5)
    assert sqrt(e**5) == e**Rational(5, 2)
    assert sqrt(e**6) == e**3
    assert sqrt((1 + I*r)**6) != (1 + I*r)**3
Esempio n. 2
0
def test_diofant_parser():
    x = Symbol('x')
    inputs = {
        '2*x':
        2 * x,
        '3.00':
        Float(3),
        '22/7':
        Rational(22, 7),
        '2+3j':
        2 + 3 * I,
        'exp(x)':
        exp(x),
        '-(2)':
        -Integer(2),
        '[-1, -2, 3]': [Integer(-1), Integer(-2),
                        Integer(3)],
        'Symbol("x").free_symbols':
        x.free_symbols,
        'Float(Integer(3).evalf(3))':
        3.00,
        'factorint(12, visual=True)':
        Mul(Pow(2, 2, evaluate=False),
            Pow(3, 1, evaluate=False),
            evaluate=False),
        'Limit(sin(x), x, 0, dir="-")':
        Limit(sin(x), x, 0, dir='-'),
    }
    for text, result in inputs.items():
        assert parse_expr(text) == result
Esempio n. 3
0
def test_pow_as_base_exp():
    assert (oo**(2 - x)).as_base_exp() == (oo, 2 - x)
    assert (oo**(x - 2)).as_base_exp() == (oo, x - 2)
    p = Rational(1, 2)**x
    assert p.base, p.exp == p.as_base_exp() == (Integer(2), -x)
    # issue sympy/sympy#8344:
    assert Pow(1, 2, evaluate=False).as_base_exp() == (Integer(1), Integer(2))
Esempio n. 4
0
def test_correct_arguments():
    pytest.raises(ValueError, lambda: R2.e_x(R2.e_x))
    pytest.raises(ValueError, lambda: R2.e_x(R2.dx))

    pytest.raises(ValueError, lambda: Commutator(R2.e_x, R2.x))
    pytest.raises(ValueError, lambda: Commutator(R2.dx, R2.e_x))

    pytest.raises(ValueError, lambda: Differential(Differential(R2.e_x)))

    pytest.raises(ValueError, lambda: R2.dx(R2.x))

    pytest.raises(ValueError, lambda: TensorProduct(R2.e_x, R2.dx))

    pytest.raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx))
    pytest.raises(ValueError, lambda: LieDerivative(R2.x, R2.dx))

    pytest.raises(ValueError, lambda: CovarDerivativeOp(R2.dx, []))
    pytest.raises(ValueError, lambda: CovarDerivativeOp(R2.x, []))

    a = Symbol('a')
    pytest.raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2])))
    pytest.raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2])))

    pytest.raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2])))
    pytest.raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2])))

    pytest.raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx))
    pytest.raises(ValueError, lambda: contravariant_order(R2.dx**2))
    pytest.raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx))

    pytest.raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y))
    pytest.raises(ValueError, lambda: covariant_order(R2.dx*R2.dy))

    assert covariant_order(Integer(0), True) == -1
    assert contravariant_order(Integer(0), True) == -1
Esempio n. 5
0
 def _new(cls, *args, **kwargs):
     if len(args) == 1 and isinstance(args[0], ImmutableMatrix):
         return args[0]
     rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
     rows = Integer(rows)
     cols = Integer(cols)
     mat = Tuple(*flat_list)
     return Basic.__new__(cls, rows, cols, mat)
Esempio n. 6
0
def test_term():
    assert arguments(2) == ()
    assert arguments(Integer(2)) == ()
    assert arguments(2 + x) == (2, x)
    assert operator(2 + x) == Add
    assert operator(Integer(2)) == Integer(2)
    assert term(Add, (2, x)) == 2 + x
    assert term(Integer(2), ()) == Integer(2)
Esempio n. 7
0
def test_pow_as_base_exp():
    x = Symbol('x')
    assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x)
    assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2)
    p = S.Half**x
    assert p.base, p.exp == p.as_base_exp() == (Integer(2), -x)
    # issue sympy/sympy#8344:
    assert Pow(1, 2, evaluate=False).as_base_exp() == (Integer(1), Integer(2))
Esempio n. 8
0
 def _new(cls, *args, **kwargs):
     s = MutableSparseMatrix(*args)
     rows = Integer(s.rows)
     cols = Integer(s.cols)
     mat = Dict(s._smat)
     obj = Basic.__new__(cls, rows, cols, mat)
     obj.rows = s.rows
     obj.cols = s.cols
     obj._smat = s._smat
     return obj
Esempio n. 9
0
def test_deltasummation_mul_x_kd():
    assert ds(x*KD(i, j), (j, 1, 3)) == \
        Piecewise((x, And(Integer(1) <= i, i <= 3)), (0, True))
    assert ds(x * KD(i, j), (j, 1, 1)) == Piecewise((x, Eq(i, 1)), (0, True))
    assert ds(x * KD(i, j), (j, 2, 2)) == Piecewise((x, Eq(i, 2)), (0, True))
    assert ds(x * KD(i, j), (j, 3, 3)) == Piecewise((x, Eq(i, 3)), (0, True))
    assert ds(x*KD(i, j), (j, 1, k)) == \
        Piecewise((x, And(Integer(1) <= i, i <= k)), (0, True))
    assert ds(x*KD(i, j), (j, k, 3)) == \
        Piecewise((x, And(k <= i, i <= 3)), (0, True))
    assert ds(x*KD(i, j), (j, k, l)) == \
        Piecewise((x, And(k <= i, i <= l)), (0, True))
Esempio n. 10
0
def test_deltasummation_basic_symbolic():
    assert ds(KD(i, j), (j, 1, 3)) == \
        Piecewise((1, And(Integer(1) <= i, i <= 3)), (0, True))
    assert ds(KD(i, j), (j, 1, 1)) == Piecewise((1, Eq(i, 1)), (0, True))
    assert ds(KD(i, j), (j, 2, 2)) == Piecewise((1, Eq(i, 2)), (0, True))
    assert ds(KD(i, j), (j, 3, 3)) == Piecewise((1, Eq(i, 3)), (0, True))
    assert ds(KD(i, j), (j, 1, k)) == \
        Piecewise((1, And(Integer(1) <= i, i <= k)), (0, True))
    assert ds(KD(i, j), (j, k, 3)) == \
        Piecewise((1, And(k <= i, i <= 3)), (0, True))
    assert ds(KD(i, j), (j, k, l)) == \
        Piecewise((1, And(k <= i, i <= l)), (0, True))
Esempio n. 11
0
    def __new__(cls, *args, **options):
        count = 0
        measure_number = Integer(1)
        zeroflag = False

        # Determine the component and check arguments
        # Also keep a count to ensure two vectors aren't
        # being multipled
        for arg in args:
            if isinstance(arg, cls._zero_func):
                count += 1
                zeroflag = True
            elif arg == Integer(0):
                zeroflag = True
            elif isinstance(arg, (cls._base_func, cls._mul_func)):
                count += 1
                expr = arg._base_instance
                measure_number *= arg._measure_number
            elif isinstance(arg, cls._add_func):
                count += 1
                expr = arg
            else:
                measure_number *= arg
        # Make sure incompatible types weren't multipled
        if count > 1:
            raise ValueError("Invalid multiplication")
        elif count == 0:
            return Mul(*args, **options)
        # Handle zero vector case
        if zeroflag:
            return cls.zero

        # If one of the args was a VectorAdd, return an
        # appropriate VectorAdd instance
        if isinstance(expr, cls._add_func):
            newargs = [cls._mul_func(measure_number, x) for x in expr.args]
            return cls._add_func(*newargs)

        obj = super(BasisDependentMul,
                    cls).__new__(cls, measure_number, expr._base_instance,
                                 **options)
        if isinstance(obj, Add):
            return cls._add_func(*obj.args)
        obj._base_instance = expr._base_instance
        obj._measure_number = measure_number
        assumptions = {}
        assumptions['commutative'] = True
        obj._assumptions = StdFactKB(assumptions)
        obj._components = {expr._base_instance: measure_number}
        obj._sys = expr._base_instance._sys

        return obj
Esempio n. 12
0
    def _eval_expand_func(self, **hints):
        from diofant import Sum
        n = self.args[0]
        m = self.args[1] if len(self.args) == 2 else 1

        if m == S.One:
            if n.is_Add:
                off = n.args[0]
                nnew = n - off
                if off.is_Integer and off.is_positive:
                    result = [S.One / (nnew + i)
                              for i in range(off, 0, -1)] + [harmonic(nnew)]
                    return Add(*result)
                elif off.is_Integer and off.is_negative:
                    result = [-S.One / (nnew + i)
                              for i in range(0, off, -1)] + [harmonic(nnew)]
                    return Add(*result)

            if n.is_Rational:
                # Expansions for harmonic numbers at general rational arguments (u + p/q)
                # Split n as u + p/q with p < q
                p, q = n.as_numer_denom()
                u = p // q
                p = p - u * q
                if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
                    k = Dummy("k")
                    t1 = q * Sum(1 / (q * k + p), (k, 0, u))
                    t2 = 2 * Sum(
                        cos((2 * pi * p * k) / q) * log(sin((pi * k) / q)),
                        (k, 1, floor((q - 1) / Integer(2))))
                    t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
                    return t1 + t2 - t3

        return self
Esempio n. 13
0
def test_deltaproduct_mul_add_x_y_add_y_kd():
    assert dp((x + y)*(y + KD(i, j)), (j, 1, 3)) == ((x + y)*y)**3 + \
        (x + y)*((x + y)*y)**2*KD(i, 1) + \
        (x + y)*y*(x + y)**2*y*KD(i, 2) + \
        ((x + y)*y)**2*(x + y)*KD(i, 3)
    assert dp((x + y) * (y + KD(i, j)), (j, 1, 1)) == (x + y) * (y + KD(i, 1))
    assert dp((x + y) * (y + KD(i, j)), (j, 2, 2)) == (x + y) * (y + KD(i, 2))
    assert dp((x + y) * (y + KD(i, j)), (j, 3, 3)) == (x + y) * (y + KD(i, 3))
    assert dp((x + y)*(y + KD(i, j)), (j, 1, k)) == \
        ((x + y)*y)**k + Piecewise(
            (((x + y)*y)**(i - 1)*(x + y)*((x + y)*y)**(k - i),
             And(Integer(1) <= i, i <= k)),
            (0, True)
    )
    assert dp((x + y)*(y + KD(i, j)), (j, k, 3)) == \
        ((x + y)*y)**(-k + 4) + Piecewise(
            (((x + y)*y)**(i - k)*(x + y)*((x + y)*y)**(3 - i),
             And(k <= i, i <= 3)),
            (0, True)
    )
    assert dp((x + y)*(y + KD(i, j)), (j, k, l)) == \
        ((x + y)*y)**(-k + l + 1) + Piecewise(
            (((x + y)*y)**(i - k)*(x + y)*((x + y)*y)**(l - i),
             And(k <= i, i <= l)),
            (0, True)
    )
Esempio n. 14
0
def test_deltaproduct_mul_add_x_kd_add_y_kd():
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == \
        KD(i, 1)*(KD(i, k) + x)*((KD(i, k) + x)*y)**2 + \
        KD(i, 2)*(KD(i, k) + x)*y*(KD(i, k) + x)**2*y + \
        KD(i, 3)*((KD(i, k) + x)*y)**2*(KD(i, k) + x) + \
        ((KD(i, k) + x)*y)**3
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == \
        (x + KD(i, k))*(y + KD(i, 1))
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == \
        (x + KD(i, k))*(y + KD(i, 2))
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == \
        (x + KD(i, k))*(y + KD(i, 3))
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == \
        ((x + KD(i, k))*y)**k + Piecewise(
            (((x + KD(i, k))*y)**(i - 1)*(x + KD(i, k)) *
             ((x + KD(i, k))*y)**(-i + k), And(Integer(1) <= i, i <= k)),
            (0, True)
    )
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == \
        ((x + KD(i, k))*y)**(4 - k) + Piecewise(
            (((x + KD(i, k))*y)**(i - k)*(x + KD(i, k)) *
             ((x + KD(i, k))*y)**(-i + 3), And(k <= i, i <= 3)),
            (0, True)
    )
    assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == \
        ((x + KD(i, k))*y)**(-k + l + 1) + Piecewise(
            (((x + KD(i, k))*y)**(i - k)*(x + KD(i, k)) *
             ((x + KD(i, k))*y)**(-i + l), And(k <= i, i <= l)),
            (0, True)
    )
Esempio n. 15
0
def test_deltasummation_mul_x_add_y_kd():
    assert ds(x*(y + KD(i, j)), (j, 1, 3)) == \
        Piecewise((3*x*y + x, And(Integer(1) <= i, i <= 3)), (3*x*y, True))
    assert ds(x*(y + KD(i, j)), (j, 1, 1)) == \
        Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
    assert ds(x*(y + KD(i, j)), (j, 2, 2)) == \
        Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
    assert ds(x*(y + KD(i, j)), (j, 3, 3)) == \
        Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
    assert ds(x*(y + KD(i, j)), (j, 1, k)) == \
        Piecewise((k*x*y + x, And(Integer(1) <= i, i <= k)), (k*x*y, True))
    assert ds(x*(y + KD(i, j)), (j, k, 3)) == \
        Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
    assert ds(x * (y + KD(i, j)), (j, k, l)) == Piecewise(
        ((l - k + 1) * x * y + x, And(k <= i, i <= l)),
        ((l - k + 1) * x * y, True))
Esempio n. 16
0
def test_prime():
    assert Integer(-1).is_prime is False
    assert Integer(-2).is_prime is False
    assert Integer(-4).is_prime is False
    assert Integer(0).is_prime is False
    assert Integer(1).is_prime is False
    assert Integer(2).is_prime is True
    assert Integer(17).is_prime is True
    assert Integer(4).is_prime is False
Esempio n. 17
0
 def eval(cls, m):
     if m.is_odd:
         return S.Zero
     if m.is_Integer and m.is_nonnegative:
         from mpmath import mp
         m = m._to_mpmath(mp.prec)
         res = mp.eulernum(m, exact=True)
         return Integer(res)
Esempio n. 18
0
def test_monomial_key():
    assert monomial_key() == lex

    assert monomial_key('lex') == lex
    assert monomial_key('grlex') == grlex
    assert monomial_key('grevlex') == grevlex

    pytest.raises(ValueError, lambda: monomial_key('foo'))
    pytest.raises(ValueError, lambda: monomial_key(1))

    M = [x, x**2*z**2, x*y, x**2, Integer(1), y**2, x**3, y, z, x*y**2*z, x**2*y**2]
    assert sorted(M, key=monomial_key('lex', [z, y, x])) == \
        [Integer(1), x, x**2, x**3, y, x*y, y**2, x**2*y**2, z, x*y**2*z, x**2*z**2]
    assert sorted(M, key=monomial_key('grlex', [z, y, x])) == \
        [Integer(1), x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x*y**2*z, x**2*z**2]
    assert sorted(M, key=monomial_key('grevlex', [z, y, x])) == \
        [Integer(1), x, y, z, x**2, x*y, y**2, x**3, x**2*y**2, x**2*z**2, x*y**2*z]
Esempio n. 19
0
 def eval(cls, n, k_sym=None, symbols=None):
     if n.is_Integer and n.is_nonnegative:
         if k_sym is None:
             return Integer(cls._bell(int(n)))
         elif symbols is None:
             return cls._bell_poly(int(n)).subs(_sym, k_sym)
         else:
             r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
             return r
Esempio n. 20
0
def test_local_dict():
    local_dict = {
        'my_function': lambda x: x + 2
    }
    inputs = {
        'my_function(2)': Integer(4)
    }
    for text, result in inputs.items():
        assert parse_expr(text, local_dict=local_dict) == result
Esempio n. 21
0
def test_composite():
    assert Integer(-1).is_composite is False
    assert Integer(-2).is_composite is False
    assert Integer(-4).is_composite is False
    assert Integer(0).is_composite is False
    assert Integer(2).is_composite is False
    assert Integer(17).is_composite is False
    assert Integer(4).is_composite is True
Esempio n. 22
0
def jacobi_normalized(n, a, b, x):
    r"""
    Jacobi polynomial :math:`P_n^{\left(\alpha, \beta\right)}(x)`

    jacobi_normalized(n, alpha, beta, x) gives the nth Jacobi polynomial
    in x, :math:`P_n^{\left(\alpha, \beta\right)}(x)`.

    The Jacobi polynomials are orthogonal on :math:`[-1, 1]` with respect
    to the weight :math:`\left(1-x\right)^\alpha \left(1+x\right)^\beta`.

    This functions returns the polynomials normilzed:

    .. math::

        \int_{-1}^{1}
          P_m^{\left(\alpha, \beta\right)}(x)
          P_n^{\left(\alpha, \beta\right)}(x)
          (1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x
        = \delta_{m,n}

    Examples
    ========

    >>> from diofant import jacobi_normalized
    >>> from diofant.abc import n,a,b,x

    >>> jacobi_normalized(n, a, b, x)
    jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))

    See Also
    ========

    gegenbauer,
    chebyshevt_root, chebyshevu, chebyshevu_root,
    legendre, assoc_legendre,
    hermite,
    laguerre, assoc_laguerre,
    diofant.polys.orthopolys.jacobi_poly,
    diofant.polys.orthopolys.gegenbauer_poly
    diofant.polys.orthopolys.chebyshevt_poly
    diofant.polys.orthopolys.chebyshevu_poly
    diofant.polys.orthopolys.hermite_poly
    diofant.polys.orthopolys.legendre_poly
    diofant.polys.orthopolys.laguerre_poly

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Jacobi_polynomials
    .. [2] http://mathworld.wolfram.com/JacobiPolynomial.html
    .. [3] http://functions.wolfram.com/Polynomials/JacobiP/
    """
    nfactor = (Integer(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1))
               / (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1)))

    return jacobi(n, a, b, x) / sqrt(nfactor)
Esempio n. 23
0
    def radius_of_convergence(self):
        """
        Compute the radius of convergence of the defining series.

        Note that even if this is not oo, the function may still be evaluated
        outside of the radius of convergence by analytic continuation. But if
        this is zero, then the function is not actually defined anywhere else.

        >>> from diofant.functions import hyper
        >>> from diofant.abc import z
        >>> hyper((1, 2), [3], z).radius_of_convergence
        1
        >>> hyper((1, 2, 3), [4], z).radius_of_convergence
        0
        >>> hyper((1, 2), (3, 4), z).radius_of_convergence
        oo
        """
        if any(a.is_integer and (a <= 0) is S.true for a in self.ap + self.bq):
            aints = [a for a in self.ap if a.is_Integer and (a <= 0) is S.true]
            bints = [a for a in self.bq if a.is_Integer and (a <= 0) is S.true]
            if len(aints) < len(bints):
                return Integer(0)
            popped = False
            for b in bints:
                cancelled = False
                while aints:
                    a = aints.pop()
                    if a >= b:
                        cancelled = True
                        break
                    popped = True
                if not cancelled:
                    return Integer(0)
            if aints or popped:
                # There are still non-positive numerator parameters.
                # This is a polynomial.
                return oo
        if len(self.ap) == len(self.bq) + 1:
            return Integer(1)
        elif len(self.ap) <= len(self.bq):
            return oo
        else:
            return Integer(0)
Esempio n. 24
0
def test_deltasummation_mul_add_x_kd_add_y_kd():
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, 1, 3)) == piecewise_fold(
        Piecewise((KD(i, k) + x, And(Integer(1) <= i, i <= 3)), (0, True)) +
        3 * (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, 1, 1)) == piecewise_fold(
        Piecewise((KD(i, k) + x, Eq(i, 1)), (0, True)) + (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, 2, 2)) == piecewise_fold(
        Piecewise((KD(i, k) + x, Eq(i, 2)), (0, True)) + (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, 3, 3)) == piecewise_fold(
        Piecewise((KD(i, k) + x, Eq(i, 3)), (0, True)) + (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, 1, k)) == piecewise_fold(
        Piecewise((KD(i, k) + x, And(Integer(1) <= i, i <= k)), (0, True)) +
        k * (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, k, 3)) == piecewise_fold(
        Piecewise((KD(i, k) + x, And(k <= i, i <= 3)), (0, True)) + (4 - k) *
        (KD(i, k) + x) * y)
    assert ds((x + KD(i, k)) * (y + KD(i, j)), (j, k, l)) == piecewise_fold(
        Piecewise((KD(i, k) + x, And(k <= i, i <= l)), (0, True)) +
        (l - k + 1) * (KD(i, k) + x) * y)
Esempio n. 25
0
class Inverse(MatPow):
    """
    The multiplicative inverse of a matrix expression

    This is a symbolic object that simply stores its argument without
    evaluating it. To actually compute the inverse, use the ``.inverse()``
    method of matrices.

    Examples
    ========

    >>> from diofant import MatrixSymbol, Inverse
    >>> A = MatrixSymbol('A', 3, 3)
    >>> B = MatrixSymbol('B', 3, 3)
    >>> Inverse(A)
    A^-1
    >>> A.inverse() == Inverse(A)
    True
    >>> (A*B).inverse()
    B^-1*A^-1
    >>> Inverse(A*B)
    (A*B)^-1

    """
    is_Inverse = True
    exp = Integer(-1)

    def __new__(cls, mat):
        mat = _sympify(mat)
        if not mat.is_Matrix:
            raise TypeError("mat should be a matrix")
        if not mat.is_square:
            raise ShapeError("Inverse of non-square matrix %s" % mat)
        return Basic.__new__(cls, mat)

    @property
    def arg(self):
        return self.args[0]

    @property
    def shape(self):
        return self.arg.shape

    def _eval_inverse(self):
        return self.arg

    def _eval_determinant(self):
        from diofant.matrices.expressions.determinant import det
        return 1/det(self.arg)

    def doit(self, **hints):
        if hints.get('deep', True):
            return self.arg.doit(**hints).inverse()
        else:
            return self.arg.inverse()
Esempio n. 26
0
def test_mul():
    Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
    a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
    t = TensMul.from_data(Integer(1), [], [], [])
    assert str(t) == '1'
    A, B = tensorhead('A B', [Lorentz] * 2, [[1] * 2])
    t = (1 + x) * A(a, b)
    assert str(t) == '(x + 1)*A(a, b)'
    assert t.types == [Lorentz]
    assert t.rank == 2
    assert t.dum == []
    assert t.coeff == 1 + x
    assert sorted(t.free) == [(a, 0, 0), (b, 1, 0)]
    assert t.components == [A]

    ts = A(a, b)
    assert str(ts) == 'A(a, b)'
    assert ts.types == [Lorentz]
    assert ts.rank == 2
    assert ts.dum == []
    assert ts.coeff == 1
    assert sorted(ts.free) == [(a, 0, 0), (b, 1, 0)]
    assert ts.components == [A]

    t = A(-b, a) * B(-a, c) * A(-c, d)
    t1 = tensor_mul(*t.split())
    assert t == t(-b, d)
    assert t == t1
    assert tensor_mul(*[]) == TensMul.from_data(Integer(1), [], [], [])

    t = TensMul.from_data(1, [], [], [])
    zsym = tensorsymmetry()
    typ = TensorType([], zsym)
    C = typ('C')
    assert str(C()) == 'C'
    assert str(t) == '1'
    assert t.split()[0] == t
    pytest.raises(ValueError, lambda: TIDS.free_dum_from_indices(a, a))
    pytest.raises(ValueError, lambda: TIDS.free_dum_from_indices(-a, -a))
    pytest.raises(ValueError, lambda: A(a, b) * A(a, c))
    t = A(a, b) * A(-a, c)
    pytest.raises(ValueError, lambda: t(a, b, c))
Esempio n. 27
0
 def eval(cls, n, sym=None):
     if n.is_Integer:
         n = int(n)
         if n < 0:
             return S.NegativeOne**(n + 1) * fibonacci(-n)
         if sym is None:
             return Integer(cls._fib(n))
         else:
             if n < 1:
                 raise ValueError("Fibonacci polynomials are defined "
                                  "only for positive integer indices.")
             return cls._fibpoly(n).subs(_sym, sym)
Esempio n. 28
0
    def eval(cls, n):
        if n.is_Number:
            if (not n.is_Integer) or n.is_nonpositive:
                raise ValueError("Genocchi numbers are defined only for " +
                                 "positive integers")
            return 2 * (1 - Integer(2)**n) * bernoulli(n)

        if n.is_odd and (n - 1).is_positive:
            return S.Zero

        if (n - 1).is_zero:
            return S.One
Esempio n. 29
0
def test_deltasummation_basic_numerical():
    n = symbols('n', integer=True, nonzero=True)
    assert ds(KD(n, 0), (n, 1, 3)) == 0

    # return unevaluated, until it gets implemented
    assert ds(KD(i**2, j**2), (j, -oo, oo)) == \
        Sum(KD(i**2, j**2), (j, -oo, oo))

    assert Piecewise((KD(i, k), And(Integer(1) <= i, i <= 3)), (0, True)) == \
        ds(KD(i, j)*KD(j, k), (j, 1, 3)) == \
        ds(KD(j, k)*KD(i, j), (j, 1, 3))

    assert ds(KD(i, k), (k, -oo, oo)) == 1
    assert ds(KD(i, k), (k, 0, oo)) == Piecewise((1, Integer(0) <= i),
                                                 (0, True))
    assert ds(KD(i, k), (k, 1, 3)) == \
        Piecewise((1, And(Integer(1) <= i, i <= 3)), (0, True))
    assert ds(k * KD(i, j) * KD(j, k), (k, -oo, oo)) == j * KD(i, j)
    assert ds(j * KD(i, j), (j, -oo, oo)) == i
    assert ds(i * KD(i, j), (i, -oo, oo)) == j
    assert ds(x, (i, 1, 3)) == 3 * x
    assert ds((i + j) * KD(i, j), (j, -oo, oo)) == 2 * i
Esempio n. 30
0
def test_deltasummation_mul_add_x_y_add_kd_kd():
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
        Piecewise((x + y, And(Integer(1) <= i, i <= 3)), (0, True)) +
        Piecewise((x + y, And(Integer(1) <= j, j <= 3)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
        Piecewise((x + y, Eq(i, 1)), (0, True)) +
        Piecewise((x + y, Eq(j, 1)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
        Piecewise((x + y, Eq(i, 2)), (0, True)) +
        Piecewise((x + y, Eq(j, 2)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
        Piecewise((x + y, Eq(i, 3)), (0, True)) +
        Piecewise((x + y, Eq(j, 3)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
        Piecewise((x + y, And(Integer(1) <= i, i <= l)), (0, True)) +
        Piecewise((x + y, And(Integer(1) <= j, j <= l)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
        Piecewise((x + y, And(l <= i, i <= 3)), (0, True)) +
        Piecewise((x + y, And(l <= j, j <= 3)), (0, True)))
    assert ds((x + y) * (KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
        Piecewise((x + y, And(l <= i, i <= m)), (0, True)) +
        Piecewise((x + y, And(l <= j, j <= m)), (0, True)))