Example #1
0
def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y):
    A_dict = C.A_dict
    A_dict_inv = C.A_dict_inv
    if C.is_complete():
        # if C is complete then it only needs to test
        # whether the relators in R2 are satisfied
        for w, alpha in product(R2, C.omega):
            if not C.scan_check(alpha, w):
                return
        # relators in R2 are satisfied, append the table to list
        S.append(C)
    else:
        # find the first undefined entry in Coset Table
        for alpha, x in product(range(len(C.table)), C.A):
            if C.table[alpha][A_dict[x]] is None:
                # this is "x" in pseudo-code (using "y" makes it clear)
                undefined_coset, undefined_gen = alpha, x
                break
        # for filling up the undefine entry we try all possible values
        # of β ∈ Ω or β = n where β^(undefined_gen^-1) is undefined
        reach = C.omega + [C.n]
        for beta in reach:
            if beta < N:
                if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None:
                    try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \
                            undefined_gen, beta, Y)
Example #2
0
def test_function_subs():
    f = Function("f")
    S = Sum(x*f(y),(x,0,oo),(y,0,oo))
    assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
    assert S.subs(f(x),x) == S
    raises(ValueError, lambda: S.subs(f(y),x+y) )
    S = Sum(x*log(y),(x,0,oo),(y,0,oo))
    assert S.subs(log(y),y) == S
    S = Sum(x*f(y),(x,0,oo),(y,0,oo))
    assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
Example #3
0
def test_exceptions():
    S = Sum(x, (x, a, b))
    raises(ValueError, lambda: S.change_index(x, x**2, y))
    S = Sum(x, (x, a, b), (x, 1, 4))
    raises(ValueError, lambda: S.index(x))
    S = Sum(x, (x, a, b), (y, 1, 4))
    raises(ValueError, lambda: S.reorder([x]))
    S = Sum(x, (x, y, b), (y, 1, 4))
    raises(ReorderError, lambda: S.reorder_limit(0, 1))
    S = Sum(x*y, (x, a, b), (y, 1, 4))
    raises(NotImplementedError, lambda: S.is_convergent())
Example #4
0
def test_permutation_methods():
    from sympy.combinatorics.fp_groups import FpSubgroup
    F, x, y = free_group("x, y")
    # DihedralGroup(8)
    G = FpGroup(F, [x**2, y**8, x*y*x**-1*y])
    T = G._to_perm_group()[1]
    assert T.is_isomorphism()
    assert G.center() == [y**4]

    # DiheadralGroup(4)
    G = FpGroup(F, [x**2, y**4, x*y*x**-1*y])
    S = FpSubgroup(G, G.normal_closure([x]))
    assert x in S
    assert y**-1*x*y in S

    # Z_5xZ_4
    G = FpGroup(F, [x*y*x**-1*y**-1, y**5, x**4])
    assert G.is_abelian
    assert G.is_solvable

    # AlternatingGroup(5)
    G = FpGroup(F, [x**3, y**2, (x*y)**5])
    assert not G.is_solvable

    # AlternatingGroup(4)
    G = FpGroup(F, [x**3, y**2, (x*y)**3])
    assert len(G.derived_series()) == 3
    S = FpSubgroup(G, G.derived_subgroup())
    assert S.order() == 4
def test_Sum_doit():
    assert Sum(n * Integral(a ** 2), (n, 0, 2)).doit() == a ** 3
    assert Sum(n * Integral(a ** 2), (n, 0, 2)).doit(deep=False) == 3 * Integral(a ** 2)
    assert summation(n * Integral(a ** 2), (n, 0, 2)) == 3 * Integral(a ** 2)

    # test nested sum evaluation
    S = Sum(Sum(Sum(2, (z, 1, n + 1)), (y, x + 1, n)), (x, 1, n))
    assert 0 == (S.doit() - n * (n + 1) * (n - 1)).factor()
Example #6
0
    def test_PQ_f7(self):
        S = QQ['t']
        t = S.gen()
        r0,r1,r2 = (t**3 - t**2 + 1).roots(QQbar, multiplicities=False)

        series = self.get_PQ(self.f7)
        x,y = self.f7.parent().gens()
        x = QQbar['x,y'](x)
        y = QQbar['x,y'](y)
        self.assertItemsEqual(
            series,
            [(x, y + r0),
             (x, y + r1),
             (x, y + r2)])
Example #7
0
    def update(f, sugar, P):
        """Add f with sugar ``sugar`` to S, update P."""
        if not f:
            return P
        k = len(S)
        S.append(f)
        Sugars.append(sugar)

        LMf = sdm_LM(f)

        def removethis(pair):
            i, j, s, t = pair
            if LMf[0] != t[0]:
                return False
            tik = sdm_monomial_lcm(LMf, sdm_LM(S[i]))
            tjk = sdm_monomial_lcm(LMf, sdm_LM(S[j]))
            return tik != t and tjk != t and sdm_monomial_divides(tik, t) and \
                sdm_monomial_divides(tjk, t)
        # apply the chain criterion
        P = [p for p in P if not removethis(p)]

        # new-pair set
        N = [(i, k, Ssugar(i, k), sdm_monomial_lcm(LMf, sdm_LM(S[i])))
             for i in range(k) if LMf[0] == sdm_LM(S[i])[0]]
        # TODO apply the product criterion?
        N.sort(key=ourkey)
        remove = set()
        for i, p in enumerate(N):
            for j in range(i + 1, len(N)):
                if sdm_monomial_divides(p[3], N[j][3]):
                    remove.add(j)

        # TODO mergesort?
        P.extend(reversed([p for i, p in enumerate(N) if not i in remove]))
        P.sort(key=ourkey, reverse=True)
        # NOTE reverse-sort, because we want to pop from the end
        return P
Example #8
0
    def test_PQ_f27(self):
        S = QQ['t']
        t = S.gen()
        sqrt2 = (t**2 - 2).roots(QQbar, multiplicities=False)[0]

        series = self.get_PQ(self.f27)
        x,y = self.f27.parent().gens()
        x = QQbar['x,y'](x)
        y = QQbar['x,y'](y)
        self.assertItemsEqual(
            series,
            [(x, x*(y + sqrt2)),
             (x, x*(y - sqrt2)),
             (x**2/2, x**3*(y + 1)/2),
             (x**3/2, x*(y + 1))])
Example #9
0
def test_hyperexpand_parametric():
    assert hyperexpand(hyper([a, S(1)/2 + a], [S(1)/2], z)) \
        == (1 + sqrt(z))**(-2*a)/2 + (1 - sqrt(z))**(-2*a)/2
    assert hyperexpand(hyper([a, -S(1)/2 + a], [2*a], z)) \
        == 2**(2*a - 1)*(sqrt(-z + 1) + 1)**(-2*a + 1)
Example #10
0
def test_geometric_sums():
    assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
    assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
    assert summation(Rational(1, 2)**n, (n, 1, oo)) == 1
    assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
    assert summation(2**n, (n, 1, oo)) == oo
    assert summation(2**(-n), (n, 1, oo)) == 1
    assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
    assert summation(2**(-4 * n + 3), (n, 1, oo)) == Rational(8, 15)
    assert summation(2**(n + 1), (n, 1, b)).expand() == 4 * (2**b - 1)

    # issue 6664:
    assert summation(x**n, (n, 0, oo)) == \
        Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))

    assert summation(-2**n, (n, 0, oo)) == -oo
    assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))

    # issue 6802:
    assert summation((-1)**(2 * x + 2), (x, 0, n)) == n + 1
    assert summation((-2)**(2 * x + 2),
                     (x, 0, n)) == 4 * 4**(n + 1) / S(3) - S(4) / 3
    assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1) / S(2) + S(1) / 2
    assert summation(y**x, (x, a, b)) == \
        Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
    assert summation((-2)**(y*x + 2), (x, 0, n)) == \
        4*Piecewise((n + 1, Eq((-2)**y, 1)),
                    ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))

    # issue 8251:
    assert summation((1 / (n + 1)**2) * n**2, (n, 0, oo)) == oo

    #issue 9908:
    assert Sum(1 / (n**3 - 1),
               (n, -oo, -2)).doit() == summation(1 / (n**3 - 1), (n, -oo, -2))

    #issue 11642:
    result = Sum(0.5**n, (n, 1, oo)).doit()
    assert result == 1
    assert result.is_Float

    result = Sum(0.25**n, (n, 1, oo)).doit()
    assert result == S(1) / 3
    assert result.is_Float

    result = Sum(0.99999**n, (n, 1, oo)).doit()
    assert result == 99999
    assert result.is_Float

    result = Sum(Rational(1, 2)**n, (n, 1, oo)).doit()
    assert result == 1
    assert not result.is_Float

    result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
    assert result == S(3) / 2
    assert not result.is_Float

    assert Sum(1.0**n, (n, 1, oo)).doit() == oo
    assert Sum(2.43**n, (n, 1, oo)).doit() == oo

    # Issue 13979:
    i, k, q = symbols('i k q', integer=True)
    result = summation(
        exp(-2 * I * pi * k * i / n) * exp(2 * I * pi * q * i / n) / n,
        (i, 0, n - 1))
    assert result.simplify() == Piecewise(
        (1, Eq(exp(2 * I * pi * (-k + q) / n), 1)), (0, True))
