Beispiel #1
0
def test_sympyissue_3449():
    # test if powers are simplified correctly
    # see also issue sympy/sympy#3995
    assert cbrt(x)**2 == x**Rational(2, 3)
    assert (x**3)**Rational(2, 5) == Pow(x**3, Rational(2, 5), evaluate=False)

    a = Symbol('a', extended_real=True)
    b = Symbol('b', extended_real=True)
    assert (a**2)**b == (abs(a)**b)**2
    assert sqrt(1/a) != 1/sqrt(a)  # e.g. for a = -1
    assert cbrt(a**3) != a
    assert (x**a)**b != x**(a*b)  # e.g. x = -1, a=2, b=1/2
    assert (x**.5)**b == x**(.5*b)
    assert (x**.5)**.5 == x**.25
    assert (x**2.5)**.5 != x**1.25  # e.g. for x = 5*I

    k = Symbol('k', integer=True)
    m = Symbol('m', integer=True)
    assert (x**k)**m == x**(k*m)
    assert Number(5)**Rational(2, 3) == cbrt(Number(25))

    assert (x**.5)**2 == x**1.0
    assert (x**2)**k == (x**k)**2 == x**(2*k)

    a = Symbol('a', positive=True)
    assert (a**3)**Rational(2, 5) == a**Rational(6, 5)
    assert (a**2)**b == (a**b)**2
    assert (a**Rational(2, 3))**x == (a**(2*x/3)) != (a**x)**Rational(2, 3)
Beispiel #2
0
def test_add2():
    Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
    m, n, p, q = tensor_indices('m,n,p,q', Lorentz)
    R = tensorhead('R', [Lorentz] * 4, [[2, 2]])
    A = tensorhead('A', [Lorentz] * 3, [[3]])
    t1 = 2 * R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q)
    t2 = t1 * A(-n, -p, -q)
    assert t2 == 0
    t1 = Rational(2, 3) * R(m, n, p, q) - Rational(1, 3) * R(
        m, q, n, p) + Rational(1, 3) * R(m, p, n, q)
    t2 = t1 * A(-n, -p, -q)
    assert t2 == 0
    t = A(m, -m, n) + A(n, p, -p)
    assert t == 0
Beispiel #3
0
    def _print_Mul(self, expr):

        prec = precedence(expr)

        c, e = expr.as_coeff_Mul()
        if c < 0:
            expr = _keep_coeff(-c, e)
            sign = "-"
        else:
            sign = ""

        a = []  # items in the numerator
        b = []  # items that are in the denominator (if any)

        if self.order != 'none':
            args = expr.as_ordered_factors()
        else:
            # use make_args in case expr was something like -x -> x
            args = Mul.make_args(expr)

        multiple_ones = len([x for x in args if x == S.One]) > 1

        # Gather args for numerator/denominator
        for item in args:
            if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
                if item.exp != -1:
                    b.append(Pow(item.base, -item.exp, evaluate=False))
                else:
                    b.append(Pow(item.base, -item.exp))
            elif item.is_Rational and item is not S.Infinity:
                if item.p != 1 or multiple_ones:
                    a.append(Rational(item.p))
                if item.q != 1:
                    b.append(Rational(item.q))
            else:
                a.append(item)

        a = a or [S.One]

        a_str = [self.parenthesize(x, prec) for x in a]
        b_str = [self.parenthesize(x, prec) for x in b]

        if len(b) == 0:
            return sign + '*'.join(a_str)
        elif len(b) == 1:
            return sign + '*'.join(a_str) + "/" + b_str[0]
        else:
            return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
Beispiel #4
0
def test_Pow():
    assert mcode(x**3) == "x^3"
    assert mcode(x**(y**3)) == "x^(y^3)"
    assert mcode(1/(f(x)*3.5)**(x - y**x)/(x**2 + y)) == \
        "(3.5*f[x])^(-x + y^x)/(x^2 + y)"
    assert mcode(x**-1.0) == 'x^(-1.0)'
    assert mcode(x**Rational(2, 3)) == 'x^(2/3)'
Beispiel #5
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))
Beispiel #6
0
def test_sympyissue_6990():
    x = Symbol('x')
    a = Symbol('a')
    b = Symbol('b')
    assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \
        b*x/(2*sqrt(a)) + x**2*(1/(2*sqrt(a)) -
        b**2/(8*a**Rational(3, 2))) + sqrt(a)