Example #11
0
def test_inverse_mellin_transform():
    from sympy import (sin, simplify, expand_func, powsimp, Max, Min, expand,
                       powdenest, powsimp, exp_polar, combsimp, cos, cot)
    IMT = inverse_mellin_transform

    assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
    assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1 / x)
    assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
        (x**2 + 1)*Heaviside(1 - x)/(4*x)

    # test passing "None"
    assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
    assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)

    # test expansion of sums
    assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1) * exp(-x) / x

    # test factorisation of polys
    r = symbols('r', real=True)
    assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
              ).subs(x, r).rewrite(sin).simplify() \
        == sin(r)*Heaviside(1 - exp(-r))

    # test multiplicative substitution
    _a, _b = symbols('a b', positive=True)
    assert IMT(_b**(-s / _a) * factorial(s / _a) / s, s, x,
               (0, oo)) == exp(-_b * x**_a)
    assert IMT(factorial(_a / _b + s / _b) / (_a + s), s, x,
               (-_a, oo)) == x**_a * exp(-x**_b)

    def simp_pows(expr):
        return simplify(powsimp(expand_mul(expr, deep=False),
                                force=True)).replace(exp_polar, exp)

    # Now test the inverses of all direct transforms tested above

    # Section 8.4.2
    assert IMT(-1 / (nu + s), s, x, (-oo, None)) == x**nu * Heaviside(x - 1)
    assert IMT(1 / (nu + s), s, x, (None, oo)) == x**nu * Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
        == (1 - x)**(beta - 1)*Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
                         s, x, (-oo, None))) \
        == (x - 1)**(beta - 1)*Heaviside(x - 1)
    assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
        == (1/(x + 1))**rho
    assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
                         *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
                         s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
        == (x**c - d**c)/(x - d)

    assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
                        *gamma(-c/2 - s)/gamma(1 - c - s),
                        s, x, (0, -re(c)/2))) == \
        (1 + sqrt(x + 1))**c
    assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
                        /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
        b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) +
        b**2 + x)/(b**2 + x)
    assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
                        / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
        b**c*(sqrt(1 + x/b**2) + 1)**c

    # Section 8.4.5
    assert IMT(24 / s**5, s, x, (0, oo)) == log(x)**4 * Heaviside(1 - x)
    assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
        log(x)**3*Heaviside(x - 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (-1, 0)) == log(x + 1)
    assert IMT(pi / (s * sin(pi * s / 2)), s, x, (-2, 0)) == log(x**2 + 1)
    assert IMT(pi / (s * sin(2 * pi * s)), s, x,
               (-S(1) / 2, 0)) == log(sqrt(x) + 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (0, 1)) == log(1 + 1 / x)

    # TODO
    def mysimp(expr):
        from sympy import expand, logcombine, powsimp
        return expand(powsimp(logcombine(expr, force=True),
                              force=True,
                              deep=True),
                      force=True).replace(exp_polar, exp)

    assert mysimp(mysimp(IMT(pi / (s * tan(pi * s)), s, x, (-1, 0)))) in [
        log(1 - x) * Heaviside(1 - x) + log(x - 1) * Heaviside(x - 1),
        log(x) * Heaviside(x - 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1)
    ]
    # test passing cot
    assert mysimp(IMT(pi * cot(pi * s) / s, s, x, (0, 1))) in [
        log(1 / x - 1) * Heaviside(1 - x) + log(1 - 1 / x) * Heaviside(x - 1),
        -log(x) * Heaviside(-x + 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1),
    ]

    # 8.4.14
    assert IMT(-gamma(s + S(1)/2)/(sqrt(pi)*s), s, x, (-S(1)/2, 0)) == \
        erf(sqrt(x))

    # 8.4.19
    assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, S(3)/4))) \
        == besselj(a, 2*sqrt(x))
    assert simplify(IMT(2**a*gamma(S(1)/2 - 2*s)*gamma(s + (a + 1)/2)
                      / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-(re(a) + 1)/2, S(1)/4))) == \
        sin(sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S(1)/2 - 2*s)
                      / (gamma(S(1)/2 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-re(a)/2, S(1)/4))) == \
        cos(sqrt(x))*besselj(a, sqrt(x))
    # TODO this comes out as an amazing mess, but simplifies nicely
    assert simplify(IMT(gamma(a + s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
                      s, x, (-re(a), S(1)/2))) == \
        besselj(a, sqrt(x))**2
    assert simplify(IMT(gamma(s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
                      s, x, (0, S(1)/2))) == \
        besselj(-a, sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
                      / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
                         *gamma(a/2 + b/2 - s + 1)),
                      s, x, (-(re(a) + re(b))/2, S(1)/2))) == \
        besselj(a, sqrt(x))*besselj(b, sqrt(x))

    # Section 8.4.20
    # TODO this can be further simplified!
    assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
                    gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
                    (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
                    s, x,
                    (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S(1)/2))) == \
                    besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
                    besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
    # TODO more

    # for coverage

    assert IMT(pi / cos(pi * s), s, x, (0, S(1) / 2)) == sqrt(x) / (x + 1)
Example #12
0
from sage.all import SR
from sage.calculus.functional import taylor
from sage.calculus.var import var
from sage.rings.arith import xgcd
from sage.rings.laurent_series_ring import LaurentSeriesRing
from sage.rings.rational_field import QQ
from sage.rings.qqbar import QQbar
from sage.rings.infinity import infinity
from sympy import Poly, Point, Segment, Polygon, RootOf, sqrt, S

# every example will be over QQ[x,y]. consider putting in setup?
R = QQ['x,y']
S = QQ['t']
x,y = R.gens()
t = S.gens()