Beispiel #7
0
def test_simplex():
    pytest.raises(ValueError, lambda: simplex([1], [[1, 2], [2, 3]], [4, 7]))
    pytest.raises(ValueError, lambda: simplex([1, 3], [[1, 2], [2, 3]], [4]))

    pytest.raises(InfeasibleProblem,
                  lambda: simplex([1, 3], [[1, 2], [2, 3]], [-3, 1]))

    assert simplex([2, 3, 2], [[2, 1, 1], [1, 2, 1], [0, 0, 1]],
                   [4, 7, 5]) == (11, (0, 3, 1))
    assert simplex([2, 3, 4], [[3, 2, 1], [2, 5, 3]],
                   [10, 15]) == (20, (0, 0, 5))
    assert simplex([Rational(1, 2), 3, 1, 1],
                   [[1, 1, 1, 1], [-2, -1, 1, 1], [0, 1, 0, -1]],
                   [40, 10, 10]) == (90, (0, 25, 0, 15))

    assert simplex([2, 1], [[-1, 1], [1, -2]], [1, 2]) == (oo, (oo, oo))

    assert simplex([1, 2, 3, -2],
                   [[3, -2, 1, 1], [-2, 1, 10, -1], [2, 0, 0, 1]],
                   [1, -2, 3]) == (-4, (0, 1, 0, 3))

    pytest.raises(
        InfeasibleProblem, lambda: simplex(
            [1, 2, 3, -2], [[3, -2, 1, 1], [-2, 1, 10, -1], [2, 0, 0, 1],
                            [0, -1, 2, 0]], [1, -2, 3, -3]))
Beispiel #8
0
def test_Pow():
    assert mcode(x**3) == "x.^3"
    assert mcode(x**(y**3)) == "x.^(y.^3)"
    assert mcode(x**Rational(2, 3)) == 'x.^(2/3)'
    g = implemented_function('g', Lambda(x, 2 * x))
    assert mcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
        "(3.5*2*x).^(-x + y.^x)./(x.^2 + y)"
Beispiel #9
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
Beispiel #10
0
def test_rationalize():
    inputs = {
        '0.123': Rational(123, 1000)
    }
    transformations = standard_transformations + (rationalize,)
    for text, result in inputs.items():
        assert parse_expr(text, transformations=transformations) == result
Beispiel #11
0
def test_doit_with_MatrixBase():
    X = ImmutableMatrix([[1, 2], [3, 4]])
    assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2))
    assert MatPow(X, 1).doit() == X
    assert MatPow(X, 2).doit() == X**2
    assert MatPow(X, -1).doit() == X.inv()
    assert MatPow(X, -2).doit() == (X.inv())**2
    # less expensive than testing on a 2x2
    assert MatPow(ImmutableMatrix([4]), Rational(1, 2)).doit() == ImmutableMatrix([2])
Beispiel #12
0
def test_minimize_linear():
    assert minimize([
        -2 * x - 3 * y - 2 * z, 2 * x + y + z <= 4, x + 2 * y + z <= 7, z <= 5,
        x >= 0, y >= 0, z >= 0
    ], x, y, z) == (-11, {
        x: 0,
        y: 3,
        z: 1
    })
    assert minimize([
        -2 * x - 3 * y - 2 * z, 2 * x + y + z <= 4, x + 2 * y + z <= 7, z <= 5,
        x >= 0, y >= 0, z >= 0
    ], x, y, z) == (-11, {
        x: 0,
        y: 3,
        z: 1
    })
    assert minimize([
        -2 * x - 3 * y - 2 * z, 2 * x + y + z <= 4, x + 2 * y + z < 7, z <= 5,
        x >= 0, y >= 0, z >= 0
    ], x, y, z) is None
    assert minimize([
        -2 * x - 3 * y - 4 * z, 3 * x + 2 * y + z <= 10,
        2 * x + 5 * y + 3 * z <= 15, x >= 0, y >= 0, z >= 0
    ], x, y, z) == (-20, {
        x: 0,
        y: 0,
        z: 5
    })
    assert maximize([
        12 * x + 40 * y, x + y <= 15, x + 3 * y <= 36, x <= 10, x >= 0, y >= 0
    ], x, y) == (480, {
        x: 0,
        y: 12
    })
    assert minimize([
        -2 * x - 3 * y - 4 * z,
        Eq(3 * x + 2 * y + z, 10),
        Eq(2 * x + 5 * y + 3 * z, 15), x >= 0, y >= 0, z >= 0
    ], x, y, z) == (Rational(-130, 7), {
        x: Rational(15, 7),
        y: 0,
        z: Rational(25, 7)
    })
Beispiel #13
0
 def _eval_Eq(self, other):
     # RootOf represents a Root, so if other is that root, it should set
     # the expression to zero *and* it should be in the interval of the
     # RootOf instance. It must also be a number that agrees with the
     # is_real value of the RootOf instance.
     if type(self) == type(other):
         return sympify(self.__eq__(other))
     if not (other.is_number and not other.has(AppliedUndef)):
         return S.false
     if not other.is_finite:
         return S.false
     z = self.expr.subs(self.expr.free_symbols.pop(), other).is_zero
     if z is False:  # all roots will make z True but we don't know
         # whether this is the right root if z is True
         return S.false
     o = other.is_extended_real, other.is_imaginary
     s = self.is_extended_real, self.is_imaginary
     if o != s and None not in o and None not in s:
         return S.false
     i = self._get_interval()
     was = i.a, i.b
     need = [True] * 2
     # make sure it would be distinct from others
     while any(need):
         i = i.refine()
         a, b = i.a, i.b
         if need[0] and a != was[0]:
             need[0] = False
         if need[1] and b != was[1]:
             need[1] = False
     re, im = other.as_real_imag()
     if not im:
         if self.is_extended_real:
             a, b = [Rational(str(i)) for i in (a, b)]
             return sympify(a < other and other < b)
         return S.false
     if self.is_extended_real:
         return S.false
     z = r1, r2, i1, i2 = [
         Rational(str(j)) for j in (i.ax, i.bx, i.ay, i.by)
     ]
     return sympify((r1 < re and re < r2) and (i1 < im and im < i2))
Beispiel #14
0
def _sin_pow_integrate(n, x):
    if n > 0:
        if n == 1:
            # Recursion break
            return -cos(x)

        #  n > 0
        #   /                                                 /
        #  |                                                 |
        #  |    n           -1               n-1     n - 1   |     n-2
        #  | sin (x) dx =  ______ cos (x) sin (x) + _______  |  sin (x) dx
        #  |                                                 |
        #  |                 n                         n     |
        # /                                                 /
        #

        return (Rational(-1, n) * cos(x) * sin(x)**(n - 1) +
                Rational(n - 1, n) * _sin_pow_integrate(n - 2, x))

    if n < 0:
        if n == -1:
            # Make sure this does not come back here again.
            # Recursion breaks here or at n==0.
            return trigintegrate(1 / sin(x), x)

        #  n < 0
        #   /                                                 /
        #  |                                                 |
        #  |    n            1               n+1     n + 2   |     n+2
        #  | sin (x) dx = _______ cos (x) sin (x) + _______  |  sin (x) dx
        #  |                                                 |
        #  |               n + 1                     n + 1   |
        # /                                                 /
        #

        return (Rational(1, n + 1) * cos(x) * sin(x)**(n + 1) +
                Rational(n + 2, n + 1) * _sin_pow_integrate(n + 2, x))

    else:
        # n == 0
        # Recursion break.
        return x
Beispiel #15
0
def test_1_over_x_and_sqrt():
    # 1.0 and 0.5 would do something different in regular StrPrinter,
    # but these are exact in IEEE floating point so no different here.
    assert mcode(1 / x) == '1./x'
    assert mcode(x**-1) == mcode(x**-1.0) == '1./x'
    assert mcode(1 / sqrt(x)) == '1./sqrt(x)'
    assert mcode(x**Rational(-1, 2)) == mcode(x**-0.5) == '1./sqrt(x)'
    assert mcode(sqrt(x)) == mcode(x**0.5) == 'sqrt(x)'
    assert mcode(1 / pi) == '1/pi'
    assert mcode(pi**-1) == mcode(pi**-1.0) == '1/pi'
    assert mcode(pi**-0.5) == '1/sqrt(pi)'