class TestNewtonPolygon(unittest.TestCase):

    def test_segment(self):
        H = y + x
        self.assertEqual(newton_polygon(H),
                         [[(0,1),(1,0)]])

        H = y**2 + x**2
        self.assertEqual(newton_polygon(H),
                         [[(0,2),(2,0)]])

    def test_general_segment(self):
        H = y**2 + x**4
        self.assertEqual(newton_polygon(H),
Example #13
0
def test_cosine_transform():
    from sympy import Si, Ci

    t = symbols("t")
    w = symbols("w")
    a = symbols("a")
    f = Function("f")

    # Test unevaluated form
    assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w)
    assert inverse_cosine_transform(
        f(w), w, t) == InverseCosineTransform(f(w), w, t)

    assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
    assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t)

    assert cosine_transform(1/(
        a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a)

    assert cosine_transform(t**(
        -a), t, w) == 2**(-a + S(1)/2)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2)
    assert inverse_cosine_transform(2**(-a + S(
        1)/2)*w**(a - 1)*gamma(-a/2 + S(1)/2)/gamma(a/2), w, t) == t**(-a)

    assert cosine_transform(
        exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2))
    assert inverse_cosine_transform(
        sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)

    assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt(
        t)), t, w) == a*exp(-a**2/(2*w))/(2*w**(S(3)/2))

    assert cosine_transform(1/(a + t), t, w) == sqrt(2)*(
        (-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi)
    assert inverse_cosine_transform(sqrt(2)*meijerg(((S(1)/2, 0), ()), (
        (S(1)/2, 0, 0), (S(1)/2,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t)

    assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg(
        ((S(1)/2,), ()), ((0, 0), (S(1)/2,)), a**2*w**2/4)/(2*sqrt(pi))
    assert inverse_cosine_transform(sqrt(2)*meijerg(((S(1)/2,), ()), ((0, 0), (S(1)/2,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1))
Example #14
0
def test_issue_5164():
    assert limit(x**0.5, x, oo) == oo**0.5 is oo
    assert limit(x**0.5, x, 16) == S(16)**0.5
    assert limit(x**0.5, x, 0) == 0
    assert limit(x**(-0.5), x, oo) == 0
    assert limit(x**(-0.5), x, 4) == S(4)**(-0.5)
Example #15
0
def test_roach_fail():
    assert can_do([
        -S(3) / 2,
    ], [-S(1) / 2, S(1) / 2])  # shine-integral
    assert can_do([-S(3) / 2, -S(1) / 2], [2])  # elliptic integrals
    assert can_do([-S(1) / 2, 1], [S(1) / 4, S(1) / 2, S(3) / 4])  # PFDD
    assert can_do([S(3) / 2], [S(5) / 2, 5])  # polylog
    assert can_do([-S(1) / 2, S(1) / 2, 1],
                  [S(3) / 2, S(5) / 2])  # polylog, pfdd
    assert can_do([1, 2, 3], [S(1) / 2, 4])  # XXX ?
    assert can_do([S(1) / 2], [-S(1) / 3, -S(1) / 2, -S(2) / 3])  # PFDD ?
Example #16
0
def test_prudnikov_fail_3F2():
    assert can_do([a, a + S(1) / 3, a + S(2) / 3], [S(1) / 3, S(2) / 3])
    assert can_do([a, a + S(1) / 3, a + S(2) / 3], [S(2) / 3, S(4) / 3])
    assert can_do([a, a + S(1) / 3, a + S(2) / 3], [S(4) / 3, S(5) / 3])

    # page 421
    assert can_do([a, a + S(1) / 3, a + S(2) / 3],
                  [3 * a / 2, (3 * a + 1) / 2])

    # pages 422 ...
    assert can_do([-S.Half, S.Half, S.Half], [1, 1])  # elliptic integrals
    assert can_do([-S.Half, S.Half, 1], [S(3) / 2, S(3) / 2])
    # TODO LOTS more

    # PFDD
    assert can_do([S(1) / 8, S(3) / 8, 1], [S(9) / 8, S(11) / 8])
    assert can_do([S(1) / 8, S(5) / 8, 1], [S(9) / 8, S(13) / 8])
    assert can_do([S(1) / 8, S(7) / 8, 1], [S(9) / 8, S(15) / 8])
    assert can_do([S(1) / 6, S(1) / 3, 1], [S(7) / 6, S(4) / 3])
    assert can_do([S(1) / 6, S(2) / 3, 1], [S(7) / 6, S(5) / 3])
    assert can_do([S(1) / 6, S(2) / 3, 1], [S(5) / 3, S(13) / 6])
    assert can_do([S.Half, 1, 1], [S(1) / 4, S(3) / 4])
Example #17
0
def test_prudnikov_11():
    # 7.15
    assert can_do([a, a + S.Half], [2 * a, b, 2 * a - b])
    assert can_do([a, a + S.Half], [S(3) / 2, 2 * a, 2 * a - S(1) / 2])

    assert can_do([S(1) / 4, S(3) / 4], [S(1) / 2, S(1) / 2, 1])
    assert can_do([S(5) / 4, S(3) / 4], [S(3) / 2, S(1) / 2, 2])
    assert can_do([S(5) / 4, S(3) / 4], [S(3) / 2, S(3) / 2, 1])
    assert can_do([S(5) / 4, S(7) / 4], [S(3) / 2, S(5) / 2, 2])
Example #18
0
def test_prudnikov_12():
    # 7.16
    assert can_do([], [a, a + S.Half, 2 * a],
                  False)  # branches only agree for some z!
    assert can_do([], [a, a + S.Half, 2 * a + 1], False)  # dito
    assert can_do([], [S.Half, a, a + S.Half])
    assert can_do([], [S(3) / 2, a, a + S.Half])

    assert can_do([], [S(1) / 4, S(1) / 2, S(3) / 4])
    assert can_do([], [S(1) / 2, S(1) / 2, 1])
    assert can_do([], [S(1) / 2, S(3) / 2, 1])
    assert can_do([], [S(3) / 4, S(3) / 2, S(5) / 4])
    assert can_do([], [1, 1, S(3) / 2])
    assert can_do([], [1, 2, S(3) / 2])
    assert can_do([], [1, S(3) / 2, S(3) / 2])
    assert can_do([], [S(5) / 4, S(3) / 2, S(7) / 4])
    assert can_do([], [2, S(3) / 2, S(3) / 2])
Example #19
0
def test_prudnikov_9():
    # 7.13.1 [we have a general formula ... so this is a bit pointless]
    for i in range(9):
        assert can_do([], [(S(i) + 1) / 2])
    for i in range(5):
        assert can_do([], [-(2 * S(i) + 1) / 2])
Example #20
0
def randrat():
    """ Steer clear of integers. """
    return S(randrange(25) + 10) / 50
Example #21
0
def test_shifted_sum():
    from sympy import simplify
    assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \
           == -S(1)/2 + cos(2*z)/2 + z*sin(2*z) - z**2*cos(2*z)
Example #22
0
def test_to_mpmath():
    assert sqrt(3)._to_mpmath(20)._mpf_ == (0, long(908093), -19, 20)
    assert S(3.2)._to_mpmath(20)._mpf_ == (0, long(838861), -18, 20)
Example #23
0
def test_prudnikov_fail_other():
    # 7.11.2
    assert can_do([a], [a + 1])  # lowergamma ... why??

    # 7.12.1
    assert can_do([1, a], [b, 1 - 2 * a + b])  # ???

    # 7.14.2
    assert can_do([-S(1) / 2], [S(1) / 2, S(1) / 2])  # shine-integral shi
    assert can_do([-S(1) / 2], [S(1) / 2, 1])  # poly-log
    assert can_do([1], [S(1) / 2, S(1) / 2])  # poly-log
    assert can_do([S(1) / 4], [S(1) / 2, S(5) / 4])  # PFDD
    assert can_do([S(3) / 4], [S(3) / 2, S(7) / 4])  # PFDD
    assert can_do([1], [S(1) / 4, S(3) / 4])  # PFDD
    assert can_do([1], [S(3) / 4, S(5) / 4])  # PFDD
    assert can_do([1], [S(5) / 4, S(7) / 4])  # PFDD
    # TODO LOTS more

    # 7.15.2
    assert can_do([S(1) / 2, 1], [S(3) / 4, S(5) / 4, S(3) / 2])  # PFDD
    assert can_do([S(1) / 2, 1], [S(7) / 4, S(5) / 4, S(3) / 2])  # PFDD
    assert can_do([1, 1], [S(3) / 2, 2, 2])  # cosh-integral chi

    # 7.16.1
    assert can_do([], [S(1) / 3, S(2 / 3)])  # PFDD
    assert can_do([], [S(2) / 3, S(4 / 3)])  # PFDD
    assert can_do([], [S(5) / 3, S(4 / 3)])  # PFDD

    # XXX this does not *evaluate* right??
    assert can_do([], [a, a + S.Half, 2 * a - 1])
Example #24
0
def test_plane():
    x, y, z, u, v = symbols("x y z u v", real=True)
    p1 = Point3D(0, 0, 0)
    p2 = Point3D(1, 1, 1)
    p3 = Point3D(1, 2, 3)
    pl3 = Plane(p1, p2, p3)
    pl4 = Plane(p1, normal_vector=(1, 1, 1))
    pl4b = Plane(p1, p2)
    pl5 = Plane(p3, normal_vector=(1, 2, 3))
    pl6 = Plane(Point3D(2, 3, 7), normal_vector=(2, 2, 2))
    pl7 = Plane(Point3D(1, -5, -6), normal_vector=(1, -2, 1))
    pl8 = Plane(p1, normal_vector=(0, 0, 1))
    pl9 = Plane(p1, normal_vector=(0, 12, 0))
    pl10 = Plane(p1, normal_vector=(-2, 0, 0))
    pl11 = Plane(p2, normal_vector=(0, 0, 1))
    l1 = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
    l2 = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
    l3 = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))

    assert Plane(p1, p2, p3) != Plane(p1, p3, p2)
    assert Plane(p1, p2, p3).is_coplanar(Plane(p1, p3, p2))
    assert pl3 == Plane(Point3D(0, 0, 0), normal_vector=(1, -2, 1))
    assert pl3 != pl4
    assert pl4 == pl4b
    assert pl5 == Plane(Point3D(1, 2, 3), normal_vector=(1, 2, 3))

    assert pl5.equation(x, y, z) == x + 2 * y + 3 * z - 14
    assert pl3.equation(x, y, z) == x - 2 * y + z

    assert pl3.p1 == p1
    assert pl4.p1 == p1
    assert pl5.p1 == p3

    assert pl4.normal_vector == (1, 1, 1)
    assert pl5.normal_vector == (1, 2, 3)

    assert p1 in pl3
    assert p1 in pl4
    assert p3 in pl5

    assert pl3.projection(Point(0, 0)) == p1
    p = pl3.projection(Point3D(1, 1, 0))
    assert p == Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))
    assert p in pl3

    l = pl3.projection_line(Line(Point(0, 0), Point(1, 1)))
    assert l == Line3D(
        Point3D(0, 0, 0), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))
    )
    assert l in pl3
    # get a segment that does not intersect the plane which is also
    # parallel to pl3's normal veector
    t = Dummy()
    r = pl3.random_point()
    a = pl3.perpendicular_line(r).arbitrary_point(t)
    s = Segment3D(a.subs(t, 1), a.subs(t, 2))
    assert s.p1 not in pl3 and s.p2 not in pl3
    assert pl3.projection_line(s).equals(r)
    assert pl3.projection_line(Segment(Point(1, 0), Point(1, 1))) == Segment3D(
        Point3D(Rational(5, 6), Rational(1, 3), Rational(-1, 6)),
        Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)),
    )
    assert pl6.projection_line(Ray(Point(1, 0), Point(1, 1))) == Ray3D(
        Point3D(Rational(14, 3), Rational(11, 3), Rational(11, 3)),
        Point3D(Rational(13, 3), Rational(13, 3), Rational(10, 3)),
    )
    assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r)

    assert pl3.is_parallel(pl6) is False
    assert pl4.is_parallel(pl6)
    assert pl6.is_parallel(l1) is False

    assert pl3.is_perpendicular(pl6)
    assert pl4.is_perpendicular(pl7)
    assert pl6.is_perpendicular(pl7)
    assert pl6.is_perpendicular(l1) is False

    assert pl6.distance(pl6.arbitrary_point(u, v)) == 0
    assert pl7.distance(pl7.arbitrary_point(u, v)) == 0
    assert pl6.distance(pl6.arbitrary_point(t)) == 0
    assert pl7.distance(pl7.arbitrary_point(t)) == 0
    assert pl6.p1.distance(pl6.arbitrary_point(t)).simplify() == 1
    assert pl7.p1.distance(pl7.arbitrary_point(t)).simplify() == 1
    assert pl3.arbitrary_point(t) == Point3D(
        -sqrt(30) * sin(t) / 30 + 2 * sqrt(5) * cos(t) / 5,
        sqrt(30) * sin(t) / 15 + sqrt(5) * cos(t) / 5,
        sqrt(30) * sin(t) / 6,
    )
    assert pl3.arbitrary_point(u, v) == Point3D(2 * u - v, u + 2 * v, 5 * v)

    assert pl7.distance(Point3D(1, 3, 5)) == 5 * sqrt(6) / 6
    assert pl6.distance(Point3D(0, 0, 0)) == 4 * sqrt(3)
    assert pl6.distance(pl6.p1) == 0
    assert pl7.distance(pl6) == 0
    assert pl7.distance(l1) == 0
    assert (
        pl6.distance(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4)))
        == pl6.distance(Point3D(1, 3, 4))
        == 4 * sqrt(3) / 3
    )
    assert (
        pl6.distance(Segment3D(Point3D(1, 3, 4), Point3D(0, 3, 7)))
        == pl6.distance(Point3D(0, 3, 7))
        == 2 * sqrt(3) / 3
    )
    assert pl6.distance(Segment3D(Point3D(0, 3, 7), Point3D(-1, 3, 10))) == 0
    assert pl6.distance(Segment3D(Point3D(-1, 3, 10), Point3D(-2, 3, 13))) == 0
    assert (
        pl6.distance(Segment3D(Point3D(-2, 3, 13), Point3D(-3, 3, 16)))
        == pl6.distance(Point3D(-2, 3, 13))
        == 2 * sqrt(3) / 3
    )
    assert pl6.distance(Plane(Point3D(5, 5, 5), normal_vector=(8, 8, 8))) == sqrt(3)
    assert (
        pl6.distance(Ray3D(Point3D(1, 3, 4), direction_ratio=[1, 0, -3]))
        == 4 * sqrt(3) / 3
    )
    assert pl6.distance(Ray3D(Point3D(2, 3, 1), direction_ratio=[-1, 0, 3])) == 0

    assert pl6.angle_between(pl3) == pi / 2
    assert pl6.angle_between(pl6) == 0
    assert pl6.angle_between(pl4) == 0
    assert pl7.angle_between(Line3D(Point3D(2, 3, 5), Point3D(2, 4, 6))) == -asin(
        sqrt(3) / 6
    )
    assert pl6.angle_between(Ray3D(Point3D(2, 4, 1), Point3D(6, 5, 3))) == asin(
        sqrt(7) / 3
    )
    assert pl7.angle_between(Segment3D(Point3D(5, 6, 1), Point3D(1, 2, 4))) == asin(
        7 * sqrt(246) / 246
    )

    assert are_coplanar(l1, l2, l3) is False
    assert are_coplanar(l1) is False
    assert are_coplanar(
        Point3D(2, 7, 2), Point3D(0, 0, 2), Point3D(1, 1, 2), Point3D(1, 2, 2)
    )
    assert are_coplanar(Plane(p1, p2, p3), Plane(p1, p3, p2))
    assert Plane.are_concurrent(pl3, pl4, pl5) is False
    assert Plane.are_concurrent(pl6) is False
    raises(ValueError, lambda: Plane.are_concurrent(Point3D(0, 0, 0)))
    raises(ValueError, lambda: Plane((1, 2, 3), normal_vector=(0, 0, 0)))

    assert pl3.parallel_plane(Point3D(1, 2, 5)) == Plane(
        Point3D(1, 2, 5), normal_vector=(1, -2, 1)
    )

    # perpendicular_plane
    p = Plane((0, 0, 0), (1, 0, 0))
    # default
    assert p.perpendicular_plane() == Plane(Point3D(0, 0, 0), (0, 1, 0))
    # 1 pt
    assert p.perpendicular_plane(Point3D(1, 0, 1)) == Plane(Point3D(1, 0, 1), (0, 1, 0))
    # pts as tuples
    assert p.perpendicular_plane((1, 0, 1), (1, 1, 1)) == Plane(
        Point3D(1, 0, 1), (0, 0, -1)
    )

    a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
    Z = (0, 0, 1)
    p = Plane(a, normal_vector=Z)
    # case 4
    assert p.perpendicular_plane(a, b) == Plane(a, (1, 0, 0))
    n = Point3D(*Z)
    # case 1
    assert p.perpendicular_plane(a, n) == Plane(a, (-1, 0, 0))
    # case 2
    assert Plane(a, normal_vector=b.args).perpendicular_plane(a, a + b) == Plane(
        Point3D(0, 0, 0), (1, 0, 0)
    )
    # case 1&3
    assert Plane(b, normal_vector=Z).perpendicular_plane(b, b + n) == Plane(
        Point3D(0, 1, 0), (-1, 0, 0)
    )
    # case 2&3
    assert Plane(b, normal_vector=b.args).perpendicular_plane(n, n + b) == Plane(
        Point3D(0, 0, 1), (1, 0, 0)
    )

    assert pl6.intersection(pl6) == [pl6]
    assert pl4.intersection(pl4.p1) == [pl4.p1]
    assert pl3.intersection(pl6) == [Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))]
    assert pl3.intersection(Line3D(Point3D(1, 2, 4), Point3D(4, 4, 2))) == [
        Point3D(2, Rational(8, 3), Rational(10, 3))
    ]
    assert pl3.intersection(Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))) == [
        Line3D(Point3D(-24, -12, 0), Point3D(-25, -13, -1))
    ]
    assert pl6.intersection(Ray3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [
        Point3D(-1, 3, 10)
    ]
    assert pl6.intersection(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == []
    assert pl7.intersection(Line(Point(2, 3), Point(4, 2))) == [
        Point3D(Rational(13, 2), Rational(3, 4), 0)
    ]
    r = Ray(Point(2, 3), Point(4, 2))
    assert Plane((1, 2, 0), normal_vector=(0, 0, 1)).intersection(r) == [
        Ray3D(Point(2, 3), Point(4, 2))
    ]
    assert pl9.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, 0))]
    assert pl10.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(0, 2, 1))]
    assert pl4.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
    assert pl11.intersection(pl8) == []
    assert pl9.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(12, 0, 1))]
    assert pl9.intersection(pl4) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, -12))]
    assert pl3.random_point() in pl3

    # test geometrical entity using equals
    assert pl4.intersection(pl4.p1)[0].equals(pl4.p1)
    assert pl3.intersection(pl6)[0].equals(Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6)))
    pl8 = Plane((1, 2, 0), normal_vector=(0, 0, 1))
    assert pl8.intersection(Line3D(p1, (1, 12, 0)))[0].equals(
        Line((0, 0, 0), (0.1, 1.2, 0))
    )
    assert pl8.intersection(Ray3D(p1, (1, 12, 0)))[0].equals(Ray((0, 0, 0), (1, 12, 0)))
    assert pl8.intersection(Segment3D(p1, (21, 1, 0)))[0].equals(
        Segment3D(p1, (21, 1, 0))
    )
    assert pl8.intersection(Plane(p1, normal_vector=(0, 0, 112)))[0].equals(pl8)
    assert pl8.intersection(Plane(p1, normal_vector=(0, 12, 0)))[0].equals(
        Line3D(p1, direction_ratio=(112 * pi, 0, 0))
    )
    assert pl8.intersection(Plane(p1, normal_vector=(11, 0, 1)))[0].equals(
        Line3D(p1, direction_ratio=(0, -11, 0))
    )
    assert pl8.intersection(Plane(p1, normal_vector=(1, 0, 11)))[0].equals(
        Line3D(p1, direction_ratio=(0, 11, 0))
    )
    assert pl8.intersection(Plane(p1, normal_vector=(-1, -1, -11)))[0].equals(
        Line3D(p1, direction_ratio=(1, -1, 0))
    )
    assert pl3.random_point() in pl3
    assert len(pl8.intersection(Ray3D(Point3D(0, 2, 3), Point3D(1, 0, 3)))) == 0
    # check if two plane are equals
    assert pl6.intersection(pl6)[0].equals(pl6)
    assert pl8.equals(Plane(p1, normal_vector=(0, 12, 0))) is False
    assert pl8.equals(pl8)
    assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12)))
    assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12 * sqrt(3))))

    # issue 8570
    l2 = Line3D(
        Point3D(
            Rational(50000004459633, 5000000000000),
            Rational(-891926590718643, 1000000000000000),
            Rational(231800966893633, 100000000000000),
        ),
        Point3D(
            Rational(50000004459633, 50000000000000),
            Rational(-222981647679771, 250000000000000),
            Rational(231800966893633, 100000000000000),
        ),
    )

    p2 = Plane(
        Point3D(
            Rational(402775636372767, 100000000000000),
            Rational(-97224357654973, 100000000000000),
            Rational(216793600814789, 100000000000000),
        ),
        (-S("9.00000087501922"), -S("4.81170658872543e-13"), S("0.0")),
    )

    assert str([i.n(2) for i in p2.intersection(l2)]) == "[Point3D(4.0, -0.89, 2.3)]"
Example #25
0
def test_nan_inequality_raise_errors():
    # See discussion in pull request #7776.  We test inequalities with
    # a set including examples of various classes.
    for q in (x, S(0), S(10), S(1) / 3, pi, S(1.3), oo, -oo, nan):
        assert_all_ineq_raise_TypeError(q, nan)
Example #26
0
def test_mellin_transform():
    from sympy import Max, Min
    MT = mellin_transform

    bpos = symbols('b', positive=True)

    # 8.4.2
    assert MT(x**nu*Heaviside(x - 1), x, s) == \
        (-1/(nu + s), (-oo, -re(nu)), True)
    assert MT(x**nu*Heaviside(1 - x), x, s) == \
        (1/(nu + s), (-re(nu), oo), True)

    assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \
        (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(-beta) < 0)
    assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \
        (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
            (-oo, -re(beta) + 1), re(-beta) < 0)

    assert MT((1 + x)**(-rho), x, s) == \
        (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)

    # TODO also the conditions should be simplified
    assert MT(abs(1 - x)**(-rho), x, s) == (
        2*sin(pi*rho/2)*gamma(1 - rho)*
        cos(pi*(rho/2 - s))*gamma(s)*gamma(rho-s)/pi,
        (0, re(rho)), And(re(rho) - 1 < 0, re(rho) < 1))
    mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x)
            + a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s)
    assert mt[1], mt[2] == ((0, -re(beta) + 1), True)

    assert MT((x**a - b**a)/(x - b), x, s)[0] == \
        pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s)))
    assert MT((x**a - bpos**a)/(x - bpos), x, s) == \
        (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))),
            (Max(-re(a), 0), Min(1 - re(a), 1)), True)

    expr = (sqrt(x + b**2) + b)**a
    assert MT(expr.subs(b, bpos), x, s) == \
        (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1),
         (0, -re(a)/2), True)

    expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
    assert MT(expr.subs(b, bpos), x, s) == \
        (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s)
                                         *gamma(1 - a - 2*s)/gamma(1 - a - s),
            (0, -re(a)/2 + S(1)/2), True)

    # 8.4.2
    assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True)
    assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True)

    # 8.4.5
    assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True)
    assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True)
    assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True)
    assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True)
    assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True)
    assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True)

    # TODO we cannot currently do these (needs summation of 3F2(-1))
    #      this also implies that they cannot be written as a single g-function
    #      (although this is possible)
    mt = MT(log(x)/(x + 1), x, s)
    assert mt[1:] == ((0, 1), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
    mt = MT(log(x)**2/(x + 1), x, s)
    assert mt[1:] == ((0, 1), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
    mt = MT(log(x)/(x + 1)**2, x, s)
    assert mt[1:] == ((0, 2), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)

    # 8.4.14
    assert MT(erf(sqrt(x)), x, s) == \
        (-gamma(s + S(1)/2)/(sqrt(pi)*s), (-S(1)/2, 0), True)
Example #27
0
def sdm_groebner(G, NF, O, K, extended=False):
    """
    Compute a minimal standard basis of ``G`` with respect to order ``O``.

    The algorithm uses a normal form ``NF``, for example ``sdm_nf_mora``.
    The ground field is assumed to be ``K``, and monomials ordered according
    to ``O``.

    Let `N` denote the submodule generated by elements of `G`. A standard
    basis for `N` is a subset `S` of `N`, such that `in(S) = in(N)`, where for
    any subset `X` of `F`, `in(X)` denotes the submodule generated by the
    initial forms of elements of `X`. [SCA, defn 2.3.2]

    A standard basis is called minimal if no subset of it is a standard basis.

    One may show that standard bases are always generating sets.

    Minimal standard bases are not unique. This algorithm computes a
    deterministic result, depending on the particular order of `G`.

    If ``extended=True``, also compute the transition matrix from the initial
    generators to the groebner basis. That is, return a list of coefficient
    vectors, expressing the elements of the groebner basis in terms of the
    elements of ``G``.

    This functions implements the "sugar" strategy, see

    Giovini et al: "One sugar cube, please" OR Selection strategies in
    Buchberger algorithm.
    """

    # The critical pair set.
    # A critical pair is stored as (i, j, s, t) where (i, j) defines the pair
    # (by indexing S), s is the sugar of the pair, and t is the lcm of their
    # leading monomials.
    P = []

    # The eventual standard basis.
    S = []
    Sugars = []

    def Ssugar(i, j):
        """Compute the sugar of the S-poly corresponding to (i, j)."""
        LMi = sdm_LM(S[i])
        LMj = sdm_LM(S[j])
        return max(Sugars[i] - sdm_monomial_deg(LMi),
                   Sugars[j] - sdm_monomial_deg(LMj)) \
            + sdm_monomial_deg(sdm_monomial_lcm(LMi, LMj))

    ourkey = lambda p: (p[2], O(p[3]), p[1])

    def update(f, sugar, P):
        """Add f with sugar ``sugar`` to S, update P."""
        if not f:
            return P
        k = len(S)
        S.append(f)
        Sugars.append(sugar)

        LMf = sdm_LM(f)

        def removethis(pair):
            i, j, s, t = pair
            if LMf[0] != t[0]:
                return False
            tik = sdm_monomial_lcm(LMf, sdm_LM(S[i]))
            tjk = sdm_monomial_lcm(LMf, sdm_LM(S[j]))
            return tik != t and tjk != t and sdm_monomial_divides(tik, t) and \
                sdm_monomial_divides(tjk, t)
        # apply the chain criterion
        P = [p for p in P if not removethis(p)]

        # new-pair set
        N = [(i, k, Ssugar(i, k), sdm_monomial_lcm(LMf, sdm_LM(S[i])))
             for i in range(k) if LMf[0] == sdm_LM(S[i])[0]]
        # TODO apply the product criterion?
        N.sort(key=ourkey)
        remove = set()
        for i, p in enumerate(N):
            for j in range(i + 1, len(N)):
                if sdm_monomial_divides(p[3], N[j][3]):
                    remove.add(j)

        # TODO mergesort?
        P.extend(reversed([p for i, p in enumerate(N) if not i in remove]))
        P.sort(key=ourkey, reverse=True)
        # NOTE reverse-sort, because we want to pop from the end
        return P

    # Figure out the number of generators in the ground ring.
    try:
        # NOTE: we look for the first non-zero vector, take its first monomial
        #       the number of generators in the ring is one less than the length
        #       (since the zeroth entry is for the module generators)
        numgens = len(next(x[0] for x in G if x)[0]) - 1
    except StopIteration:
        # No non-zero elements in G ...
        if extended:
            return [], []
        return []

    # This list will store expressions of the elements of S in terms of the
    # initial generators
    coefficients = []

    # First add all the elements of G to S
    for i, f in enumerate(G):
        P = update(f, sdm_deg(f), P)
        if extended and f:
            coefficients.append(sdm_from_dict({(i,) + (0,)*numgens: K(1)}, O))

    # Now carry out the buchberger algorithm.
    while P:
        i, j, s, t = P.pop()
        f, sf, g, sg = S[i], Sugars[i], S[j], Sugars[j]
        if extended:
            sp, coeff = sdm_spoly(f, g, O, K,
                                  phantom=(coefficients[i], coefficients[j]))
            h, hcoeff = NF(sp, S, O, K, phantom=(coeff, coefficients))
            if h:
                coefficients.append(hcoeff)
        else:
            h = NF(sdm_spoly(f, g, O, K), S, O, K)
        P = update(h, Ssugar(i, j), P)

    # Finally interreduce the standard basis.
    # (TODO again, better data structures)
    S = set((tuple(f), i) for i, f in enumerate(S))
    for (a, ai), (b, bi) in permutations(S, 2):
        A = sdm_LM(a)
        B = sdm_LM(b)
        if sdm_monomial_divides(A, B) and (b, bi) in S and (a, ai) in S:
            S.remove((b, bi))

    L = sorted(((list(f), i) for f, i in S), key=lambda p: O(sdm_LM(p[0])),
               reverse=True)
    res = [x[0] for x in L]
    if extended:
        return res, [coefficients[i] for _, i in L]
    return res
Example #28
0
def test_mellin_transform_bessel():
    from sympy import Max, Min, hyper, meijerg
    MT = mellin_transform

    # 8.4.19
    assert MT(besselj(a, 2*sqrt(x)), x, s) == \
        (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, S(3)/4), True)
    assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(-2*s + S(1)/2)*gamma(a/2 + s + S(1)/2)/(
        gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
        -re(a)/2 - S(1)/2, S(1)/4), True)
    assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(a/2 + s)*gamma(-2*s + S(1)/2)/(
        gamma(-a/2 - s + S(1)/2)*gamma(a - 2*s + 1)), (
        -re(a)/2, S(1)/4), True)
    assert MT(besselj(a, sqrt(x))**2, x, s) == \
        (gamma(a + s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
            (-re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
            (0, S(1)/2), True)
    # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
    #       I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
    assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (gamma(1 - s)*gamma(a + s - S(1)/2)
         / (sqrt(pi)*gamma(S(3)/2 - s)*gamma(a - s + S(1)/2)),
            (S(1)/2 - re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
        (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
         / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
            *gamma( 1 - s + (a + b)/2)),
            (-(re(a) + re(b))/2, S(1)/2), True)
    assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
        ((Max(re(a), -re(a)), S(1)/2), True)

    # Section 8.4.20
    assert MT(bessely(a, 2*sqrt(x)), x, s) == \
        (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
            (Max(-re(a)/2, re(a)/2), S(3)/4), True)
    assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*sin(pi*(a/2 - s))*gamma(S(1)/2 - 2*s)
         * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
         / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
            (Max(-(re(a) + 1)/2, (re(a) - 1)/2), S(1)/4), True)
    assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S(1)/2 - 2*s)
         / (sqrt(pi)*gamma(S(1)/2 - s - a/2)*gamma(S(1)/2 - s + a/2)),
            (Max(-re(a)/2, re(a)/2), S(1)/4), True)
    assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S(1)/2 - s)
         / (pi**S('3/2')*gamma(1 + a - s)),
            (Max(-re(a), 0), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
         * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
         / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
            (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S(1)/2), True)
    # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
    # are a mess (no matter what way you look at it ...)
    assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
             ((Max(-re(a), 0, re(a)), S(1)/2), True)

    # Section 8.4.22
    # TODO we can't do any of these (delicate cancellation)

    # Section 8.4.23
    assert MT(besselk(a, 2*sqrt(x)), x, s) == \
        (gamma(
         s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
    assert MT(
        besselj(a, 2 * sqrt(2 * sqrt(x))) * besselk(a, 2 * sqrt(2 * sqrt(x))),
        x, s) == (4**(-s) * gamma(2 * s) * gamma(a / 2 + s) /
                  (2 * gamma(a / 2 - s + 1)), (Max(0, -re(a) / 2), oo), True)
    # TODO bessely(a, x)*besselk(a, x) is a mess
    assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(
        a + s)*gamma(-s + S(1)/2)/(2*sqrt(pi)*gamma(a - s + 1)),
        (Max(-re(a), 0), S(1)/2), True)
    assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
        gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
        gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
        re(a)/2 - re(b)/2), S(1)/2), True)

    # TODO products of besselk are a mess

    mt = MT(exp(-x / 2) * besselk(a, x / 2), x, s)
    mt0 = combsimp((trigsimp(combsimp(mt[0].expand(func=True)))))
    assert mt0 == 2 * pi**(S(3) / 2) * cos(pi * s) * gamma(-s + S(1) / 2) / (
        (cos(2 * pi * a) - cos(2 * pi * s)) * gamma(-a - s + 1) *
        gamma(a - s + 1))
    assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