Beispiel #16
0
def test_ccode_Pow():
    assert ccode(x**3) == "pow(x, 3)"
    assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
    g = implemented_function('g', Lambda(x, 2 * x))
    assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
        "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)"
    assert ccode(x**-1.0) == '1.0/x'
    assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0L/3.0L)'
    _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
                   (lambda base, exp: not exp.is_integer, "pow")]
    assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
    assert ccode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)'
Beispiel #17
0
def test_MatrixSymbol():
    n = Symbol('n', integer=True)
    A = MatrixSymbol('A', n, n)
    B = MatrixSymbol('B', n, n)
    assert mcode(A * B) == "A*B"
    assert mcode(B * A) == "B*A"
    assert mcode(2 * A * B) == "2*A*B"
    assert mcode(B * 2 * A) == "2*B*A"
    assert mcode(A * (B + 3 * Identity(n))) == "A*(B + 3*eye(n))"
    assert mcode(A**(x**2)) == "A^(x.^2)"
    assert mcode(A**3) == "A^3"
    assert mcode(A**Rational(1, 2)) == "A^(1/2)"
Beispiel #18
0
def test_neg_rational():
    r = Rational(-3, 4)
    assert r.is_positive is False
    assert r.is_nonpositive is True
    assert r.is_negative is True
    assert r.is_nonnegative is False
    r = Rational(-1, 4)
    assert r.is_nonpositive is True
    assert r.is_positive is False
    assert r.is_negative is True
    assert r.is_nonnegative is False
    r = Rational(-5, 4)
    assert r.is_negative is True
    assert r.is_positive is False
    assert r.is_nonpositive is True
    assert r.is_nonnegative is False
    r = Rational(-5, 3)
    assert r.is_nonnegative is False
    assert r.is_positive is False
    assert r.is_negative is True
    assert r.is_nonpositive is True
Beispiel #19
0
def test_riemann_cyclic():
    Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
    i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
    R = tensorhead('R', [Lorentz] * 4, [[2, 2]])
    t = R(i, j, k, l) + R(i, l, j, k) + R(i, k, l, j) - \
        R(i, j, l, k) - R(i, l, k, j) - R(i, k, j, l)
    t2 = t * R(-i, -j, -k, -l)
    t3 = riemann_cyclic(t2)
    assert t3 == 0
    t = R(i, j, k, l) * (R(-i, -j, -k, -l) - 2 * R(-i, -k, -j, -l))
    t1 = riemann_cyclic(t)
    assert t1 == 0
    t = R(i, j, k, l)
    t1 = riemann_cyclic(t)
    assert t1 == -Rational(1, 3) * R(i, l, j, k) + Rational(1, 3) * R(
        i, k, j, l) + Rational(2, 3) * R(i, j, k, l)

    t = R(i, j, k, l) * R(-k, -l, m,
                          n) * (R(-m, -n, -i, -j) + 2 * R(-m, -j, -n, -i))
    t1 = riemann_cyclic(t)
    assert t1 == 0
Beispiel #20
0
def test_ccode_Rational():
    assert ccode(Rational(3, 7)) == "3.0L/7.0L"
    assert ccode(Rational(18, 9)) == "2"
    assert ccode(Rational(3, -7)) == "-3.0L/7.0L"
    assert ccode(Rational(-3, -7)) == "3.0L/7.0L"
    assert ccode(x + Rational(3, 7)) == "x + 3.0L/7.0L"
    assert ccode(Rational(3, 7) * x) == "(3.0L/7.0L)*x"
Beispiel #21
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
Beispiel #22
0
def _cos_pow_integrate(n, x):
    if n > 0:
        if n == 1:
            # Recursion break.
            return sin(x)

        #  n > 0
        #   /                                                 /
        #  |                                                 |
        #  |    n            1               n-1     n - 1   |     n-2
        #  | sin (x) dx =  ______ sin (x) cos (x) + _______  |  cos (x) dx
        #  |                                                 |
        #  |                 n                         n     |
        # /                                                 /
        #

        return (Rational(1, n) * sin(x) * cos(x)**(n - 1) +
                Rational(n - 1, n) * _cos_pow_integrate(n - 2, x))

    if n < 0:
        if n == -1:
            # Recursion break
            return trigintegrate(1 / cos(x), x)

        #  n < 0
        #   /                                                 /
        #  |                                                 |
        #  |    n            -1              n+1     n + 2   |     n+2
        #  | cos (x) dx = _______ sin (x) cos (x) + _______  |  cos (x) dx
        #  |                                                 |
        #  |               n + 1                     n + 1   |
        # /                                                 /
        #

        return (Rational(-1, n + 1) * sin(x) * cos(x)**(n + 1) +
                Rational(n + 2, n + 1) * _cos_pow_integrate(n + 2, x))
    else:
        # n == 0
        # Recursion Break.
        return x