Example #29
0
def test_union():
    N = Normal('N', 3, 2)
    assert simplify(P(N**2 - N > 2)) == \
        -erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + S(3)/2
    assert simplify(P(N**2 - 4 > 0)) == \
        -erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + S(3)/2
Example #30
0
 def setup(self):
     super().setup()
     speed = min(150, 25 * self.level)
     self.fy += S('%d * t' % speed)
Example #31
0
 def setup(self):
     super().setup()
     speed = min(50, 10 * self.level)
     self.fy += S('%d * t' % speed)
     self.fx += S('%d * t' % speed)
Example #32
0
def test_factorial2():
    n = Symbol('n', integer=True)

    assert factorial2(-1) == 1
    assert factorial2(0) == 1
    assert factorial2(7) == 105
    assert factorial2(8) == 384

    # The following is exhaustive
    tt = Symbol('tt', integer=True, nonnegative=True)
    tte = Symbol('tte', even=True, nonnegative=True)
    tpe = Symbol('tpe', even=True, positive=True)
    tto = Symbol('tto', odd=True, nonnegative=True)
    tf = Symbol('tf', integer=True, nonnegative=False)
    tfe = Symbol('tfe', even=True, nonnegative=False)
    tfo = Symbol('tfo', odd=True, nonnegative=False)
    ft = Symbol('ft', integer=False, nonnegative=True)
    ff = Symbol('ff', integer=False, nonnegative=False)
    fn = Symbol('fn', integer=False)
    nt = Symbol('nt', nonnegative=True)
    nf = Symbol('nf', nonnegative=False)
    nn = Symbol('nn')
    #Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
    raises (ValueError, lambda: factorial2(oo))
    raises (ValueError, lambda: factorial2(S(5)/2))
    assert factorial2(n).is_integer is None
    assert factorial2(tt - 1).is_integer
    assert factorial2(tte - 1).is_integer
    assert factorial2(tpe - 3).is_integer
    assert factorial2(tto - 4).is_integer
    assert factorial2(tto - 2).is_integer
    assert factorial2(tf).is_integer is None
    assert factorial2(tfe).is_integer is None
    assert factorial2(tfo).is_integer is None
    assert factorial2(ft).is_integer is None
    assert factorial2(ff).is_integer is None
    assert factorial2(fn).is_integer is None
    assert factorial2(nt).is_integer is None
    assert factorial2(nf).is_integer is None
    assert factorial2(nn).is_integer is None

    assert factorial2(n).is_positive is None
    assert factorial2(tt - 1).is_positive is True
    assert factorial2(tte - 1).is_positive is True
    assert factorial2(tpe - 3).is_positive is True
    assert factorial2(tpe - 1).is_positive is True
    assert factorial2(tto - 2).is_positive is True
    assert factorial2(tto - 1).is_positive is True
    assert factorial2(tf).is_positive is None
    assert factorial2(tfe).is_positive is None
    assert factorial2(tfo).is_positive is None
    assert factorial2(ft).is_positive is None
    assert factorial2(ff).is_positive is None
    assert factorial2(fn).is_positive is None
    assert factorial2(nt).is_positive is None
    assert factorial2(nf).is_positive is None
    assert factorial2(nn).is_positive is None

    assert factorial2(tt).is_even is None
    assert factorial2(tt).is_odd is None
    assert factorial2(tte).is_even is None
    assert factorial2(tte).is_odd is None
    assert factorial2(tte + 2).is_even is True
    assert factorial2(tpe).is_even is True
    assert factorial2(tto).is_odd is True
    assert factorial2(tf).is_even is None
    assert factorial2(tf).is_odd is None
    assert factorial2(tfe).is_even is None
    assert factorial2(tfe).is_odd is None
    assert factorial2(tfo).is_even is False
    assert factorial2(tfo).is_odd is None
Example #33
0
def test_factor_and_dimension_with_Abs():
    v_w1 = Quantity('v_w1', length / time, S(3) / 2 * meter / second)
    expr = v_w1 - Abs(v_w1)
    assert (0, length / time) == Quantity._collect_factor_and_dimension(expr)
Example #34
0
def sdm_groebner(G, NF, O, K):
    """
    Compute a minimal standard basis of ``G`` with respect to order ``O``.

    The algorithm uses a normal form ``NF``, for example ``sdm_nf_mora``.
    The ground field is assumed to be ``K``, and monomials ordered according
    to ``O``.

    Let `N` denote the submodule generated by elements of `G`. A standard
    basis for `N` is a subset `S` of `N`, such that `in(S) = in(N)`, where for
    any subset `X` of `F`, `in(X)` denotes the submodule generated by the
    initial forms of elements of `X`. [SCA, defn 2.3.2]

    A standard basis is called minimal if no subset of it is a standard basis.

    One may show that standard bases are always generating sets.

    Minimal standard bases are not unique. This algorithm computes a
    deterministic result, depending on the particular order of `G`.

    See [SCA, algorithm 2.3.8, and remark 1.6.3].
    """
    # First compute a standard basis
    S = [f for f in G if f]
    P = list(combinations(S, 2))

    def prune(P, S, h):
        """
        Prune the pair-set by applying the chain criterion
        [SCA, remark 2.5.11].
        """
        remove = set()
        retain = set()
        for (a, b, c) in permutations(S, 3):
            A = sdm_LM(a)
            B = sdm_LM(b)
            C = sdm_LM(c)
            if len(set([A[0], B[0], C[0]])) != 1 or not h in [a, b, c] or \
               any(tuple(x) in retain for x in [a, b, c]):
                continue
            if monomial_divides(B[1:], monomial_lcm(A[1:], C[1:])):
                remove.add((tuple(a), tuple(c)))
                retain.update([tuple(b), tuple(c), tuple(a)])
        return [(f, g) for (f, g) in P if (h not in [f, g]) or \
                    ((tuple(f), tuple(g)) not in remove and \
                     (tuple(g), tuple(f)) not in remove)]

    while P:
        # TODO better data structures!!!
        #print len(P), len(S)
        # Use the "normal selection strategy"
        lcms = [(i, sdm_LM(f)[:1] + monomial_lcm(sdm_LM(f)[1:], sdm_LM(g)[1:])) for \
                i, (f, g) in enumerate(P)]
        i = min(lcms, key=lambda x: O(x[1]))[0]
        f, g = P.pop(i)
        h = NF(sdm_spoly(f, g, O, K), S, O, K)
        if h:
            S.append(h)
            P.extend((h, f) for f in S if sdm_LM(h)[0] == sdm_LM(f)[0])
            P = prune(P, S, h)

    # Now interreduce it. (TODO again, better data structures)
    S = set(tuple(f) for f in S)
    for a, b in permutations(S, 2):
        A = sdm_LM(list(a))
        B = sdm_LM(list(b))
        if sdm_monomial_divides(A, B) and b in S and a in S:
            S.remove(b)

    return sorted((list(f) for f in S), key=lambda f: O(sdm_LM(f)),
                  reverse=True)
Example #35
0
def test_probability():
    # various integrals from probability theory
    from sympy.abc import x, y
    from sympy import symbols, Symbol, Abs, expand_mul, gammasimp, powsimp, sin
    mu1, mu2 = symbols('mu1 mu2', nonzero=True)
    sigma1, sigma2 = symbols('sigma1 sigma2', positive=True)
    rate = Symbol('lambda', positive=True)

    def normal(x, mu, sigma):
        return 1 / sqrt(2 * pi * sigma**2) * exp(-(x - mu)**2 / 2 / sigma**2)

    def exponential(x, rate):
        return rate * exp(-rate * x)

    assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1
    assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \
        mu1
    assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
        == mu1**2 + sigma1**2
    assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
        == mu1**3 + 3*mu1*sigma1**2
    assert integrate(normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo),
                     meijerg=True) == 1
    assert integrate(x * normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo),
                     meijerg=True) == mu1
    assert integrate(y * normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo),
                     meijerg=True) == mu2
    assert integrate(x * y * normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo),
                     meijerg=True) == mu1 * mu2
    assert integrate(
        (x + y + 1) * normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
        (x, -oo, oo), (y, -oo, oo),
        meijerg=True) == 1 + mu1 + mu2
    assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo), meijerg=True) == \
        -1 + mu1 + mu2

    i = integrate(x**2 * normal(x, mu1, sigma1) * normal(y, mu2, sigma2),
                  (x, -oo, oo), (y, -oo, oo),
                  meijerg=True)
    assert not i.has(Abs)
    assert simplify(i) == mu1**2 + sigma1**2
    assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
                     (x, -oo, oo), (y, -oo, oo), meijerg=True) == \
        sigma2**2 + mu2**2

    assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1
    assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \
        1/rate
    assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \
        2/rate**2

    def E(expr):
        res1 = integrate(expr * exponential(x, rate) * normal(y, mu1, sigma1),
                         (x, 0, oo), (y, -oo, oo),
                         meijerg=True)
        res2 = integrate(expr * exponential(x, rate) * normal(y, mu1, sigma1),
                         (y, -oo, oo), (x, 0, oo),
                         meijerg=True)
        assert expand_mul(res1) == expand_mul(res2)
        return res1

    assert E(1) == 1
    assert E(x * y) == mu1 / rate
    assert E(x * y**2) == mu1**2 / rate + sigma1**2 / rate
    ans = sigma1**2 + 1 / rate**2
    assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans
    assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans
    assert simplify(E((x + y)**2) - E(x + y)**2) == ans

    # Beta' distribution
    alpha, beta = symbols('alpha beta', positive=True)
    betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
        /gamma(alpha)/gamma(beta)
    assert integrate(betadist, (x, 0, oo), meijerg=True) == 1
    i = integrate(x * betadist, (x, 0, oo), meijerg=True, conds='separate')
    assert (gammasimp(i[0]), i[1]) == (alpha / (beta - 1), 1 < beta)
    j = integrate(x**2 * betadist, (x, 0, oo), meijerg=True, conds='separate')
    assert j[1] == (1 < beta - 1)
    assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \
        /(beta - 2)/(beta - 1)**2

    # Beta distribution
    # NOTE: this is evaluated using antiderivatives. It also tests that
    #       meijerint_indefinite returns the simplest possible answer.
    a, b = symbols('a b', positive=True)
    betadist = x**(a - 1) * (-x + 1)**(b - 1) * gamma(a + b) / (gamma(a) *
                                                                gamma(b))
    assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1
    assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \
        a/(a + b)
    assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \
        a*(a + 1)/(a + b)/(a + b + 1)
    assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \
        gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y)

    # Chi distribution
    k = Symbol('k', integer=True, positive=True)
    chi = 2**(1 - k / 2) * x**(k - 1) * exp(-x**2 / 2) / gamma(k / 2)
    assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1
    assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \
        sqrt(2)*gamma((k + 1)/2)/gamma(k/2)
    assert simplify(integrate(x**2 * chi, (x, 0, oo), meijerg=True)) == k

    # Chi^2 distribution
    chisquared = 2**(-k / 2) / gamma(k / 2) * x**(k / 2 - 1) * exp(-x / 2)
    assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1
    assert simplify(integrate(x * chisquared, (x, 0, oo), meijerg=True)) == k
    assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \
        k*(k + 2)
    assert gammasimp(
        integrate(((x - k) / sqrt(2 * k))**3 * chisquared, (x, 0, oo),
                  meijerg=True)) == 2 * sqrt(2) / sqrt(k)

    # Dagum distribution
    a, b, p = symbols('a b p', positive=True)
    # XXX (x/b)**a does not work
    dagum = a * p / x * (x / b)**(a * p) / (1 + x**a / b**a)**(p + 1)
    assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1
    # XXX conditions are a mess
    arg = x * dagum
    assert simplify(integrate(
        arg, (x, 0, oo), meijerg=True,
        conds='none')) == a * b * gamma(1 - 1 / a) * gamma(p + 1 + 1 / a) / (
            (a * p + 1) * gamma(p))
    assert simplify(integrate(
        x * arg, (x, 0, oo), meijerg=True,
        conds='none')) == a * b**2 * gamma(1 -
                                           2 / a) * gamma(p + 1 + 2 / a) / (
                                               (a * p + 2) * gamma(p))

    # F-distribution
    d1, d2 = symbols('d1 d2', positive=True)
    f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
        /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
    assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1
    # TODO conditions are a mess
    assert simplify(integrate(x * f, (x, 0, oo), meijerg=True,
                              conds='none')) == d2 / (d2 - 2)
    assert simplify(
        integrate(x**2 * f, (x, 0, oo), meijerg=True,
                  conds='none')) == d2**2 * (d1 + 2) / d1 / (d2 - 4) / (d2 - 2)

    # TODO gamma, rayleigh

    # inverse gaussian
    lamda, mu = symbols('lamda mu', positive=True)
    dist = sqrt(lamda / 2 / pi) * x**(Rational(-3, 2)) * exp(
        -lamda * (x - mu)**2 / x / 2 / mu**2)
    mysimp = lambda expr: simplify(expr.rewrite(exp))
    assert mysimp(integrate(dist, (x, 0, oo))) == 1
    assert mysimp(integrate(x * dist, (x, 0, oo))) == mu
    assert mysimp(integrate((x - mu)**2 * dist, (x, 0, oo))) == mu**3 / lamda
    assert mysimp(integrate((x - mu)**3 * dist,
                            (x, 0, oo))) == 3 * mu**5 / lamda**2

    # Levi
    c = Symbol('c', positive=True)
    assert integrate(
        sqrt(c / 2 / pi) * exp(-c / 2 / (x - mu)) / (x - mu)**S('3/2'),
        (x, mu, oo)) == 1
    # higher moments oo

    # log-logistic
    alpha, beta = symbols('alpha beta', positive=True)
    distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \
        (1 + x**beta/alpha**beta)**2
    # FIXME: If alpha, beta are not declared as finite the line below hangs
    # after the changes in:
    #    https://github.com/sympy/sympy/pull/16603
    assert simplify(integrate(distn, (x, 0, oo))) == 1
    # NOTE the conditions are a mess, but correctly state beta > 1
    assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \
        pi*alpha/beta/sin(pi/beta)
    # (similar comment for conditions applies)
    assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \
        pi*alpha**y*y/beta/sin(pi*y/beta)

    # weibull
    k = Symbol('k', positive=True)
    n = Symbol('n', positive=True)
    distn = k / lamda * (x / lamda)**(k - 1) * exp(-(x / lamda)**k)
    assert simplify(integrate(distn, (x, 0, oo))) == 1
    assert simplify(integrate(x**n*distn, (x, 0, oo))) == \
        lamda**n*gamma(1 + n/k)

    # rice distribution
    from sympy import besseli
    nu, sigma = symbols('nu sigma', positive=True)
    rice = x / sigma**2 * exp(-(x**2 + nu**2) / 2 / sigma**2) * besseli(
        0, x * nu / sigma**2)
    assert integrate(rice, (x, 0, oo), meijerg=True) == 1
    # can someone verify higher moments?

    # Laplace distribution
    mu = Symbol('mu', real=True)
    b = Symbol('b', positive=True)
    laplace = exp(-abs(x - mu) / b) / 2 / b
    assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1
    assert integrate(x * laplace, (x, -oo, oo), meijerg=True) == mu
    assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \
        2*b**2 + mu**2

    # TODO are there other distributions supported on (-oo, oo) that we can do?

    # misc tests
    k = Symbol('k', positive=True)
    assert gammasimp(
        expand_mul(
            integrate(log(x) * x**(k - 1) * exp(-x) / gamma(k),
                      (x, 0, oo)))) == polygamma(0, k)