Beispiel #23
0
def test_Rational():
    assert mcode(Rational(3, 7)) == "3/7"
    assert mcode(Rational(18, 9)) == "2"
    assert mcode(Rational(3, -7)) == "-3/7"
    assert mcode(Rational(-3, -7)) == "3/7"
    assert mcode(x + Rational(3, 7)) == "x + 3/7"
    assert mcode(Rational(3, 7)*x) == "(3/7)*x"
Beispiel #24
0
def test_pos_rational():
    r = Rational(3, 4)
    assert r.is_commutative is True
    assert r.is_integer is False
    assert r.is_rational is True
    assert r.is_algebraic is True
    assert r.is_transcendental is False
    assert r.is_extended_real is True
    assert r.is_complex is True
    assert r.is_noninteger is True
    assert r.is_irrational is False
    assert r.is_imaginary is False
    assert r.is_positive is True
    assert r.is_negative is False
    assert r.is_nonpositive is False
    assert r.is_nonnegative is True
    assert r.is_even is False
    assert r.is_odd is False
    assert r.is_finite is True
    assert r.is_infinite is False
    assert r.is_comparable is True
    assert r.is_prime is False
    assert r.is_composite is False

    r = Rational(1, 4)
    assert r.is_nonpositive is False
    assert r.is_positive is True
    assert r.is_negative is False
    assert r.is_nonnegative is True
    r = Rational(5, 4)
    assert r.is_negative is False
    assert r.is_positive is True
    assert r.is_nonpositive is False
    assert r.is_nonnegative is True
    r = Rational(5, 3)
    assert r.is_nonnegative is True
    assert r.is_positive is True
    assert r.is_negative is False
    assert r.is_nonpositive is False
Beispiel #25
0
def test_MatPow():
    A = MatrixSymbol('A', n, n)

    AA = MatPow(A, 2)
    assert AA.exp == 2
    assert AA.base == A
    assert (A**n).exp == n

    assert A**0 == Identity(n)
    assert A**1 == A
    assert A**2 == AA
    assert A**-1 == Inverse(A)
    assert A**Rational(1, 2) == sqrt(A)
    pytest.raises(ShapeError, lambda: MatrixSymbol('B', 3, 2)**2)
Beispiel #26
0
def test_int_to_Integer():
    # XXX: Warning, don't test with == here.  0.5 == Rational(1, 2) is True!
    app = init_ipython_session(auto_int_to_Integer=True)
    app.run_cell("from diofant import Integer")
    app.run_cell("a = 1")
    assert isinstance(app.user_ns['a'], Integer)

    app.run_cell("a = 1/2")
    assert isinstance(app.user_ns['a'], Rational)
    app.run_cell("a = 1")
    assert isinstance(app.user_ns['a'], Integer)
    app.run_cell("a = int(1)")
    assert isinstance(app.user_ns['a'], int)
    app.run_cell("a = (1/\n2)")
    assert app.user_ns['a'] == Rational(1, 2)
Beispiel #27
0
    def random_point(self, seed=None):
        """ Returns a random point on the Plane.

        Returns
        =======

        Point3D

        """
        import random
        if seed is not None:
            rng = random.Random(seed)
        else:
            rng = random
        t = Dummy('t')
        return self.arbitrary_point(t).subs(t, Rational(rng.random()))
Beispiel #28
0
def test_rational():
    a = Rational(1, 5)

    r = sqrt(5)/5
    assert sqrt(a) == r
    assert 2*sqrt(a) == 2*r

    r = a*a**Rational(1, 2)
    assert a**Rational(3, 2) == r
    assert 2*a**Rational(3, 2) == 2*r

    r = a**5*a**Rational(2, 3)
    assert a**Rational(17, 3) == r
    assert 2 * a**Rational(17, 3) == 2*r