Example #36
0
def test_simplify():
    assert simplify(x * (y + 1) - x * y - x + 1 < x) == (x > 1)
    assert simplify(S(1) < -x) == (x < -1)
Example #37
0
def test_Or():
    N = Normal('N', 0, 1)
    assert simplify(P(Or(N > 2, N < 1))) == \
        -erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + S(3)/2
    assert P(Or(N < 0, N < 1)) == P(N < 1)
    assert P(Or(N > 0, N < 0)) == 1
Example #38
0
 def t(m, n):
     x = S(m) / n
     r = polygamma(0, x)
     if r.has(polygamma):
         return False
     return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10
Example #39
0
def test_loggamma():
    raises(TypeError, lambda: loggamma(2, 3))
    raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2))

    assert loggamma(-1) == oo
    assert loggamma(-2) == oo
    assert loggamma(0) == oo
    assert loggamma(1) == 0
    assert loggamma(2) == 0
    assert loggamma(3) == log(2)
    assert loggamma(4) == log(6)

    n = Symbol("n", integer=True, positive=True)
    assert loggamma(n) == log(gamma(n))
    assert loggamma(-n) == oo
    assert loggamma(n / 2) == log(2**(-n + 1) * sqrt(pi) * gamma(n) /
                                  gamma(n / 2 + S.Half))

    from sympy import I

    assert loggamma(oo) == oo
    assert loggamma(-oo) == zoo
    assert loggamma(I * oo) == zoo
    assert loggamma(-I * oo) == zoo
    assert loggamma(zoo) == zoo
    assert loggamma(nan) == nan

    L = loggamma(S(16) / 3)
    E = -5 * log(3) + loggamma(S(1) / 3) + log(4) + log(7) + log(10) + log(13)
    assert expand_func(L).doit() == E
    assert L.n() == E.n()

    L = loggamma(19 / S(4))
    E = -4 * log(4) + loggamma(S(3) / 4) + log(3) + log(7) + log(11) + log(15)
    assert expand_func(L).doit() == E
    assert L.n() == E.n()

    L = loggamma(S(23) / 7)
    E = -3 * log(7) + log(2) + loggamma(S(2) / 7) + log(9) + log(16)
    assert expand_func(L).doit() == E
    assert L.n() == E.n()

    L = loggamma(19 / S(4) - 7)
    E = -log(9) - log(5) + loggamma(S(3) / 4) + 3 * log(4) - 3 * I * pi
    assert expand_func(L).doit() == E
    assert L.n() == E.n()

    L = loggamma(23 / S(7) - 6)
    E = -log(19) - log(12) - log(5) + loggamma(
        S(2) / 7) + 3 * log(7) - 3 * I * pi
    assert expand_func(L).doit() == E
    assert L.n() == E.n()

    assert loggamma(x).diff(x) == polygamma(0, x)
    s1 = loggamma(1 / (x + sin(x)) + cos(x)).nseries(x, n=4)
    s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \
        log(x)*x**2/2
    assert (s1 - s2).expand(force=True).removeO() == 0
    s1 = loggamma(1 / x).series(x)
    s2 = (1/x - S(1)/2)*log(1/x) - 1/x + log(2*pi)/2 + \
        x/12 - x**3/360 + x**5/1260 + O(x**7)
    assert ((s1 - s2).expand(force=True)).removeO() == 0

    assert loggamma(x).rewrite('intractable') == log(gamma(x))

    s1 = loggamma(x).series(x)
    assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \
        pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6)
    assert s1 == loggamma(x).rewrite('intractable').series(x)

    assert conjugate(loggamma(x)) == loggamma(conjugate(x))
    assert conjugate(loggamma(0)) == conjugate(loggamma(0))
    assert conjugate(loggamma(1)) == loggamma(conjugate(1))
    assert conjugate(loggamma(-oo)) == conjugate(loggamma(-oo))
    assert loggamma(x).is_real is None
    y, z = Symbol('y', real=True), Symbol('z', imaginary=True)
    assert loggamma(y).is_real
    assert loggamma(z).is_real is False

    def tN(N, M):
        assert loggamma(1 / x)._eval_nseries(x, n=N).getn() == M

    tN(0, 0)
    tN(1, 1)
    tN(2, 3)
    tN(3, 3)
    tN(4, 5)
    tN(5, 5)
Example #40
0
 def _test_subgroup(K, T, S):
     _gens = T(K.generators)
     assert all(elem in S for elem in _gens)
     assert T.is_injective()
     assert T.image().order() == S.order()
Example #41
0
def test_issue_14450():
    assert uppergamma(3 / 8, x).evalf() == uppergamma(0.375, x)
    assert lowergamma(x, 3 / 8).evalf() == lowergamma(x, 0.375)
    # some values from Wolfram Alpha for comparison
    assert abs(uppergamma(S(3) / 8, 2).evalf() - 0.07105675881) < 1e-9
    assert abs(lowergamma(S(3) / 8, 2).evalf() - 2.2993794256) < 1e-9
Example #42
0
def test_sparse_matrix():
    def sparse_eye(n):
        return SparseMatrix.eye(n)

    def sparse_zeros(n):
        return SparseMatrix.zeros(n)

    # creation args
    raises(TypeError, lambda: SparseMatrix(1, 2))

    a = SparseMatrix((
        (1, 0),
        (0, 1)
    ))
    assert SparseMatrix(a) == a

    from sympy.matrices import MutableSparseMatrix, MutableDenseMatrix
    a = MutableSparseMatrix([])
    b = MutableDenseMatrix([1, 2])
    assert a.row_join(b) == b
    assert a.col_join(b) == b
    assert type(a.row_join(b)) == type(a)
    assert type(a.col_join(b)) == type(a)

    # make sure 0 x n matrices get stacked correctly
    sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]
    assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])
    sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]
    assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])

    # test element assignment
    a = SparseMatrix((
        (1, 0),
        (0, 1)
    ))

    a[3] = 4
    assert a[1, 1] == 4
    a[3] = 1

    a[0, 0] = 2
    assert a == SparseMatrix((
        (2, 0),
        (0, 1)
    ))
    a[1, 0] = 5
    assert a == SparseMatrix((
        (2, 0),
        (5, 1)
    ))
    a[1, 1] = 0
    assert a == SparseMatrix((
        (2, 0),
        (5, 0)
    ))
    assert a._smat == {(0, 0): 2, (1, 0): 5}

    # test_multiplication
    a = SparseMatrix((
        (1, 2),
        (3, 1),
        (0, 6),
    ))

    b = SparseMatrix((
        (1, 2),
        (3, 0),
    ))

    c = a*b
    assert c[0, 0] == 7
    assert c[0, 1] == 2
    assert c[1, 0] == 6
    assert c[1, 1] == 6
    assert c[2, 0] == 18
    assert c[2, 1] == 0

    try:
        eval('c = a @ b')
    except SyntaxError:
        pass
    else:
        assert c[0, 0] == 7
        assert c[0, 1] == 2
        assert c[1, 0] == 6
        assert c[1, 1] == 6
        assert c[2, 0] == 18
        assert c[2, 1] == 0

    x = Symbol("x")

    c = b * Symbol("x")
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == x
    assert c[0, 1] == 2*x
    assert c[1, 0] == 3*x
    assert c[1, 1] == 0

    c = 5 * b
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == 5
    assert c[0, 1] == 2*5
    assert c[1, 0] == 3*5
    assert c[1, 1] == 0

    #test_power
    A = SparseMatrix([[2, 3], [4, 5]])
    assert (A**5)[:] == [6140, 8097, 10796, 14237]
    A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
    assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]

    # test_creation
    x = Symbol("x")
    a = SparseMatrix([[x, 0], [0, 0]])
    m = a
    assert m.cols == m.rows
    assert m.cols == 2
    assert m[:] == [x, 0, 0, 0]
    b = SparseMatrix(2, 2, [x, 0, 0, 0])
    m = b
    assert m.cols == m.rows
    assert m.cols == 2
    assert m[:] == [x, 0, 0, 0]

    assert a == b
    S = sparse_eye(3)
    S.row_del(1)
    assert S == SparseMatrix([
                             [1, 0, 0],
    [0, 0, 1]])
    S = sparse_eye(3)
    S.col_del(1)
    assert S == SparseMatrix([
                             [1, 0],
    [0, 0],
    [0, 1]])
    S = SparseMatrix.eye(3)
    S[2, 1] = 2
    S.col_swap(1, 0)
    assert S == SparseMatrix([
        [0, 1, 0],
        [1, 0, 0],
        [2, 0, 1]])

    a = SparseMatrix(1, 2, [1, 2])
    b = a.copy()
    c = a.copy()
    assert a[0] == 1
    a.row_del(0)
    assert a == SparseMatrix(0, 2, [])
    b.col_del(1)
    assert b == SparseMatrix(1, 1, [1])

    # test_determinant
    x, y = Symbol('x'), Symbol('y')

    assert SparseMatrix(1, 1, [0]).det() == 0

    assert SparseMatrix([[1]]).det() == 1

    assert SparseMatrix(((-3, 2), (8, -5))).det() == -1

    assert SparseMatrix(((x, 1), (y, 2*y))).det() == 2*x*y - y

    assert SparseMatrix(( (1, 1, 1),
                          (1, 2, 3),
                          (1, 3, 6) )).det() == 1

    assert SparseMatrix(( ( 3, -2,  0, 5),
                          (-2,  1, -2, 2),
                          ( 0, -2,  5, 0),
                          ( 5,  0,  3, 4) )).det() == -289

    assert SparseMatrix(( ( 1,  2,  3,  4),
                          ( 5,  6,  7,  8),
                          ( 9, 10, 11, 12),
                          (13, 14, 15, 16) )).det() == 0

    assert SparseMatrix(( (3, 2, 0, 0, 0),
                          (0, 3, 2, 0, 0),
                          (0, 0, 3, 2, 0),
                          (0, 0, 0, 3, 2),
                          (2, 0, 0, 0, 3) )).det() == 275

    assert SparseMatrix(( (1, 0,  1,  2, 12),
                          (2, 0,  1,  1,  4),
                          (2, 1,  1, -1,  3),
                          (3, 2, -1,  1,  8),
                          (1, 1,  1,  0,  6) )).det() == -55

    assert SparseMatrix(( (-5,  2,  3,  4,  5),
                          ( 1, -4,  3,  4,  5),
                          ( 1,  2, -3,  4,  5),
                          ( 1,  2,  3, -2,  5),
                          ( 1,  2,  3,  4, -1) )).det() == 11664

    assert SparseMatrix(( ( 2,  7, -1, 3, 2),
                          ( 0,  0,  1, 0, 1),
                          (-2,  0,  7, 0, 2),
                          (-3, -2,  4, 5, 3),
                          ( 1,  0,  0, 0, 1) )).det() == 123

    # test_slicing
    m0 = sparse_eye(4)
    assert m0[:3, :3] == sparse_eye(3)
    assert m0[2:4, 0:2] == sparse_zeros(2)

    m1 = SparseMatrix(3, 3, lambda i, j: i + j)
    assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2))
    assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3))

    m2 = SparseMatrix(
        [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
    assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15])
    assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]])

    assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]])

    # test_submatrix_assignment
    m = sparse_zeros(4)
    m[2:4, 2:4] = sparse_eye(2)
    assert m == SparseMatrix([(0, 0, 0, 0),
                              (0, 0, 0, 0),
                              (0, 0, 1, 0),
                              (0, 0, 0, 1)])
    assert len(m._smat) == 2
    m[:2, :2] = sparse_eye(2)
    assert m == sparse_eye(4)
    m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4))
    assert m == SparseMatrix([(1, 0, 0, 0),
                              (2, 1, 0, 0),
                              (3, 0, 1, 0),
                              (4, 0, 0, 1)])
    m[:, :] = sparse_zeros(4)
    assert m == sparse_zeros(4)
    m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))
    assert m == SparseMatrix((( 1,  2,  3,  4),
                              ( 5,  6,  7,  8),
                              ( 9, 10, 11, 12),
                              (13, 14, 15, 16)))
    m[:2, 0] = [0, 0]
    assert m == SparseMatrix((( 0,  2,  3,  4),
                              ( 0,  6,  7,  8),
                              ( 9, 10, 11, 12),
                              (13, 14, 15, 16)))

    # test_reshape
    m0 = sparse_eye(3)
    assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
    m1 = SparseMatrix(3, 4, lambda i, j: i + j)
    assert m1.reshape(4, 3) == \
        SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)])
    assert m1.reshape(2, 6) == \
        SparseMatrix([(0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)])

    # test_applyfunc
    m0 = sparse_eye(3)
    assert m0.applyfunc(lambda x: 2*x) == sparse_eye(3)*2
    assert m0.applyfunc(lambda x: 0 ) == sparse_zeros(3)

    # test__eval_Abs
    assert abs(SparseMatrix(((x, 1), (y, 2*y)))) == SparseMatrix(((Abs(x), 1), (Abs(y), 2*Abs(y))))

    # test_LUdecomp
    testmat = SparseMatrix([[ 0, 2, 5, 3],
                            [ 3, 3, 7, 4],
                            [ 8, 4, 0, 2],
                            [-2, 6, 3, 4]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)

    testmat = SparseMatrix([[ 6, -2, 7, 4],
                            [ 0,  3, 6, 7],
                            [ 1, -2, 7, 4],
                            [-9,  2, 6, 3]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)

    x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
    M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
    L, U, p = M.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L*U).permute_rows(p, 'backward') - M == sparse_zeros(3)

    # test_LUsolve
    A = SparseMatrix([[2, 3, 5],
                      [3, 6, 2],
                      [8, 3, 6]])
    x = SparseMatrix(3, 1, [3, 7, 5])
    b = A*x
    soln = A.LUsolve(b)
    assert soln == x
    A = SparseMatrix([[0, -1, 2],
                      [5, 10, 7],
                      [8,  3, 4]])
    x = SparseMatrix(3, 1, [-1, 2, 5])
    b = A*x
    soln = A.LUsolve(b)
    assert soln == x

    # test_inverse
    A = sparse_eye(4)
    assert A.inv() == sparse_eye(4)
    assert A.inv(method="CH") == sparse_eye(4)
    assert A.inv(method="LDL") == sparse_eye(4)

    A = SparseMatrix([[2, 3, 5],
                      [3, 6, 2],
                      [7, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A*Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    A = SparseMatrix([[2, 3, 5],
                      [3, 6, 2],
                      [5, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A*Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    # test_cross
    v1 = Matrix(1, 3, [1, 2, 3])
    v2 = Matrix(1, 3, [3, 4, 5])
    assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2])
    assert v1.norm(2)**2 == 14

    # conjugate
    a = SparseMatrix(((1, 2 + I), (3, 4)))
    assert a.C == SparseMatrix([
        [1, 2 - I],
        [3,     4]
    ])

    # mul
    assert a*Matrix(2, 2, [1, 0, 0, 1]) == a
    assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([
        [2, 3 + I],
        [4,     5]
    ])

    # col join
    assert a.col_join(sparse_eye(2)) == SparseMatrix([
        [1, 2 + I],
        [3,     4],
        [1,     0],
        [0,     1]
    ])

    # symmetric
    assert not a.is_symmetric(simplify=False)

    # test_cofactor
    assert sparse_eye(3) == sparse_eye(3).cofactor_matrix()
    test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
    assert test.cofactor_matrix() == \
        SparseMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
    test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    assert test.cofactor_matrix() == \
        SparseMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])

    # test_jacobian
    x = Symbol('x')
    y = Symbol('y')
    L = SparseMatrix(1, 2, [x**2*y, 2*y**2 + x*y])
    syms = [x, y]
    assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])

    L = SparseMatrix(1, 2, [x, x**2*y**3])
    assert L.jacobian(syms) == SparseMatrix([[1, 0], [2*x*y**3, x**2*3*y**2]])

    # test_QR
    A = Matrix([[1, 2], [2, 3]])
    Q, S = A.QRdecomposition()
    R = Rational
    assert Q == Matrix([
        [  5**R(-1, 2),  (R(2)/5)*(R(1)/5)**R(-1, 2)],
        [2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]])
    assert S == Matrix([
        [5**R(1, 2),     8*5**R(-1, 2)],
        [         0, (R(1)/5)**R(1, 2)]])
    assert Q*S == A
    assert Q.T * Q == sparse_eye(2)

    R = Rational
    # test nullspace
    # first test reduced row-ech form

    M = SparseMatrix([[5, 7, 2, 1],
               [1, 6, 2, -1]])
    out, tmp = M.rref()
    assert out == Matrix([[1, 0, -R(2)/23, R(13)/23],
                          [0, 1,  R(8)/23, R(-6)/23]])

    M = SparseMatrix([[ 1,  3, 0,  2,  6, 3, 1],
                      [-2, -6, 0, -2, -8, 3, 1],
                      [ 3,  9, 0,  0,  6, 6, 2],
                      [-1, -3, 0,  1,  0, 9, 3]])

    out, tmp = M.rref()
    assert out == Matrix([[1, 3, 0, 0, 2, 0, 0],
                          [0, 0, 0, 1, 2, 0, 0],
                          [0, 0, 0, 0, 0, 1, R(1)/3],
                          [0, 0, 0, 0, 0, 0, 0]])
    # now check the vectors
    basis = M.nullspace()
    assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
    assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
    assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
    assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1)/3, 1])

    # test eigen
    x = Symbol('x')
    y = Symbol('y')
    sparse_eye3 = sparse_eye(3)
    assert sparse_eye3.charpoly(x) == PurePoly(((x - 1)**3))
    assert sparse_eye3.charpoly(y) == PurePoly(((y - 1)**3))

    # test values
    M = Matrix([( 0, 1, -1),
                ( 1, 1,  0),
                (-1, 0,  1)])
    vals = M.eigenvals()
    assert sorted(vals.keys()) == [-1, 1, 2]

    R = Rational
    M = Matrix([[1, 0, 0],
                [0, 1, 0],
                [0, 0, 1]])
    assert M.eigenvects() == [(1, 3, [
        Matrix([1, 0, 0]),
        Matrix([0, 1, 0]),
        Matrix([0, 0, 1])])]
    M = Matrix([[5, 0, 2],
                [3, 2, 0],
                [0, 0, 1]])
    assert M.eigenvects() == [(1, 1, [Matrix([R(-1)/2, R(3)/2, 1])]),
                              (2, 1, [Matrix([0, 1, 0])]),
                              (5, 1, [Matrix([1, 1, 0])])]

    assert M.zeros(3, 5) == SparseMatrix(3, 5, {})
    A =  SparseMatrix(10, 10, {(0, 0): 18, (0, 9): 12, (1, 4): 18, (2, 7): 16, (3, 9): 12, (4, 2): 19, (5, 7): 16, (6, 2): 12, (9, 7): 18})
    assert A.row_list() == [(0, 0, 18), (0, 9, 12), (1, 4, 18), (2, 7, 16), (3, 9, 12), (4, 2, 19), (5, 7, 16), (6, 2, 12), (9, 7, 18)]
    assert A.col_list() == [(0, 0, 18), (4, 2, 19), (6, 2, 12), (1, 4, 18), (2, 7, 16), (5, 7, 16), (9, 7, 18), (0, 9, 12), (3, 9, 12)]
    assert SparseMatrix.eye(2).nnz() == 2
def test_issue_4511():
    # This works, but gives a complicated answer.  The correct answer is x - cos(x).
    # The last one is what Maple gives.  It is also quite slow.
    assert integrate(cos(x)**2 / (1 - sin(x))) in [x - cos(x), 1 - cos(x) + x,
            -2/(tan((S(1)/2)*x)**2 + 1) + x]