Beispiel #29
0
    def eval(cls, n, sym=None):
        if n.is_Number:
            if n.is_Integer and n.is_nonnegative:
                if n is S.Zero:
                    return S.One
                elif n is S.One:
                    if sym is None:
                        return -S.Half
                    else:
                        return sym - S.Half
                # Bernoulli numbers
                elif sym is None:
                    if n.is_odd:
                        return S.Zero
                    n = int(n)
                    # Use mpmath for enormous Bernoulli numbers
                    if n > 500:
                        p, q = bernfrac(n)
                        return Rational(int(p), int(q))
                    case = n % 6
                    highest_cached = cls._highest[case]
                    if n <= highest_cached:
                        return cls._cache[n]
                    # To avoid excessive recursion when, say, bernoulli(1000) is
                    # requested, calculate and cache the entire sequence ... B_988,
                    # B_994, B_1000 in increasing order
                    for i in range(highest_cached + 6, n + 6, 6):
                        b = cls._calc_bernoulli(i)
                        cls._cache[i] = b
                        cls._highest[case] = i
                    return b
                # Bernoulli polynomials
                else:
                    n, result = int(n), []
                    for k in range(n + 1):
                        result.append(binomial(n, k) * cls(k) * sym**(n - k))
                    return Add(*result)
            else:
                raise ValueError("Bernoulli numbers are defined only"
                                 " for nonnegative integer indices.")

        if sym is None:
            if n.is_odd and (n - 1).is_positive:
                return S.Zero
Beispiel #30
0
def test_trigintegrate_odd():
    assert trigintegrate(Rational(1), x) == x
    assert trigintegrate(x, x) is None
    assert trigintegrate(x**2, x) is None

    assert trigintegrate(sin(x), x) == -cos(x)
    assert trigintegrate(cos(x), x) == sin(x)

    assert trigintegrate(sin(3 * x), x) == -cos(3 * x) / 3
    assert trigintegrate(cos(3 * x), x) == sin(3 * x) / 3

    y = Symbol('y')
    assert trigintegrate(sin(y*x), x) == \
        Piecewise((0, Eq(y, 0)), (-cos(y*x)/y, True))
    assert trigintegrate(cos(y*x), x) == \
        Piecewise((x, Eq(y, 0)), (sin(y*x)/y, True))
    assert trigintegrate(sin(y*x)**2, x) == \
        Piecewise((0, Eq(y, 0)), ((x*y/2 - sin(x*y)*cos(x*y)/2)/y, True))
    assert trigintegrate(sin(y*x)*cos(y*x), x) == \
        Piecewise((0, Eq(y, 0)), (sin(x*y)**2/(2*y), True))
    assert trigintegrate(cos(y*x)**2, x) == \
        Piecewise((x, Eq(y, 0)), ((x*y/2 + sin(x*y)*cos(x*y)/2)/y, True))

    y = Symbol('y', positive=True)
    # TODO: remove conds='none' below. For this to work we would have to rule
    #       out (e.g. by trying solve) the condition y = 0, incompatible with
    #       y.is_positive being True.
    assert trigintegrate(sin(y * x), x, conds='none') == -cos(y * x) / y
    assert trigintegrate(cos(y * x), x, conds='none') == sin(y * x) / y

    assert trigintegrate(sin(x) * cos(x), x) == sin(x)**2 / 2
    assert trigintegrate(sin(x) * cos(x)**2, x) == -cos(x)**3 / 3
    assert trigintegrate(sin(x)**2 * cos(x), x) == sin(x)**3 / 3

    # check if it selects right function to substitute,
    # so the result is kept simple
    assert trigintegrate(sin(x)**7 * cos(x), x) == sin(x)**8 / 8
    assert trigintegrate(sin(x) * cos(x)**7, x) == -cos(x)**8 / 8

    assert trigintegrate(sin(x)**7 * cos(x)**3, x) == \
        -sin(x)**10/10 + sin(x)**8/8
    assert trigintegrate(sin(x)**3 * cos(x)**7, x) == \
        cos(x)**10/10 - cos(x)**8/8