Пример #1
0
def norm(A_expr,axis=None,ord=2):

    assert axis is None or axis == 0 or axis == 1
    if axis is None:
        if not A_expr.is_Matrix:
            return sympy.Abs(A_expr)
        assert A_expr.cols == 1 or A_expr.rows == 1
        if A_expr.cols == 1 and A_expr.rows == 1:
            return sympy.Abs(A_expr)
        if A_expr.cols == 1:
            return sympy.root( sympy.Add( *[ a_expr**ord for a_expr in A_expr[:,0] ] ), ord )
        if A_expr.rows == 1:
            return sympy.root( sympy.Add( *[ a_expr**ord for a_expr in A_expr[0,:] ] ), ord )
    if axis == 0:
        A_norm_expr = sympy.Matrix.zeros(1,A_expr.cols)
        for c in range(A_expr.cols):
            A_norm_expr[0,c] = sympy.root( sympy.Add( *[ a_expr**ord for a_expr in A_expr[:,c] ] ), ord )
        return A_norm_expr
    if axis == 1:
        A_norm_expr = sympy.Matrix.zeros(A_expr.rows,1)
        for r in range(A_expr.rows):
            A_norm_expr[r,0] = sympy.root( sympy.Add( *[ a_expr**ord for a_expr in A_expr[r,:] ] ), ord )
        return A_norm_expr
    assert False
    return None
Пример #2
0
def norm(A_expr, axis=None, ord=2):

    assert axis is None or axis == 0 or axis == 1
    if axis is None:
        if not A_expr.is_Matrix:
            return sympy.Abs(A_expr)
        assert A_expr.cols == 1 or A_expr.rows == 1
        if A_expr.cols == 1 and A_expr.rows == 1:
            return sympy.Abs(A_expr)
        if A_expr.cols == 1:
            return sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[:, 0]]), ord)
        if A_expr.rows == 1:
            return sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[0, :]]), ord)
    if axis == 0:
        A_norm_expr = sympy.Matrix.zeros(1, A_expr.cols)
        for c in range(A_expr.cols):
            A_norm_expr[0, c] = sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[:, c]]), ord)
        return A_norm_expr
    if axis == 1:
        A_norm_expr = sympy.Matrix.zeros(A_expr.rows, 1)
        for r in range(A_expr.rows):
            A_norm_expr[r, 0] = sympy.root(
                sympy.Add(*[a_expr**ord for a_expr in A_expr[r, :]]), ord)
        return A_norm_expr
    assert False
    return None
Пример #3
0
def test_sqrtdenest2():
    assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \
            r5 + sqrt(11 - 2*r29)
    e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16))
    assert sqrtdenest(e) == root(-2*r29 + 11, 4)
    r = sqrt(1 + r7)
    assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r)
    e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand())
    assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3))
    assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \
        sqrt(2)*root(3, 4) + root(3, 4)**3

    assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \
         1 + r5 + sqrt(1 + r3)

    assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \
        1 + sqrt(1 + r3) + r5 + r7

    e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand())
    assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3)

    e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14)
    assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14)

    # check that the result is not more complicated than the input
    z= sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16)
    assert sqrtdenest(z) == z

    assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15))

    z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29))
    assert sqrtdenest(z) == z
Пример #4
0
def test_issue_from_PR1599():
    n1, n2, n3, n4 = symbols("n1 n2 n3 n4", negative=True)
    assert powsimp(sqrt(n1) * sqrt(n2) *
                   sqrt(n3)) == -I * sqrt(-n1) * sqrt(-n2) * sqrt(-n3)
    assert powsimp(root(n1, 3) * root(n2, 3) * root(n3, 3) * root(n4, 3)) == -(
        (-1)**Rational(1, 3)) * (-n1)**Rational(1, 3) * (-n2)**Rational(
            1, 3) * (-n3)**Rational(1, 3) * (-n4)**Rational(1, 3)
Пример #5
0
def test_sqrtdenest2():
    assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \
        r5 + sqrt(11 - 2*r29)
    e = sqrt(-r5 + sqrt(-2 * r29 + 2 * sqrt(-10 * r29 + 55) + 16))
    assert sqrtdenest(e) == root(-2 * r29 + 11, 4)
    r = sqrt(1 + r7)
    assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r)
    e = sqrt(((1 + sqrt(1 + 2 * sqrt(3 + r2 + r5)))**2).expand())
    assert sqrtdenest(e) == 1 + sqrt(1 + 2 * sqrt(r2 + r5 + 3))

    assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \
        sqrt(2)*root(3, 4) + root(3, 4)**3

    assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \
        1 + r5 + sqrt(1 + r3)

    assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \
        1 + sqrt(1 + r3) + r5 + r7

    e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand())
    assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3)

    e = sqrt(-2 * r10 + 2 * r2 * sqrt(-2 * r10 + 11) + 14)
    assert sqrtdenest(e) == sqrt(-2 * r10 - 2 * r2 + 4 * r5 + 14)

    # check that the result is not more complicated than the input
    z = sqrt(-2 * r29 + cos(2) + 2 * sqrt(-10 * r29 + 55) + 16)
    assert sqrtdenest(z) == z

    assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15))

    z = sqrt(15 - 2 * sqrt(31) + 2 * sqrt(55 - 10 * r29))
    assert sqrtdenest(z) == z
Пример #6
0
def test_issue_from_PR1599():
    n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True)
    assert (powsimp(sqrt(n1) * sqrt(n2) * sqrt(n3)) == -I * sqrt(-n1) *
            sqrt(-n2) * sqrt(-n3))
    assert (powsimp(root(n1, 3) * root(n2, 3) * root(n3, 3) *
                    root(n4, 3)) == -(-1)**(S(1) / 3) * (-n1)**(S(1) / 3) *
            (-n2)**(S(1) / 3) * (-n3)**(S(1) / 3) * (-n4)**(S(1) / 3))
Пример #7
0
def test_issue_from_PR1599():
    n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True)
    assert (powsimp(sqrt(n1)*sqrt(n2)*sqrt(n3)) ==
        -I*sqrt(-n1)*sqrt(-n2)*sqrt(-n3))
    assert (powsimp(root(n1, 3)*root(n2, 3)*root(n3, 3)*root(n4, 3)) ==
        -(-1)**(S(1)/3)*
        (-n1)**(S(1)/3)*(-n2)**(S(1)/3)*(-n3)**(S(1)/3)*(-n4)**(S(1)/3))
Пример #8
0
 def _psi(y):
     factor = m * k / hbar
     hermite = Polynomial.hermite(n)
     psi = sym.expand(
         sym.root(factor, 4) * hermite(factor * y) /
         sym.sqrt(2.**n * math.factorial(n)))
     psi = psi * sym.exp(-factor / 2. * y**2) / sym.root(sym.pi, 4)
     return psi
Пример #9
0
def test_issue_3109():
    from sympy import root, Rational
    I = S.ImaginaryUnit
    assert sqrt(33**(9*I/10)) == -33**(9*I/20)
    assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3
    assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9
    assert sqrt(exp(3*I)) == exp(3*I/2)
    assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I)
Пример #10
0
def test_issue_3109():
    from sympy import root, Rational
    I = S.ImaginaryUnit
    assert sqrt(33**(9*I/10)) == -33**(9*I/20)
    assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3
    assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9
    assert sqrt(exp(3*I)) == exp(3*I/2)
    assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I)
Пример #11
0
def test_factor_terms():
    A = Symbol('A', commutative=False)
    assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
        9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
    assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
        _keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
    assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
        9*3**(2*x)*(a + 1)
    assert factor_terms(x + x*A) == \
        x*(1 + A)
    assert factor_terms(sin(x + x*A)) == \
        sin(x*(1 + A))
    assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
        _keep_coeff(S(3), x + 1)**_keep_coeff(S(2)/3, x + 1)
    assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
        x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
    assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
        x*(a + 2*b)*(y + 1)
    i = Integral(x, (x, 0, oo))
    assert factor_terms(i) == i

    # check radical extraction
    eq = sqrt(2) + sqrt(10)
    assert factor_terms(eq) == eq
    assert factor_terms(eq, radical=True) == sqrt(2) * (1 + sqrt(5))
    eq = root(-6, 3) + root(6, 3)
    assert factor_terms(eq,
                        radical=True) == 6**(S(1) / 3) * (1 + (-1)**(S(1) / 3))

    eq = [x + x * y]
    ans = [x * (y + 1)]
    for c in [list, tuple, set]:
        assert factor_terms(c(eq)) == c(ans)
    assert factor_terms(Tuple(x + x * y)) == Tuple(x * (y + 1))
    assert factor_terms(Interval(0, 1)) == Interval(0, 1)
    e = 1 / sqrt(a / 2 + 1)
    assert factor_terms(e, clear=False) == 1 / sqrt(a / 2 + 1)
    assert factor_terms(e, clear=True) == sqrt(2) / sqrt(a + 2)

    eq = x / (x + 1 / x) + 1 / (x**2 + 1)
    assert factor_terms(eq, fraction=False) == eq
    assert factor_terms(eq, fraction=True) == 1

    assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \
        y*(2 + 1/(x + 1))/x**2

    # if not True, then processesing for this in factor_terms is not necessary
    assert gcd_terms(-x - y) == -x - y
    assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False)

    # if not True, then "special" processesing in factor_terms is not necessary
    assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
    e = exp(-x - 2) + x
    assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
    assert factor_terms(e, sign=False) == e
    assert factor_terms(exp(-4 * x - 2) -
                        x) == -x + exp(Mul(-2, 2 * x + 1, evaluate=False))
Пример #12
0
def test_issue_6208():
    from sympy import root
    assert sqrt(33**(I*Rational(9, 10))) == -33**(I*Rational(9, 20))
    assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3)  # != 2*I/3
    assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9
    assert sqrt(exp(3*I)) == exp(I*Rational(3, 2))
    assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I)
    assert sqrt(exp(5*I)) == -exp(I*Rational(5, 2))
    assert root(exp(5*I), 3).exp == Rational(1, 3)
Пример #13
0
def test_factor_terms():
    A = Symbol('A', commutative=False)
    assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
        9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
    assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
        _keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
    assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
        9*3**(2*x)*(a + 1)
    assert factor_terms(x + x*A) == \
        x*(1 + A)
    assert factor_terms(sin(x + x*A)) == \
        sin(x*(1 + A))
    assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
        _keep_coeff(S(3), x + 1)**_keep_coeff(S(2)/3, x + 1)
    assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
        x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
    assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
        x*(a + 2*b)*(y + 1)
    i = Integral(x, (x, 0, oo))
    assert factor_terms(i) == i

    # check radical extraction
    eq = sqrt(2) + sqrt(10)
    assert factor_terms(eq) == eq
    assert factor_terms(eq, radical=True) == sqrt(2)*(1 + sqrt(5))
    eq = root(-6, 3) + root(6, 3)
    assert factor_terms(eq, radical=True) == 6**(S(1)/3)*(1 + (-1)**(S(1)/3))

    eq = [x + x*y]
    ans = [x*(y + 1)]
    for c in [list, tuple, set]:
        assert factor_terms(c(eq)) == c(ans)
    assert factor_terms(Tuple(x + x*y)) == Tuple(x*(y + 1))
    assert factor_terms(Interval(0, 1)) == Interval(0, 1)
    e = 1/sqrt(a/2 + 1)
    assert factor_terms(e, clear=False) == 1/sqrt(a/2 + 1)
    assert factor_terms(e, clear=True) == sqrt(2)/sqrt(a + 2)

    eq = x/(x + 1/x) + 1/(x**2 + 1)
    assert factor_terms(eq, fraction=False) == eq
    assert factor_terms(eq, fraction=True) == 1

    assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \
        y*(2 + 1/(x + 1))/x**2

    # if not True, then processesing for this in factor_terms is not necessary
    assert gcd_terms(-x - y) == -x - y
    assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False)

    # if not True, then "special" processesing in factor_terms is not necessary
    assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
    e = exp(-x - 2) + x
    assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
    assert factor_terms(e, sign=False) == e
    assert factor_terms(exp(-4*x - 2) - x) == -x + exp(Mul(-2, 2*x + 1, evaluate=False))
Пример #14
0
def test_roots_cyclotomic():
    assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1]
    assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1]
    assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True)) == [
        Rational(-1, 2) - I * sqrt(3) / 2,
        Rational(-1, 2) + I * sqrt(3) / 2,
    ]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True)) == [
        S.Half - I * sqrt(3) / 2,
        S.Half + I * sqrt(3) / 2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [
        -cos(pi / 7) - I * sin(pi / 7),
        -cos(pi / 7) + I * sin(pi / 7),
        -cos(pi * Rational(3, 7)) - I * sin(pi * Rational(3, 7)),
        -cos(pi * Rational(3, 7)) + I * sin(pi * Rational(3, 7)),
        cos(pi * Rational(2, 7)) - I * sin(pi * Rational(2, 7)),
        cos(pi * Rational(2, 7)) + I * sin(pi * Rational(2, 7)),
    ]

    assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [
        -sqrt(2) / 2 - I * sqrt(2) / 2,
        -sqrt(2) / 2 + I * sqrt(2) / 2,
        sqrt(2) / 2 - I * sqrt(2) / 2,
        sqrt(2) / 2 + I * sqrt(2) / 2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [
        -sqrt(3) / 2 - I / 2,
        -sqrt(3) / 2 + I / 2,
        sqrt(3) / 2 - I / 2,
        sqrt(3) / 2 + I / 2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True), factor=True) == [1]
    assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True), factor=True) == [-1]

    assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == [
        -root(-1, 3),
        -1 + root(-1, 3),
    ]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == [
        -root(-1, 5),
        -root(-1, 5) ** 3,
        root(-1, 5) ** 2,
        -1 - root(-1, 5) ** 2 + root(-1, 5) + root(-1, 5) ** 3,
    ]

    assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == [
        1 - root(-1, 3),
        root(-1, 3),
    ]
Пример #15
0
def extract_complex_root(expr, subs):

    def divide_rational(rational):
        return rational.numerator(), rational.denominator()

    def is_not_odd(number):
        return bool(number % 2)

    def check_root(act):
        for arg_ in act.args:
            if isinstance(arg_, Rational):
                return arg_
        return None

    if isinstance(expr, Pow) and check_root(expr) is not None:
        n, m = divide_rational(check_root(expr))
        if is_not_odd(n) and is_not_odd(m):
            under_root = expr.args[0]
            if under_root.evalf(subs=subs) < 0:
                if n > 0:
                    return -root(abs(under_root) ** n, m)
                else:
                    return 1/-root(abs(under_root) ** -n, m)
            else:
                if n > 0:
                    return root(abs(under_root) ** n, m)
                else:
                    return 1 / root(abs(under_root) ** -n, m)
        else:
            return expr
    else:
        if isinstance(expr, Add):
            out_expr = 0
            for arg in expr.args:
                out_expr += extract_complex_root(arg, subs)
            return out_expr
        elif isinstance(expr, Mul):
            out_expr = 1
            for arg in expr.args:
                out_expr *= extract_complex_root(arg, subs)
            return out_expr
        elif isinstance(expr, Pow):
            out_expr = 1
            for arg in expr.args:
                out_expr **= extract_complex_root(arg, subs)
            return out_expr
        else:
            return expr
Пример #16
0
def test_sqrtdenest():
    d = {sqrt(5 + 2 * sqrt(6)): sqrt(2) + sqrt(3),
        sqrt(sqrt(2)): sqrt(sqrt(2)),
        sqrt(5+sqrt(7)): sqrt(5+sqrt(7)),
        sqrt(3+sqrt(5+2*sqrt(7))):
            sqrt(6+3*sqrt(7))/(sqrt(2)*(5+2*sqrt(7))**Rational(1,4)) +
            3*(5+2*sqrt(7))**Rational(1,4)/(sqrt(2)*sqrt(6+3*sqrt(7))),
        sqrt(3+2*sqrt(3)): 3**Rational(1,4)/sqrt(2)+3/(sqrt(2)*3**Rational(1,4))}
    for i in d:
        assert sqrtdenest(i) == d[i] or denester([i])[0] == d[i]

    # this test caused a pattern recognition failure in sqrtdenest
    # nest = sqrt(2) + sqrt(5) - sqrt(7)
    nest = symbols('nest')
    x0, x1, x2, x3, x4, x5, x6 = symbols('x:7')
    l = sqrt(2) + sqrt(5)
    r = sqrt(7) + nest
    s = (l**2 - r**2).expand() + nest**2 # == nest**2
    ok = solve(nest**4 - s**2, nest)[1] # this will change if results order changes
    assert abs((l - r).subs(nest, ok).n()) < 1e-12
    x0 = sqrt(3)
    x2 = root(45*I*x0 - 28, 3)
    x3 = 19/x2
    x4 = x2 + x3
    x5 = -x4 - 14
    x6 = sqrt(-x5)
    ans = -x0*x6/3 + x0*sqrt(-x4 + 28 - 6*sqrt(210)*x6/x5)/3
    assert expand_mul(radsimp(ok) - ans) == 0
    # issue 2554
    eq = sqrt(sqrt(sqrt(2) + 2) + 2)
    assert sqrtdenest(eq) == eq
Пример #17
0
def test_trig_split():
    assert trig_split(cos(x), cos(y)) == (1, 1, 1, x, y, True)
    assert trig_split(2*cos(x), -2*cos(y)) == (2, 1, -1, x, y, True)
    assert trig_split(cos(x)*sin(y), cos(y)*sin(y)) == \
        (sin(y), 1, 1, x, y, True)

    assert trig_split(cos(x), -sqrt(3)*sin(x), two=True) == \
        (2, 1, -1, x, pi/6, False)
    assert trig_split(cos(x), sin(x), two=True) == \
        (sqrt(2), 1, 1, x, pi/4, False)
    assert trig_split(cos(x), -sin(x), two=True) == \
        (sqrt(2), 1, -1, x, pi/4, False)
    assert trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) == \
        (2*sqrt(2), 1, -1, x, pi/6, False)
    assert trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) == \
        (-2*sqrt(2), 1, 1, x, pi/3, False)
    assert trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) == \
        (sqrt(6)/3, 1, 1, x, pi/6, False)
    assert trig_split(-sqrt(6)*cos(x)*sin(y),
            -sqrt(2)*sin(x)*sin(y), two=True) == \
        (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False)

    assert trig_split(cos(x), sin(x)) is None
    assert trig_split(cos(x), sin(z)) is None
    assert trig_split(2*cos(x), -sin(x)) is None
    assert trig_split(cos(x), -sqrt(3)*sin(x)) is None
    assert trig_split(cos(x)*cos(y), sin(x)*sin(z)) is None
    assert trig_split(cos(x)*cos(y), sin(x)*sin(y)) is None
    assert trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) is \
        None

    assert trig_split(sqrt(3)*sqrt(x), cos(3), two=True) is None
    assert trig_split(sqrt(3)*root(x, 3), sin(3)*cos(2), two=True) is None
    assert trig_split(cos(5)*cos(6), cos(7)*sin(5), two=True) is None
Пример #18
0
def test_trig_split():
    assert trig_split(cos(x), cos(y)) == (1, 1, 1, x, y, True)
    assert trig_split(2 * cos(x), -2 * cos(y)) == (2, 1, -1, x, y, True)
    assert trig_split(cos(x)*sin(y), cos(y)*sin(y)) == \
        (sin(y), 1, 1, x, y, True)

    assert trig_split(cos(x), -sqrt(3)*sin(x), two=True) == \
        (2, 1, -1, x, pi/6, False)
    assert trig_split(cos(x), sin(x), two=True) == \
        (sqrt(2), 1, 1, x, pi/4, False)
    assert trig_split(cos(x), -sin(x), two=True) == \
        (sqrt(2), 1, -1, x, pi/4, False)
    assert trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) == \
        (2*sqrt(2), 1, -1, x, pi/6, False)
    assert trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) == \
        (-2*sqrt(2), 1, 1, x, pi/3, False)
    assert trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) == \
        (sqrt(6)/3, 1, 1, x, pi/6, False)
    assert trig_split(-sqrt(6)*cos(x)*sin(y),
            -sqrt(2)*sin(x)*sin(y), two=True) == \
        (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False)

    assert trig_split(cos(x), sin(x)) is None
    assert trig_split(cos(x), sin(z)) is None
    assert trig_split(2 * cos(x), -sin(x)) is None
    assert trig_split(cos(x), -sqrt(3) * sin(x)) is None
    assert trig_split(cos(x) * cos(y), sin(x) * sin(z)) is None
    assert trig_split(cos(x) * cos(y), sin(x) * sin(y)) is None
    assert trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) is \
        None

    assert trig_split(sqrt(3) * sqrt(x), cos(3), two=True) is None
    assert trig_split(sqrt(3) * root(x, 3), sin(3) * cos(2), two=True) is None
    assert trig_split(cos(5) * cos(6), cos(7) * sin(5), two=True) is None
Пример #19
0
 def invalidPubExponent(self, c, p="p", q="q", e="e"):
     """Recovers some bytes of ciphertext if n is factored, but e was invalid.
     (Like e=100) The vast majority of bytes are however lost, as we are taking the
     GCD(e, totient(N))th root of the Ciphertext. Therefore only the most significant
     bits of the ciphertext may be recovered.
     Returns plaintext, since a key can't be formed from a non-integer exponent"""
     # Explanation of why this works: There exists no modinv if GCD(e,Totient(N)) != 1
     # but let x be e/GCD
     # then there is a modular inverse of x to totient n
     # c = m^(GCDx) mod n
     # c^(x^-1) = m^GCD mod n, where x^-1 denotes modinv(x,totientN)
     # Now if we take the GCD-th root
     # c^(x^-1)^(1/GCD) = m mod n, except that roots aren't an operation defined on modular rings
     # They are defined on finite fields in some circumstances, but this is not a finite field.
     # Therefore we have only recovered a few of the most significant bits of c.
     if (p == "p"): p = self.p
     if (p == "q"): q = self.q
     totientN = (p - 1) * (q - 1)
     n = p * q
     if (e == "e"): e = self.e
     GCD = gcd(e, totientN)
     if (GCD == 1):
         return "[X] This method only applies for invalid Public Exponents."
     d = modinv(e // GCD, totientN)
     c = pow(c, d, n)
     import sympy
     plaintext = sympy.root(c, GCD)
     return plaintext
def test_roots_cyclotomic():
    assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1]
    assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1]
    assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True)) == [
        -S(1) / 2 - I * sqrt(3) / 2, -S(1) / 2 + I * sqrt(3) / 2
    ]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True)) == [
        S(1) / 2 - I * sqrt(3) / 2,
        S(1) / 2 + I * sqrt(3) / 2
    ]

    assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [
        -cos(pi / 7) - I * sin(pi / 7),
        -cos(pi / 7) + I * sin(pi / 7),
        -cos(3 * pi / 7) - I * sin(3 * pi / 7),
        -cos(3 * pi / 7) + I * sin(3 * pi / 7),
        cos(2 * pi / 7) - I * sin(2 * pi / 7),
        cos(2 * pi / 7) + I * sin(2 * pi / 7),
    ]

    assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [
        -sqrt(2) / 2 - I * sqrt(2) / 2,
        -sqrt(2) / 2 + I * sqrt(2) / 2,
        sqrt(2) / 2 - I * sqrt(2) / 2,
        sqrt(2) / 2 + I * sqrt(2) / 2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [
        -sqrt(3) / 2 - I / 2,
        -sqrt(3) / 2 + I / 2,
        sqrt(3) / 2 - I / 2,
        sqrt(3) / 2 + I / 2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True),
                            factor=True) == [1]
    assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True),
                            factor=True) == [-1]

    assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \
        [-root(-1, 3), -1 + root(-1, 3)]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \
        [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \
        [-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3]

    assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \
        [1 - root(-1, 3), root(-1, 3)]
Пример #21
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
    r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re {\left (x + y \right )}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta{\left (x \right )}'
Пример #22
0
def n1n2n3e3c1c2c3(n1, n2, n3, c1, c2, c3, e=3):
    from sympy.ntheory.modular import crt
    from sympy import root

    N = [n1, n2, n3]
    C = [c1, c2, c3]
    M = crt(N, C)[0]

    m = root(M, 3)
    return m
Пример #23
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1)+exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
    r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2,k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3,k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x+y)) == r"\Re {\left (x + y \right )}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x,y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta{\left (x \right )}'
Пример #24
0
def test_AlgebraicNumber():
    a = AlgebraicNumber(sqrt(2))
    sT(
        a,
        "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])"
    )
    a = AlgebraicNumber(root(-2, 3))
    sT(
        a,
        "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])"
    )
Пример #25
0
def test_roots_cyclotomic():
    assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1]
    assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1]
    assert roots_cyclotomic(cyclotomic_poly(
        3, x, polys=True)) == [-S(1)/2 - I*sqrt(3)/2, -S(1)/2 + I*sqrt(3)/2]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(
        6, x, polys=True)) == [S(1)/2 - I*sqrt(3)/2, S(1)/2 + I*sqrt(3)/2]

    assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [
        -cos(pi/7) - I*sin(pi/7),
        -cos(pi/7) + I*sin(pi/7),
        -cos(3*pi/7) - I*sin(3*pi/7),
        -cos(3*pi/7) + I*sin(3*pi/7),
        cos(2*pi/7) - I*sin(2*pi/7),
        cos(2*pi/7) + I*sin(2*pi/7),
    ]

    assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [
        -sqrt(2)/2 - I*sqrt(2)/2,
        -sqrt(2)/2 + I*sqrt(2)/2,
        sqrt(2)/2 - I*sqrt(2)/2,
        sqrt(2)/2 + I*sqrt(2)/2,
    ]

    assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [
        -sqrt(3)/2 - I/2,
        -sqrt(3)/2 + I/2,
        sqrt(3)/2 - I/2,
        sqrt(3)/2 + I/2,
    ]

    assert roots_cyclotomic(
        cyclotomic_poly(1, x, polys=True), factor=True) == [1]
    assert roots_cyclotomic(
        cyclotomic_poly(2, x, polys=True), factor=True) == [-1]

    assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \
        [-root(-1, 3), -1 + root(-1, 3)]
    assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \
        [-I, I]
    assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \
        [-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3]

    assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \
        [1 - root(-1, 3), root(-1, 3)]
Пример #26
0
def first_point_model():
    x, y = sympy.symbols('x y')  #x=d1,y=L
    n = float(2)
    p0 = float(-35.0)
    d0 = float(0.6)
    s1 = float(0.002014)
    s2 = float(0.0009455)
    s3 = float(0.3127)
    PA = float(-47.8)
    PB = float(-53)
    d = float(2)
    f = [
        p0 - 10 * n * sympy.log(x / d0, 10) - s1 * sympy.root(
            (180 / sympy.pi) * sympy.atan(y / x), 2) - s2 *
        (180 / sympy.pi) * sympy.atan(y / x) - s3 - 10 * n *
        sympy.log(sympy.sqrt(sympy.root(x, 2) + sympy.root(y, 2)) / x, 10) -
        PA, p0 - 10 * n * sympy.log((d - x) / d0, 10) - s1 * sympy.root(
            (180 / math.pi) * sympy.atan(y / (d - x)), 2) - s2 *
        (180 / sympy.pi) * sympy.atan(y / (d - x)) - s3 - 10 * n * sympy.log(
            sympy.sqrt(sympy.root((d - x), 2) + sympy.root(y, 2)) /
            (d - x), 10) - PB
    ]
    p = sympy.expand(f[0])
    print(p)
    q = sympy.expand(f[1])
    print(q)
    result = sympy.nonlinsolve([p, q], [x, y])
    # result=fsolve(f,[1,1])
    print(result)
    return result
Пример #27
0
    def _gen_params(self, dimension, fixed_e):
        if fixed_e is not None:
            if (fixed_e % 2) == 0:
                print("Error: e is even number")
                fixed_e = None
            if fixed_e < 3:
                fixed_e = None

        difference = 2**(dimension // 2 - 2)

        while True:
            p = q = 0

            # Based on Pollard's p − 1 algorithm generate strong primes
            # https://en.wikipedia.org/wiki/Pollard%27s_p_%E2%88%92_1_algorithm
            # (p - 1 = prime * 2) => (p = prime * 2 + 1)
            while sympy.isprime(p) is False:
                p_1 = sympy.nextprime(
                    random.getrandbits(dimension // 2 + 1)) * 2
                p = p_1 + 1
            while sympy.isprime(q) is False:
                q_1 = sympy.nextprime(random.getrandbits(dimension // 2)) * 2
                q = q_1 + 1

            # Anti Fermat's factorization method
            # https://en.wikipedia.org/wiki/Fermat%27s_factorization_method
            if abs(p - q) > difference:
                n = p * q
                if lib.bitcount(n) == dimension:
                    phi = (p - 1) * (q - 1)
                    while True:
                        if fixed_e is None:
                            e = random.randint(3, phi - 1)
                        else:
                            e = fixed_e

                        if sympy.gcd(e, phi) == 1:
                            d = sympy.invert(e, phi)

                            # Anti Wiener's attack
                            # https://en.wikipedia.org/wiki/Wiener%27s_attack
                            if d > 1 / 3 * sympy.root(n, 4):
                                break
                    break

        self.p = p
        self.q = q
        self.n = n
        self.e = e
        self.d = int(d)

        return e, d, n
Пример #28
0
def test_sqrtdenest2():
    assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \
            r5 + sqrt(11 - 2*r29)
    e = sqrt(-r5 + sqrt(-2 * r29 + 2 * sqrt(-10 * r29 + 55) + 16))
    assert sqrtdenest(e) == root(-2 * r29 + 11, 4)
    r = sqrt(1 + r7)
    assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r)
    e = sqrt(((1 + sqrt(1 + 2 * sqrt(3 + r2 + r5)))**2).expand())
    assert sqrtdenest(e) == 1 + sqrt(1 + 2 * sqrt(r2 + r5 + 3))
    assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \
        r2*root(3, 4) + root(3, 4)**3

    assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \
         1 + r5 + sqrt(1 + r3)

    assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \
        1 + sqrt(1 + r3) + r5 + r7

    e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand())
    assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3)

    e = sqrt(-2 * r10 + 2 * r2 * sqrt(-2 * r10 + 11) + 14)
    assert sqrtdenest(e) == sqrt(-2 * r10 - 2 * r2 + 4 * r5 + 14)

    # check that the result is not more complicated than the input
    z = sqrt(-2 * r29 + cos(2) + 2 * sqrt(-10 * r29 + 55) + 16)
    assert sqrtdenest(z) == z

    assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15))

    # no assertion error when the 'r's are not the same in _denester
    z = sqrt(15 - 2 * sqrt(31) + 2 * sqrt(55 - 10 * r29))
    assert sqrtdenest(z) == z

    # currently cannot denest this; check one does not get a wrong answer
    z = sqrt(8 - r2 * sqrt(5 - r5) - 3 * (1 + r5))
    assert (sqrtdenest(z) - z).evalf() < 1.0e-100
Пример #29
0
def test_sqrtdenest2():
    assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \
            r5 + sqrt(11 - 2*r29)
    e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16))
    assert sqrtdenest(e) == root(-2*r29 + 11, 4)
    r = sqrt(1 + r7)
    assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r)
    e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand())
    assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3))
    assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \
        root(3, 4)**3*(r6 + 3)/3

    assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \
         1 + r5 + sqrt(1 + r3)

    assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \
        1 + sqrt(1 + r3) + r5 + r7

    e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand())
    assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3)

    e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14)
    assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14)

    # check that the result is not more complicated than the input
    z= sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16)
    assert sqrtdenest(z) == z

    assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15))

    # no assertion error when the 'r's are not the same in _denester
    z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29))
    assert sqrtdenest(z) == z

    # currently cannot denest this; check one does not get a wrong answer
    z = sqrt(8 - r2*sqrt(5 - r5) - 3*(1 + r5))
    assert (sqrtdenest(z) - z).evalf() < 1.0e-100
Пример #30
0
    def test_subs(self):
        x, y, z, t = symbols("x:z, t", real=True, positive=True)
        expr1 = -pi * x**3 * (S(1) / 6 + y / 4 / x) + z

        eq1 = Equation(expr1, expr1)
        eq2 = eq1.subs(x**3, t)
        eq3 = eq1.subs(x**3, t, side="left")
        eq4 = eq1.subs(x**3, t, side="right")
        eq5 = eq1.subs(x**3, t, side="")
        expr2 = -pi * t * (S(1) / 6 + y / 4 / root(t, 3)) + z
        self.assertEqual(eq2, Equation(expr2, expr2))
        self.assertEqual(eq3, Equation(expr2, expr1))
        self.assertEqual(eq4, Equation(expr1, expr2))
        self.assertEqual(eq5, eq1)

        eq6 = Equation(x + y, x * y)
        eq7 = Equation(x, y**2)
        eq8 = eq6.subs(eq7)
        self.assertEqual(eq8, Equation(y + y**2, y**3))
Пример #31
0
def gen_group(bits):
    if (bits % N != 0):
        raise Exception

    n_primes = bits // N

    a = root(2**(n_primes - 1), n_primes) * 2**(bits // n_primes - 1)
    b = 2**(bits // n_primes) - 1

    primes = []

    while (len(primes) < n_primes):
        primes.append(gen_prime(a, b, DLOG_LIMIT))
        print("FOUND ONE %d MORE TO GO" % (n_primes - len(primes)))

    modulus = 1
    for x in primes:
        modulus *= x

    return (modulus, primes)
Пример #32
0
def convert_func(func):
    if func.func_normal():
        return handle_func_normal(func)
    elif func.LETTER() or func.SYMBOL():
        if func.LETTER():
            fname = func.LETTER().getText()
        elif func.SYMBOL():
            fname = func.SYMBOL().getText()[1:]
        fname = str(fname)  # can't be unicode
        if func.subexpr():
            subscript = None
            if func.subexpr().expr():                   # subscript is expr
                subscript = convert_expr(func.subexpr().expr())
            else:                                       # subscript is atom
                subscript = convert_atom(func.subexpr().atom())
            subscriptName = StrPrinter().doprint(subscript)
            fname += '_{' + subscriptName + '}'
        input_args = func.args()
        output_args = []
        while input_args.args():                        # handle multiple arguments to function
            output_args.append(convert_expr(input_args.expr()))
            input_args = input_args.args()
        output_args.append(convert_expr(input_args.expr()))
        return sympy.Function(fname)(*output_args)
    elif func.FUNC_INT():
        return handle_integral(func)
    elif func.FUNC_SQRT():
        expr = convert_expr(func.base)
        if func.root:
            r = convert_expr(func.root)
            return sympy.root(expr, r)
        else:
            return sympy.sqrt(expr)
    elif func.FUNC_SUM():
        return handle_sum_or_prod(func, "summation")
    elif func.FUNC_PROD():
        return handle_sum_or_prod(func, "product")
    elif func.FUNC_LIM():
        return handle_limit(func)
    elif func.FUNC_LOG() or func.FUNC_LN():
        return handle_log(func)
Пример #33
0
def test_roots_cubic():
    assert roots_cubic(Poly(2 * x**3, x)) == [0, 0, 0]
    assert roots_cubic(Poly(x**3 - 3 * x**2 + 3 * x - 1, x)) == [1, 1, 1]

    # valid for arbitrary y (issue 21263)
    r = root(y, 3)
    assert roots_cubic(Poly(x**3 - y, x)) == [
        r, r * (-S.Half + sqrt(3) * I / 2), r * (-S.Half - sqrt(3) * I / 2)
    ]
    # simpler form when y is negative
    assert roots_cubic(Poly(x**3 - -1, x)) == \
        [-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]
    assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \
         S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2
    eq = -x**3 + 2 * x**2 + 3 * x - 2
    assert roots(eq, trig=True, multiple=True) == \
           roots_cubic(Poly(eq, x), trig=True) == [
        Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3,
        -2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3),
        -2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3),
        ]
Пример #34
0
def make_int_pow_prob(var="x", order=3):
    """
    Generates a n-order polynomial to be integrated.

    x : charector for the variable to be solved for. defaults to "x".
                            OR
        a list of possible charectors. A random selection will be made from them.
    n : order of the polynomial or a list of possible orders. Defaults to 3.
        A random selection will be made from them.

    """
    if isinstance(var, str):
        var = sympy.Symbol(var, positive=True)
    elif isinstance(var, list):
        var = sympy.Symbol(random.choice(var), positive=True)
    if isinstance(order, list):
        order = random.choice(order)
    eq = 0;
    sol = 0;
    length = random.randint(1,3)
    for i in range(1,length+1):
        a = random.randint(1,10)*random.choice([-1,1])
        b = random.randint(1,10)
        n = random.randint(1,5)
        while (not n%order):
            n = random.randint(1,5)
        if (True):
            sign = random.choice([-1,1])
            eq += sympy.Rational(a,b)*(var**sympy.Rational(n,order))**sign
            sol+= sympy.Rational(a*(n*sign+order),b*order)*(var**sympy.Rational(n*sign+order,order))
        else:
            eq += (sympy.Rational(a,b)*sympy.root(var**n,order))**random.choice([-1,1])
    
    sol = sympy.latex(sol)
    eq = sympy.latex(sympy.Integral(eq, var))
    eq = 'd'.join(eq.split("\\partial"))
    eq = "$$" + eq + "$$"
    sol = "$$" + sol + " + C $$"
    return eq, sol
Пример #35
0
def test_sqrtdenest():
    d = {
        sqrt(5 + 2 * sqrt(6)):
        sqrt(2) + sqrt(3),
        sqrt(sqrt(2)):
        sqrt(sqrt(2)),
        sqrt(5 + sqrt(7)):
        sqrt(5 + sqrt(7)),
        sqrt(3 + sqrt(5 + 2 * sqrt(7))):
        sqrt(6 + 3 * sqrt(7)) / (sqrt(2) *
                                 (5 + 2 * sqrt(7))**Rational(1, 4)) + 3 *
        (5 + 2 * sqrt(7))**Rational(1, 4) / (sqrt(2) * sqrt(6 + 3 * sqrt(7))),
        sqrt(3 + 2 * sqrt(3)):
        3**Rational(1, 4) / sqrt(2) + 3 / (sqrt(2) * 3**Rational(1, 4))
    }
    for i in d:
        assert sqrtdenest(i) == d[i] or denester([i])[0] == d[i]

    # this test caused a pattern recognition failure in sqrtdenest
    # nest = sqrt(2) + sqrt(5) - sqrt(7)
    nest = symbols('nest')
    x0, x1, x2, x3, x4, x5, x6 = symbols('x:7')
    l = sqrt(2) + sqrt(5)
    r = sqrt(7) + nest
    s = (l**2 - r**2).expand() + nest**2  # == nest**2
    ok = solve(nest**4 - s**2,
               nest)[1]  # this will change if results order changes
    assert abs((l - r).subs(nest, ok).n()) < 1e-12
    x0 = sqrt(3)
    x2 = root(45 * I * x0 - 28, 3)
    x3 = 19 / x2
    x4 = x2 + x3
    x5 = -x4 - 14
    x6 = sqrt(-x5)
    ans = -x0 * x6 / 3 + x0 * sqrt(-x4 + 28 - 6 * sqrt(210) * x6 / x5) / 3
    assert expand_mul(radsimp(ok) - ans) == 0
    # issue 2554
    eq = sqrt(sqrt(sqrt(2) + 2) + 2)
    assert sqrtdenest(eq) == eq
Пример #36
0
def convert_func(func):
    if func.func_normal():
        if func.L_PAREN():  # function called with parenthesis
            arg = convert_func_arg(func.func_arg())
        else:
            arg = convert_func_arg(func.func_arg_noparens())

        name = func.func_normal().start.text[1:]

        # change arc<trig> -> a<trig>
        if name in [
                "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
        ]:
            name = "a" + name[3:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)
        if name in ["arsinh", "arcosh", "artanh"]:
            name = "a" + name[2:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if name == "exp":
            expr = sympy.exp(arg, evaluate=False)

        if (name == "log" or name == "ln"):
            if func.subexpr():
                if func.subexpr().expr():
                    base = convert_expr(func.subexpr().expr())
                else:
                    base = convert_atom(func.subexpr().atom())
            elif name == "log":
                base = 10
            elif name == "ln":
                base = sympy.E
            expr = sympy.log(arg, base, evaluate=False)

        func_pow = None
        should_pow = True
        if func.supexpr():
            if func.supexpr().expr():
                func_pow = convert_expr(func.supexpr().expr())
            else:
                func_pow = convert_atom(func.supexpr().atom())

        if name in [
                "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
                "tanh"
        ]:
            if func_pow == -1:
                name = "a" + name
                should_pow = False
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if func_pow and should_pow:
            expr = sympy.Pow(expr, func_pow, evaluate=False)

        return expr
    elif func.LETTER() or func.SYMBOL():
        if func.LETTER():
            fname = func.LETTER().getText()
        elif func.SYMBOL():
            fname = func.SYMBOL().getText()[1:]
        fname = str(fname)  # can't be unicode
        if func.subexpr():
            subscript = None
            if func.subexpr().expr():  # subscript is expr
                subscript = convert_expr(func.subexpr().expr())
            else:  # subscript is atom
                subscript = convert_atom(func.subexpr().atom())
            subscriptName = StrPrinter().doprint(subscript)
            fname += '_{' + subscriptName + '}'
        input_args = func.args()
        output_args = []
        while input_args.args():  # handle multiple arguments to function
            output_args.append(convert_expr(input_args.expr()))
            input_args = input_args.args()
        output_args.append(convert_expr(input_args.expr()))
        return sympy.Function(fname)(*output_args)
    elif func.FUNC_INT():
        return handle_integral(func)
    elif func.FUNC_SQRT():
        expr = convert_expr(func.base)
        if func.root:
            r = convert_expr(func.root)
            return sympy.root(expr, r, evaluate=False)
        else:
            return sympy.sqrt(expr, evaluate=False)
    elif func.FUNC_OVERLINE():
        expr = convert_expr(func.base)
        return sympy.conjugate(expr, evaluate=False)
    elif func.FUNC_SUM():
        return handle_sum_or_prod(func, "summation")
    elif func.FUNC_PROD():
        return handle_sum_or_prod(func, "product")
    elif func.FUNC_LIM():
        return handle_limit(func)
Пример #37
0
def test_slow_general_univariate():
    r = rootof(x**5 - x**2 + 1, 0)
    assert solve(sqrt(x) + 1/root(x, 3) > 1) == \
        Or(And(S(0) < x, x < r**6), And(r**6 < x, x < oo))
Пример #38
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == r'f{\left (x \right )}'
    assert latex(f) == r'f'

    g = Function('g')
    assert latex(g(x, y)) == r'g{\left (x,y \right )}'
    assert latex(g) == r'g'

    h = Function('h')
    assert latex(h(x, y, z)) == r'h{\left (x,y,z \right )}'
    assert latex(h) == r'h'

    Li = Function('Li')
    assert latex(Li) == r'\operatorname{Li}'
    assert latex(Li(x)) == r'\operatorname{Li}{\left (x \right )}'

    beta = Function('beta')

    # not to be confused with the beta function
    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(beta) == r"\beta"

    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(
        FallingFactorial(3, k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\left\lvert{x}\right\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(
        polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(elliptic_k(z)) == r"K\left(z\right)"
    assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)"
    assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)"
    assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)"
    assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)"
    assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)"
    assert latex(elliptic_e(z)) == r"E\left(z\right)"
    assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)"
    assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)"
    assert latex(elliptic_pi(x, y, z)**2) == \
        r"\Pi^{2}\left(x; y\middle| z\right)"
    assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)"
    assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}', latex(Chi(x)**2)

    assert latex(
        jacobi(n, a, b, x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(n, a, b, x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(
        gegenbauer(n, a, x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(n, a, x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(
        chebyshevt(n, x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(
        chebyshevu(n, x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(
        assoc_legendre(n, a, x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(n, a, x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(
        assoc_laguerre(n, a, x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(n, a, x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    theta = Symbol("theta", real=True)
    phi = Symbol("phi", real=True)
    assert latex(Ynm(n,m,theta,phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)'
    assert latex(Ynm(n, m, theta, phi)**3) == r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
    assert latex(Znm(n,m,theta,phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)'
    assert latex(Znm(n, m, theta, phi)**3) == r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(
        0)**3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"

    assert latex(totient(n)) == r'\phi\left( n \right)'

    # some unknown function name should get rendered with \operatorname
    fjlkd = Function('fjlkd')
    assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left (x \right )}'
    # even when it is referred to without an argument
    assert latex(fjlkd) == r'\operatorname{fjlkd}'
Пример #39
0
def test_roots0():
    assert roots(1, x) == {}
    assert roots(x, x) == {S.Zero: 1}
    assert roots(x**9, x) == {S.Zero: 9}
    assert roots(((x - 2) * (x + 3) * (x - 4)).expand(), x) == {
        -S(3): 1,
        S(2): 1,
        S(4): 1
    }

    assert roots(2 * x + 1, x) == {Rational(-1, 2): 1}
    assert roots((2 * x + 1)**2, x) == {Rational(-1, 2): 2}
    assert roots((2 * x + 1)**5, x) == {Rational(-1, 2): 5}
    assert roots((2 * x + 1)**10, x) == {Rational(-1, 2): 10}

    assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1}
    assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2}

    assert roots(((2 * x - 3)**2).expand(), x) == {Rational(3, 2): 2}
    assert roots(((2 * x + 3)**2).expand(), x) == {Rational(-3, 2): 2}

    assert roots(((2 * x - 3)**3).expand(), x) == {Rational(3, 2): 3}
    assert roots(((2 * x + 3)**3).expand(), x) == {Rational(-3, 2): 3}

    assert roots(((2 * x - 3)**5).expand(), x) == {Rational(3, 2): 5}
    assert roots(((2 * x + 3)**5).expand(), x) == {Rational(-3, 2): 5}

    assert roots(((a * x - b)**5).expand(), x) == {b / a: 5}
    assert roots(((a * x + b)**5).expand(), x) == {-b / a: 5}

    assert roots(x**2 + (-a - 1) * x + a, x) == {a: 1, S.One: 1}

    assert roots(x**4 - 2 * x**2 + 1, x) == {S.One: 2, S.NegativeOne: 2}

    assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \
        {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1}

    assert roots(x**8 - 1, x) == {
        sqrt(2) / 2 + I * sqrt(2) / 2: 1,
        sqrt(2) / 2 - I * sqrt(2) / 2: 1,
        -sqrt(2) / 2 + I * sqrt(2) / 2: 1,
        -sqrt(2) / 2 - I * sqrt(2) / 2: 1,
        S.One: 1,
        -S.One: 1,
        I: 1,
        -I: 1
    }

    f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \
        224*x**7 - 384*x**8 - 64*x**9

    assert roots(f) == {
        S.Zero: 2,
        -S(2): 2,
        S(2): 1,
        Rational(-7, 2): 1,
        Rational(-3, 2): 1,
        Rational(-1, 2): 1,
        Rational(3, 2): 1
    }

    assert roots((a + b + c) * x - (a + b + c + d), x) == {
        (a + b + c + d) / (a + b + c): 1
    }

    assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {}
    assert roots(((x - 2) * (x + 3) * (x - 4)).expand(), x, cubics=False) == {
        -S(3): 1,
        S(2): 1,
        S(4): 1
    }
    assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \
        {-S(3): 1, S(2): 1, S(4): 1, S(5): 1}
    assert roots(x**3 + 2 * x**2 + 4 * x + 8, x) == {
        -S(2): 1,
        -2 * I: 1,
        2 * I: 1
    }
    assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \
        {-2*I: 1, 2*I: 1, -S(2): 1}
    assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \
        {S.One: 1, S.Zero: 1, -S(2): 1, -2*I: 1, 2*I: 1}

    r1_2, r1_3 = S.Half, Rational(1, 3)

    x0 = (3 * sqrt(33) + 19)**r1_3
    x1 = 4 / x0 / 3
    x2 = x0 / 3
    x3 = sqrt(3) * I / 2
    x4 = x3 - r1_2
    x5 = -x3 - r1_2
    assert roots(x**3 + x**2 - x + 1, x, cubics=True) == {
        -x1 - x2 - r1_3: 1,
        -x1 / x4 - x2 * x4 - r1_3: 1,
        -x1 / x5 - x2 * x5 - r1_3: 1,
    }

    f = (x**2 + 2 * x + 3).subs(x, 2 * x**2 + 3 * x).subs(x, 5 * x - 4)

    r13_20, r1_20 = [Rational(*r) for r in ((13, 20), (1, 20))]

    s2 = sqrt(2)
    assert roots(f, x) == {
        r13_20 + r1_20 * sqrt(1 - 8 * I * s2): 1,
        r13_20 - r1_20 * sqrt(1 - 8 * I * s2): 1,
        r13_20 + r1_20 * sqrt(1 + 8 * I * s2): 1,
        r13_20 - r1_20 * sqrt(1 + 8 * I * s2): 1,
    }

    f = x**4 + x**3 + x**2 + x + 1

    r1_4, r1_8, r5_8 = [Rational(*r) for r in ((1, 4), (1, 8), (5, 8))]

    assert roots(f, x) == {
        -r1_4 + r1_4 * 5**r1_2 + I * (r5_8 + r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 + r1_4 * 5**r1_2 - I * (r5_8 + r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 - r1_4 * 5**r1_2 + I * (r5_8 - r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 - r1_4 * 5**r1_2 - I * (r5_8 - r1_8 * 5**r1_2)**r1_2: 1,
    }

    f = z**3 + (-2 - y) * z**2 + (1 + 2 * y - 2 * x**2) * z - y + 2 * x**2

    assert roots(f, z) == {
        S.One: 1,
        S.Half + S.Half * y + S.Half * sqrt(1 - 2 * y + y**2 + 8 * x**2): 1,
        S.Half + S.Half * y - S.Half * sqrt(1 - 2 * y + y**2 + 8 * x**2): 1,
    }

    assert roots(a * b * c * x**3 + 2 * x**2 + 4 * x + 8, x,
                 cubics=False) == {}
    assert roots(a * b * c * x**3 + 2 * x**2 + 4 * x + 8, x, cubics=True) != {}

    assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1}
    assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1}

    assert roots((x - 1) * (x + 1), x) == {S.One: 1, -S.One: 1}
    assert roots((x - 1) * (x + 1), x, predicate=lambda r: r.is_positive) == {
        S.One: 1
    }

    assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One]
    assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I]

    ar, br = symbols('a, b', real=True)
    p = x**2 * (ar - br)**2 + 2 * x * (br - ar) + 1
    assert roots(p, x, filter='R') == {1 / (ar - br): 2}

    assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero]
    assert roots(1234, x, multiple=True) == []

    f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1

    assert roots(f) == {
        -I * sin(pi / 7) + cos(pi / 7): 1,
        -I * sin(pi * Rational(2, 7)) - cos(pi * Rational(2, 7)): 1,
        -I * sin(pi * Rational(3, 7)) + cos(pi * Rational(3, 7)): 1,
        I * sin(pi / 7) + cos(pi / 7): 1,
        I * sin(pi * Rational(2, 7)) - cos(pi * Rational(2, 7)): 1,
        I * sin(pi * Rational(3, 7)) + cos(pi * Rational(3, 7)): 1,
    }

    g = ((x**2 + 1) * f**2).expand()

    assert roots(g) == {
        -I * sin(pi / 7) + cos(pi / 7): 2,
        -I * sin(pi * Rational(2, 7)) - cos(pi * Rational(2, 7)): 2,
        -I * sin(pi * Rational(3, 7)) + cos(pi * Rational(3, 7)): 2,
        I * sin(pi / 7) + cos(pi / 7): 2,
        I * sin(pi * Rational(2, 7)) - cos(pi * Rational(2, 7)): 2,
        I * sin(pi * Rational(3, 7)) + cos(pi * Rational(3, 7)): 2,
        -I: 1,
        I: 1,
    }

    r = roots(x**3 + 40 * x + 64)
    real_root = [rx for rx in r if rx.is_real][0]
    cr = 108 + 6 * sqrt(1074)
    assert real_root == -2 * root(cr, 3) / 3 + 20 / root(cr, 3)

    eq = Poly((7 + 5 * sqrt(2)) * x**3 + (-6 - 4 * sqrt(2)) * x**2 +
              (-sqrt(2) - 1) * x + 2,
              x,
              domain='EX')
    assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2 * sqrt(2): 1, -sqrt(2) + 1: 1}

    eq = Poly(41 * x**5 + 29 * sqrt(2) * x**5 - 153 * x**4 -
              108 * sqrt(2) * x**4 + 175 * x**3 + 125 * sqrt(2) * x**3 -
              45 * x**2 - 30 * sqrt(2) * x**2 - 26 * sqrt(2) * x - 26 * x + 24,
              x,
              domain='EX')
    assert roots(eq) == {
        -sqrt(2) + 1: 1,
        -2 + 2 * sqrt(2): 1,
        -1 + sqrt(2): 1,
        -4 + 4 * sqrt(2): 1,
        -3 + 3 * sqrt(2): 1
    }

    eq = Poly(x**3 - 2 * x**2 + 6 * sqrt(2) * x**2 - 8 * sqrt(2) * x + 23 * x -
              14 + 14 * sqrt(2),
              x,
              domain='EX')
    assert roots(eq) == {
        -2 * sqrt(2) + 2: 1,
        -2 * sqrt(2) + 1: 1,
        -2 * sqrt(2) - 1: 1
    }

    assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \
        {-sqrt(2) + root(7, 3)*(-S.Half - sqrt(3)*I/2): 1,
         -sqrt(2) + root(7, 3)*(-S.Half + sqrt(3)*I/2): 1,
         -sqrt(2) + root(7, 3): 1}
Пример #40
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function("f")
    assert latex(f(x)) == "\\operatorname{f}{\\left (x \\right )}"

    beta = Function("beta")

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2 * x ** 2), fold_func_brackets=True) == r"\sin {2 x^{2}}"
    assert latex(sin(x ** 2), fold_func_brackets=True) == r"\sin {x^{2}}"

    assert latex(asin(x) ** 2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x) ** 2, inv_trig_style="full") == r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x) ** 2, inv_trig_style="power") == r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x ** 2), inv_trig_style="power", fold_func_brackets=True) == r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x ** 3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y) ** 2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x ** 3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y) ** 2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r"\gamma\left(x, y\right)"
    assert latex(uppergamma(x, y)) == r"\Gamma\left(x, y\right)"

    assert latex(cot(x)) == r"\cot{\left (x \right )}"
    assert latex(coth(x)) == r"\coth{\left (x \right )}"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(root(x, y)) == r"x^{\frac{1}{y}}"
    assert latex(arg(x)) == r"\arg{\left (x \right )}"
    assert latex(zeta(x)) == r"\zeta\left(x\right)"

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x) ** 2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y) ** 2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x) ** 2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x, y) ** 2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n) ** 2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r"\operatorname{Ei}{\left (x \right )}"
    assert latex(Ei(x) ** 2) == r"\operatorname{Ei}^{2}{\left (x \right )}"
    assert latex(expint(x, y) ** 2) == r"\operatorname{E}_{x}^{2}\left(y\right)"
    assert latex(Shi(x) ** 2) == r"\operatorname{Shi}^{2}{\left (x \right )}"
    assert latex(Si(x) ** 2) == r"\operatorname{Si}^{2}{\left (x \right )}"
    assert latex(Ci(x) ** 2) == r"\operatorname{Ci}^{2}{\left (x \right )}"
    assert latex(Chi(x) ** 2) == r"\operatorname{Chi}^{2}{\left (x \right )}"

    assert latex(jacobi(n, a, b, x)) == r"P_{n}^{\left(a,b\right)}\left(x\right)"
    assert latex(jacobi(n, a, b, x) ** 2) == r"\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}"
    assert latex(gegenbauer(n, a, x)) == r"C_{n}^{\left(a\right)}\left(x\right)"
    assert latex(gegenbauer(n, a, x) ** 2) == r"\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(chebyshevt(n, x)) == r"T_{n}\left(x\right)"
    assert latex(chebyshevt(n, x) ** 2) == r"\left(T_{n}\left(x\right)\right)^{2}"
    assert latex(chebyshevu(n, x)) == r"U_{n}\left(x\right)"
    assert latex(chebyshevu(n, x) ** 2) == r"\left(U_{n}\left(x\right)\right)^{2}"
    assert latex(legendre(n, x)) == r"P_{n}\left(x\right)"
    assert latex(legendre(n, x) ** 2) == r"\left(P_{n}\left(x\right)\right)^{2}"
    assert latex(assoc_legendre(n, a, x)) == r"P_{n}^{\left(a\right)}\left(x\right)"
    assert latex(assoc_legendre(n, a, x) ** 2) == r"\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(laguerre(n, x)) == r"L_{n}\left(x\right)"
    assert latex(laguerre(n, x) ** 2) == r"\left(L_{n}\left(x\right)\right)^{2}"
    assert latex(assoc_laguerre(n, a, x)) == r"L_{n}^{\left(a\right)}\left(x\right)"
    assert latex(assoc_laguerre(n, a, x) ** 2) == r"\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}"
    assert latex(hermite(n, x)) == r"H_{n}\left(x\right)"
    assert latex(hermite(n, x) ** 2) == r"\left(H_{n}\left(x\right)\right)^{2}"

    # Test latex printing of function names with "_"
    assert latex(polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0) ** 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Пример #41
0
def test_radsimp():
    r2 = sqrt(2)
    r3 = sqrt(3)
    r5 = sqrt(5)
    r7 = sqrt(7)
    assert fraction(radsimp(1/r2)) == (sqrt(2), 2)
    assert radsimp(1/(1 + r2)) == \
        -1 + sqrt(2)
    assert radsimp(1/(r2 + r3)) == \
        -sqrt(2) + sqrt(3)
    assert fraction(radsimp(1/(1 + r2 + r3))) == \
        (-sqrt(6) + sqrt(2) + 2, 4)
    assert fraction(radsimp(1/(r2 + r3 + r5))) == \
        (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12)
    assert fraction(radsimp(1/(1 + r2 + r3 + r5))) == (
        (-34*sqrt(10) - 26*sqrt(15) - 55*sqrt(3) - 61*sqrt(2) + 14*sqrt(30) +
        93 + 46*sqrt(6) + 53*sqrt(5), 71))
    assert fraction(radsimp(1/(r2 + r3 + r5 + r7))) == (
        (-50*sqrt(42) - 133*sqrt(5) - 34*sqrt(70) - 145*sqrt(3) + 22*sqrt(105)
        + 185*sqrt(2) + 62*sqrt(30) + 135*sqrt(7), 215))
    z = radsimp(1/(1 + r2/3 + r3/5 + r5 + r7))
    assert len((3616791619821680643598*z).args) == 16
    assert radsimp(1/z) == 1/z
    assert radsimp(1/z, max_terms=20).expand() == 1 + r2/3 + r3/5 + r5 + r7
    assert radsimp(1/(r2*3)) == \
        sqrt(2)/6
    assert radsimp(1/(r2*a + r3 + r5 + r7)) == (
        (8*sqrt(2)*a**7 - 8*sqrt(7)*a**6 - 8*sqrt(5)*a**6 - 8*sqrt(3)*a**6 -
        180*sqrt(2)*a**5 + 8*sqrt(30)*a**5 + 8*sqrt(42)*a**5 + 8*sqrt(70)*a**5
        - 24*sqrt(105)*a**4 + 84*sqrt(3)*a**4 + 100*sqrt(5)*a**4 +
        116*sqrt(7)*a**4 - 72*sqrt(70)*a**3 - 40*sqrt(42)*a**3 -
        8*sqrt(30)*a**3 + 782*sqrt(2)*a**3 - 462*sqrt(3)*a**2 -
        302*sqrt(7)*a**2 - 254*sqrt(5)*a**2 + 120*sqrt(105)*a**2 -
        795*sqrt(2)*a - 62*sqrt(30)*a + 82*sqrt(42)*a + 98*sqrt(70)*a -
        118*sqrt(105) + 59*sqrt(7) + 295*sqrt(5) + 531*sqrt(3))/(16*a**8 -
        480*a**6 + 3128*a**4 - 6360*a**2 + 3481))
    assert radsimp(1/(r2*a + r2*b + r3 + r7)) == (
        (sqrt(2)*a*(a + b)**2 - 5*sqrt(2)*a + sqrt(42)*a + sqrt(2)*b*(a +
        b)**2 - 5*sqrt(2)*b + sqrt(42)*b - sqrt(7)*(a + b)**2 - sqrt(3)*(a +
        b)**2 - 2*sqrt(3) + 2*sqrt(7))/(2*a**4 + 8*a**3*b + 12*a**2*b**2 -
        20*a**2 + 8*a*b**3 - 40*a*b + 2*b**4 - 20*b**2 + 8))
    assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \
        sqrt(2)/(2*a + 2*b + 2*c + 2*d)
    assert radsimp(1/(1 + r2*a + r2*b + r2*c + r2*d)) == (
        (sqrt(2)*a + sqrt(2)*b + sqrt(2)*c + sqrt(2)*d - 1)/(2*a**2 + 4*a*b +
        4*a*c + 4*a*d + 2*b**2 + 4*b*c + 4*b*d + 2*c**2 + 4*c*d + 2*d**2 - 1))
    assert radsimp((y**2 - x)/(y - sqrt(x))) == \
        sqrt(x) + y
    assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \
        -(sqrt(x) + y)
    assert radsimp(1/(1 - I + a*I)) == \
        (-I*a + 1 + I)/(a**2 - 2*a + 2)
    assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \
        (-x - sqrt(y))/((x - y)*(x**2 - y))
    e = (3 + 3*sqrt(2))*x*(3*x - 3*sqrt(y))
    assert radsimp(e) == x*(3 + 3*sqrt(2))*(3*x - 3*sqrt(y))
    assert radsimp(1/e) == (
        (-9*x + 9*sqrt(2)*x - 9*sqrt(y) + 9*sqrt(2)*sqrt(y))/(9*x*(9*x**2 -
        9*y)))
    assert radsimp(1 + 1/(1 + sqrt(3))) == \
        Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1
    A = symbols("A", commutative=False)
    assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \
        x**2 + sqrt(2)*x**2 - sqrt(2)*x*A
    assert radsimp(1/sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3)
    assert radsimp(1/sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3

    # issue 6532
    assert fraction(radsimp(1/sqrt(x))) == (sqrt(x), x)
    assert fraction(radsimp(1/sqrt(2*x + 3))) == (sqrt(2*x + 3), 2*x + 3)
    assert fraction(radsimp(1/sqrt(2*(x + 3)))) == (sqrt(2*x + 6), 2*x + 6)

    # issue 5994
    e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/'
        '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))')
    assert radsimp(e).expand() == -2*2**(S(3)/4) - 2*2**(S(1)/4) + 2 + 2*sqrt(2)

    # issue 5986 (modifications to radimp didn't initially recognize this so
    # the test is included here)
    assert radsimp(1/(-sqrt(5)/2 - S(1)/2 + (-sqrt(5)/2 - S(1)/2)**2)) == 1

    # from issue 5934
    eq = (
        (-240*sqrt(2)*sqrt(sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) -
        360*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) -
        120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) +
        120*sqrt(2)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) +
        120*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5) +
        120*sqrt(10)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) +
        120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5))/(-36000 -
        7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
        24*sqrt(10)*sqrt(-sqrt(5) + 5))**2))
    assert radsimp(eq) is S.NaN  # it's 0/0

    # work with normal form
    e = 1/sqrt(sqrt(7)/7 + 2*sqrt(2) + 3*sqrt(3) + 5*sqrt(5)) + 3
    assert radsimp(e) == (
        -sqrt(sqrt(7) + 14*sqrt(2) + 21*sqrt(3) +
        35*sqrt(5))*(-11654899*sqrt(35) - 1577436*sqrt(210) - 1278438*sqrt(15)
        - 1346996*sqrt(10) + 1635060*sqrt(6) + 5709765 + 7539830*sqrt(14) +
        8291415*sqrt(21))/1300423175 + 3)

    # obey power rules
    base = sqrt(3) - sqrt(2)
    assert radsimp(1/base**3) == (sqrt(3) + sqrt(2))**3
    assert radsimp(1/(-base)**3) == -(sqrt(2) + sqrt(3))**3
    assert radsimp(1/(-base)**x) == (-base)**(-x)
    assert radsimp(1/base**x) == (sqrt(2) + sqrt(3))**x
    assert radsimp(root(1/(-1 - sqrt(2)), -x)) == (-1)**(-1/x)*(1 + sqrt(2))**(1/x)

    # recurse
    e = cos(1/(1 + sqrt(2)))
    assert radsimp(e) == cos(-sqrt(2) + 1)
    assert radsimp(e/2) == cos(-sqrt(2) + 1)/2
    assert radsimp(1/e) == 1/cos(-sqrt(2) + 1)
    assert radsimp(2/e) == 2/cos(-sqrt(2) + 1)
    assert fraction(radsimp(e/sqrt(x))) == (sqrt(x)*cos(-sqrt(2)+1), x)

    # test that symbolic denominators are not processed
    r = 1 + sqrt(2)
    assert radsimp(x/r, symbolic=False) == -x*(-sqrt(2) + 1)
    assert radsimp(x/(y + r), symbolic=False) == x/(y + 1 + sqrt(2))
    assert radsimp(x/(y + r)/r, symbolic=False) == \
        -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2))

    # issue 7408
    eq = sqrt(x)/sqrt(y)
    assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1/y)
    assert radsimp(eq, symbolic=False) == eq

    # issue 7498
    assert radsimp(sqrt(x)/sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1/y**3)

    # for coverage
    eq = sqrt(x)/y**2
    assert radsimp(eq) == eq
Пример #42
0
def test_AlgebraicNumber():
    a = AlgebraicNumber(sqrt(2))
    sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])")
    a = AlgebraicNumber(root(-2, 3))
    sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])")
Пример #43
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re {\left (x + y \right )}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    # Test latex printing of function names with "_"
    assert latex(polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Пример #44
0
def test_powsimp():
    x, y, z, n = symbols('x,y,z,n')
    f = Function('f')
    assert powsimp( 4**x * 2**(-x) * 2**(-x) ) == 1
    assert powsimp( (-4)**x * (-2)**(-x) * 2**(-x) ) == 1

    assert powsimp(
        f(4**x * 2**(-x) * 2**(-x)) ) == f(4**x * 2**(-x) * 2**(-x))
    assert powsimp( f(4**x * 2**(-x) * 2**(-x)), deep=True ) == f(1)
    assert exp(x)*exp(y) == exp(x)*exp(y)
    assert powsimp(exp(x)*exp(y)) == exp(x + y)
    assert powsimp(exp(x)*exp(y)*2**x*2**y) == (2*E)**(x + y)
    assert powsimp(exp(x)*exp(y)*2**x*2**y, combine='exp') == \
        exp(x + y)*2**(x + y)
    assert powsimp(exp(x)*exp(y)*exp(2)*sin(x) + sin(y) + 2**x*2**y) == \
        exp(2 + x + y)*sin(x) + sin(y) + 2**(x + y)
    assert powsimp(sin(exp(x)*exp(y))) == sin(exp(x)*exp(y))
    assert powsimp(sin(exp(x)*exp(y)), deep=True) == sin(exp(x + y))
    assert powsimp(x**2*x**y) == x**(2 + y)
    # This should remain factored, because 'exp' with deep=True is supposed
    # to act like old automatic exponent combining.
    assert powsimp((1 + E*exp(E))*exp(-E), combine='exp', deep=True) == \
        (1 + exp(1 + E))*exp(-E)
    assert powsimp((1 + E*exp(E))*exp(-E), deep=True) == \
        (1 + exp(1 + E))*exp(-E)
    assert powsimp((1 + E*exp(E))*exp(-E)) == (1 + exp(1 + E))*exp(-E)
    assert powsimp((1 + E*exp(E))*exp(-E), combine='exp') == \
        (1 + exp(1 + E))*exp(-E)
    assert powsimp((1 + E*exp(E))*exp(-E), combine='base') == \
        (1 + E*exp(E))*exp(-E)
    x, y = symbols('x,y', nonnegative=True)
    n = Symbol('n', real=True)
    assert powsimp(y**n * (y/x)**(-n)) == x**n
    assert powsimp(x**(x**(x*y)*y**(x*y))*y**(x**(x*y)*y**(x*y)), deep=True) \
        == (x*y)**(x*y)**(x*y)
    assert powsimp(2**(2**(2*x)*x), deep=False) == 2**(2**(2*x)*x)
    assert powsimp(2**(2**(2*x)*x), deep=True) == 2**(x*4**x)
    assert powsimp(
        exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \
        exp(-x + exp(-x)*exp(-x*log(x)))
    assert powsimp(
        exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \
        exp(-x + exp(-x)*exp(-x*log(x)))
    assert powsimp((x + y)/(3*z), deep=False, combine='exp') == (x + y)/(3*z)
    assert powsimp((x/3 + y/3)/z, deep=True, combine='exp') == (x/3 + y/3)/z
    assert powsimp(exp(x)/(1 + exp(x)*exp(y)), deep=True) == \
        exp(x)/(1 + exp(x + y))
    assert powsimp(x*y**(z**x*z**y), deep=True) == x*y**(z**(x + y))
    assert powsimp((z**x*z**y)**x, deep=True) == (z**(x + y))**x
    assert powsimp(x*(z**x*z**y)**x, deep=True) == x*(z**(x + y))**x
    p = symbols('p', positive=True)
    assert powsimp((1/x)**log(2)/x) == (1/x)**(1 + log(2))
    assert powsimp((1/p)**log(2)/p) == p**(-1 - log(2))

    # coefficient of exponent can only be simplified for positive bases
    assert powsimp(2**(2*x)) == 4**x
    assert powsimp((-1)**(2*x)) == (-1)**(2*x)
    i = symbols('i', integer=True)
    assert powsimp((-1)**(2*i)) == 1
    assert powsimp((-1)**(-x)) != (-1)**x  # could be 1/((-1)**x), but is not
    # force=True overrides assumptions
    assert powsimp((-1)**(2*x), force=True) == 1

    # rational exponents allow combining of negative terms
    w, n, m = symbols('w n m', negative=True)
    e = i/a  # not a rational exponent if `a` is unknown
    ex = w**e*n**e*m**e
    assert powsimp(ex) == m**(i/a)*n**(i/a)*w**(i/a)
    e = i/3
    ex = w**e*n**e*m**e
    assert powsimp(ex) == (-1)**i*(-m*n*w)**(i/3)
    e = (3 + i)/i
    ex = w**e*n**e*m**e
    assert powsimp(ex) == (-1)**(3*e)*(-m*n*w)**e

    eq = x**(2*a/3)
    # eq != (x**a)**(2/3) (try x = -1 and a = 3 to see)
    assert powsimp(eq).exp == eq.exp == 2*a/3
    # powdenest goes the other direction
    assert powsimp(2**(2*x)) == 4**x

    assert powsimp(exp(p/2)) == exp(p/2)

    # issue 6368
    eq = Mul(*[sqrt(Dummy(imaginary=True)) for i in range(3)])
    assert powsimp(eq) == eq and eq.is_Mul

    assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2)))

    # issue 8836
    assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)'
objs = Backend.objs
trigUnit = TrigUnit.Radians

Backend.engineFunction("=", lambda op: sympy.N(op), operands=1)

Backend.engineFunction("+", lambda op: op[0] + op[1])
Backend.engineFunction("-", lambda op: op[0] - op[1])
Backend.engineFunction("^", lambda op: op[0] ** op[1])
Backend.engineFunction("10^x", lambda op: 10 ** op, operands=1)
Backend.engineFunction("x^2", lambda op: op ** 2, operands=1)
Backend.engineFunction("neg", lambda op: op * -1, operands=1)
Backend.engineFunction("simplify", lambda op: sympy.simplify(op), operands=1)
Backend.engineFunction("%", lambda op: op[0] * op[1] / 100)
Backend.engineFunction("inv", lambda op: 1 / op, operands=1)
Backend.engineFunction("sqrt", lambda op: sympy.sqrt(op), operands=1)
Backend.engineFunction("nthroot", lambda op: sympy.root(op[0], op[1]))
Backend.engineFunction("log", lambda op: sympy.log(op[0], 10), operands=1)
Backend.engineFunction("ln", lambda op: sympy.log(op), operands=1)
Backend.engineFunction("e^x", lambda op: sympy.exp(op), operands=1)
Backend.engineFunction("factorial", lambda op: sympy.factorial(op), operands=1)

@Backend.engineFunction(operands=2)
def mul(op):
    expr = None
    if issubclass(type(op[1]), functions.Dice):
        expr = op[1] * op[0] # Force use of Dice __mul__ function
    else:
        expr = op[0] * op[1]
    return expr

@Backend.engineFunction(operands=2)
Пример #46
0
def root3(x):
    return root(x, 3)
Пример #47
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(subfactorial(k)) == r"!k"
    assert latex(subfactorial(-k)) == r"!\left(- k\right)"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x,
                         y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    assert latex(jacobi(n, a, b,
                        x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(
        n, a, b,
        x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(gegenbauer(n, a,
                            x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(
        n, a,
        x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(chebyshevt(n,
                            x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(chebyshevu(n,
                            x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_legendre(n, a,
                                x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(
        n, a,
        x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_laguerre(n, a,
                                x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(
        n, a,
        x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Пример #48
0
def root4(x):
    return root(x, 4)
Пример #49
0
def test_slow_general_univariate():
    r = rootof(x**5 - x**2 + 1, 0)
    assert solve(sqrt(x) + 1/root(x, 3) > 1) == \
        Or(And(S(0) < x, x < r**6), And(r**6 < x, x < oo))
Пример #50
0
def convert_func(func):
    if func.func_normal():
        if func.L_PAREN():  # function called with parenthesis
            arg = convert_func_arg(func.func_arg())
        else:
            arg = convert_func_arg(func.func_arg_noparens())

        name = func.func_normal().start.text[1:]

        # change arc<trig> -> a<trig>
        if name in [
                "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
        ]:
            name = "a" + name[3:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)
        if name in ["arsinh", "arcosh", "artanh"]:
            name = "a" + name[2:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if (name == "log" or name == "ln"):
            if func.subexpr():
                base = convert_expr(func.subexpr().expr())
            elif name == "log":
                base = 10
            elif name == "ln":
                base = sympy.E
            expr = sympy.log(arg, base, evaluate=False)

        func_pow = None
        should_pow = True
        if func.supexpr():
            if func.supexpr().expr():
                func_pow = convert_expr(func.supexpr().expr())
            else:
                func_pow = convert_atom(func.supexpr().atom())

        if name in [
                "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
                "tanh"
        ]:
            if func_pow == -1:
                name = "a" + name
                should_pow = False
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if func_pow and should_pow:
            expr = sympy.Pow(expr, func_pow, evaluate=False)

        return expr
    elif func.LETTER() or func.SYMBOL():
        if func.LETTER():
            fname = func.LETTER().getText()
        elif func.SYMBOL():
            fname = func.SYMBOL().getText()[1:]
        fname = str(fname)  # can't be unicode
        if func.subexpr():
            subscript = None
            if func.subexpr().expr():  # subscript is expr
                subscript = convert_expr(func.subexpr().expr())
            else:  # subscript is atom
                subscript = convert_atom(func.subexpr().atom())
            subscriptName = StrPrinter().doprint(subscript)
            fname += '_{' + subscriptName + '}'
        input_args = func.args()
        output_args = []
        while input_args.args():  # handle multiple arguments to function
            output_args.append(convert_expr(input_args.expr()))
            input_args = input_args.args()
        output_args.append(convert_expr(input_args.expr()))
        return sympy.Function(fname)(*output_args)
    elif func.FUNC_INT():
        return handle_integral(func)
    elif func.FUNC_SQRT():
        expr = convert_expr(func.base)
        if func.root:
            r = convert_expr(func.root)
            return sympy.root(expr, r)
        else:
            return sympy.sqrt(expr)
    elif func.FUNC_SUM():
        return handle_sum_or_prod(func, "summation")
    elif func.FUNC_PROD():
        return handle_sum_or_prod(func, "product")
    elif func.FUNC_LIM():
        return handle_limit(func)
Пример #51
0
def test_unrad():
    s = symbols('s', cls=Dummy)

    # checkers to deal with possibility of answer coming
    # back with a sign change (cf issue 2104)
    def check(rv, ans):
        rv, ans = list(rv), list(ans)
        rv[0] = rv[0].expand()
        ans[0] = ans[0].expand()
        return rv[0] in [ans[0], -ans[0]] and rv[1:] == ans[1:]

    def s_check(rv, ans):
        # get the dummy
        rv = list(rv)
        d = rv[0].atoms(Dummy)
        reps = zip(d, [s] * len(d))
        # replace s with this dummy
        rv = (rv[0].subs(reps).expand(), [
            (p[0].subs(reps), p[1].subs(reps)) for p in rv[1]
        ], [a.subs(reps) for a in rv[2]])
        ans = (ans[0].subs(reps).expand(), [
            (p[0].subs(reps), p[1].subs(reps)) for p in ans[1]
        ], [a.subs(reps) for a in ans[2]])
        return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
            str(rv[1:]) == str(ans[1:])

    assert check(unrad(sqrt(x)), (x, [], []))
    assert check(unrad(sqrt(x) + 1), (x - 1, [], []))
    assert s_check(unrad(sqrt(x) + x**Rational(1, 3) + 2),
                   (2 + s**2 + s**3, [(s, x - s**6)], []))
    assert check(unrad(sqrt(x) * x**Rational(1, 3) + 2), (x**5 - 64, [], []))
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
                 (x**3 - (x + 1)**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2 * x)),
                 (-2 * sqrt(2) * x - 2 * x + 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16 * x - 9, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
                 (-4 * x + 5 * x**2, [], []))
    assert check(unrad(a * sqrt(x) + b * sqrt(x) + c * sqrt(y) + d * sqrt(y)),
                 ((a * sqrt(x) + b * sqrt(x))**2 -
                  (c * sqrt(y) + d * sqrt(y))**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x)), (2 * x - 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
                 (9 * x + (x - 5)**2 - 9, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
                 (-5 * x**2 + 2 * x - 1, [], []))
    assert check(
        unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3),
        (-25 * x**4 - 376 * x**3 - 1256 * x**2 + 2272 * x - 784, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2 * x)),
                 (-41 * x**4 - 40 * x**3 - 232 * x**2 + 160 * x - 16, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1)), (S(1), [], []))

    eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
    assert check(unrad(eq), (16 * x**3 - 9 * x**2, [], []))
    assert set(solve(eq, check=False)) == set([S(0), S(9) / 16])
    assert solve(eq) == []
    # but this one really does have those solutions
    assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \
        set([S.Zero, S(9)/16])
    '''NOTE
    real_root changes the value of the result if the solution is
    simplified; `a` in the text below is the root that is not 4/5:
    >>> eq
    sqrt(x) + sqrt(-x + 1) + sqrt(x + 1) - 6*sqrt(5)/5
    >>> eq.subs(x, a).n()
    -0.e-123 + 0.e-127*I
    >>> real_root(eq.subs(x, a)).n()
    -0.e-123 + 0.e-127*I
    >>> (eq.subs(x,simplify(a))).n()
    -0.e-126
    >>> real_root(eq.subs(x, simplify(a))).n()
    0.194825975605452 + 2.15093623885838*I

    >>> sqrt(x).subs(x, real_root(a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, (a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, simplify(a)).n()
    0.809823827278194 - 5.32999467690853e-25*I
    >>> sqrt(x).subs(x, real_root(simplify(a))).n()
    0.49864610868139 + 1.44572604257047*I
    '''
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 +
    114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 +
    sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''')
    rb = S(4) / 5
    ans = solve(sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \
        len(ans) == 2 and \
        set([i.n(chop=True) for i in ans]) == \
        set([i.n(chop=True) for i in (ra, rb)])

    raises(ValueError,
           lambda: unrad(-root(x, 3)**2 + 2**pi * root(x, 3) - x + 2**pi))
    raises(ValueError,
           lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
    raises(ValueError,
           lambda: unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2 * sqrt(y)))
    # same as last but consider only y
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2 * sqrt(y), y),
                 (4 * y - (sqrt(x) + (x + 1)**(S(1) / 3))**2, [], []))
    assert check(unrad(sqrt(x / (1 - x)) + (x + 1)**Rational(1, 3)),
                 (x**3 / (-x + 1)**3 - (x + 1)**2, [], [(-x + 1)**3]))
    # same as last but consider only y; no y-containing denominators now
    assert s_check(unrad(sqrt(x / (1 - x)) + 2 * sqrt(y), y),
                   (x / (-x + 1) - 4 * y, [], []))
    assert check(unrad(sqrt(x) * sqrt(1 - x) + 2, x),
                 (x * (-x + 1) - 4, [], []))

    # http://tutorial.math.lamar.edu/
    #        Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
    assert solve(Eq(x, sqrt(x + 6))) == [3]
    assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
    assert solve(Eq(1, x + sqrt(2 * x - 3))) == []
    assert set(solve(Eq(sqrt(5 * x + 6) - 2, x))) == set([-S(1), S(2)])
    assert set(solve(Eq(sqrt(2 * x - 1) - sqrt(x - 4),
                        2))) == set([S(5), S(13)])
    assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
    # http://www.purplemath.com/modules/solverad.htm
    assert solve((2 * x - 5)**Rational(1, 3) - 3) == [16]
    assert solve((x**3 - 3 * x**2)**Rational(1, 3) + 1 - x) == []
    assert set(solve(x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4))) == \
        set([-S(1)/2, -S(1)/3])
    assert set(solve(sqrt(2 * x**2 - 7) - (3 - x))) == set([-S(8), S(2)])
    assert solve(sqrt(2 * x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
    assert solve(sqrt(x + 4) + sqrt(2 * x - 1) - 3 * sqrt(x - 1)) == [5]
    assert solve(sqrt(x) * sqrt(x - 7) - 12) == [16]
    assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
    assert solve(sqrt(9 * x**2 + 4) - (3 * x + 2)) == [0]
    assert solve(sqrt(x) - 2 - 5) == [49]
    assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
    assert solve(sqrt(x - 1) - x + 7) == [10]
    assert solve(sqrt(x - 2) - 5) == [27]
    assert solve(sqrt(17 * x - sqrt(x**2 - 5)) - 7) == [3]
    assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []

    # don't posify the expression in unrad and use _mexpand
    z = sqrt(2 * x + 1) / sqrt(x) - sqrt(2 + 1 / x)
    p = posify(z)[0]
    assert solve(p) == []
    assert solve(z) == []
    assert solve(z + 6 * I) == [-S(1) / 11]
    assert solve(p + 6 * I) == []

    eq = sqrt(2 + I) + 2 * I
    assert unrad(eq - x, x, all=True) == (x**4 + 4 * x**2 + 8 * x + 37, [], [])
    ans = (81 * x**8 - 2268 * x**6 - 4536 * x**5 + 22644 * x**4 +
           63216 * x**3 - 31608 * x**2 - 189648 * x + 141358, [], [])
    r = sqrt(sqrt(2) / 3 + 7)
    eq = sqrt(r) + r - x
    assert unrad(eq, all=1)
    r2 = sqrt(sqrt(2) + 21) / sqrt(3)
    assert r != r2 and r.equals(r2)
    assert unrad(eq - r + r2, all=True) == ans
Пример #52
0
def test_roots():
    assert roots(1, x) == {}
    assert roots(x, x) == {S.Zero: 1}
    assert roots(x**9, x) == {S.Zero: 9}
    assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-S(3): 1, S(2): 1, S(4): 1}

    assert roots(2*x + 1, x) == {-S.Half: 1}
    assert roots((2*x + 1)**2, x) == {-S.Half: 2}
    assert roots((2*x + 1)**5, x) == {-S.Half: 5}
    assert roots((2*x + 1)**10, x) == {-S.Half: 10}

    assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1}
    assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2}

    assert roots(((2*x - 3)**2).expand(), x) == { Rational(3, 2): 2}
    assert roots(((2*x + 3)**2).expand(), x) == {-Rational(3, 2): 2}

    assert roots(((2*x - 3)**3).expand(), x) == { Rational(3, 2): 3}
    assert roots(((2*x + 3)**3).expand(), x) == {-Rational(3, 2): 3}

    assert roots(((2*x - 3)**5).expand(), x) == { Rational(3, 2): 5}
    assert roots(((2*x + 3)**5).expand(), x) == {-Rational(3, 2): 5}

    assert roots(((a*x - b)**5).expand(), x) == { b/a: 5}
    assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5}

    assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, S.One: 1}

    assert roots(x**4 - 2*x**2 + 1, x) == {S.One: 2, -S.One: 2}

    assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \
        {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1}

    assert roots(x**8 - 1, x) == {
        sqrt(2)/2 + I*sqrt(2)/2: 1,
        sqrt(2)/2 - I*sqrt(2)/2: 1,
        -sqrt(2)/2 + I*sqrt(2)/2: 1,
        -sqrt(2)/2 - I*sqrt(2)/2: 1,
        S.One: 1, -S.One: 1, I: 1, -I: 1
    }

    f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \
        224*x**7 - 384*x**8 - 64*x**9

    assert roots(f) == {S(0): 2, -S(2): 2, S(2): 1, -S(7)/2: 1, -S(3)/2: 1, -S(1)/2: 1, S(3)/2: 1}

    assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1}

    assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {}
    assert roots(((x - 2)*(
        x + 3)*(x - 4)).expand(), x, cubics=False) == {-S(3): 1, S(2): 1, S(4): 1}
    assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \
        {-S(3): 1, S(2): 1, S(4): 1, S(5): 1}
    assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-S(2): 1, -2*I: 1, 2*I: 1}
    assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \
        {-2*I: 1, 2*I: 1, -S(2): 1}
    assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \
        {S(1): 1, S(0): 1, -S(2): 1, -2*I: 1, 2*I: 1}

    r1_2, r1_3, r1_9, r4_9, r19_27 = [ Rational(*r)
        for r in ((1, 2), (1, 3), (1, 9), (4, 9), (19, 27)) ]

    U = -r1_2 - r1_2*I*3**r1_2
    V = -r1_2 + r1_2*I*3**r1_2
    W = (r19_27 + r1_9*33**r1_2)**r1_3

    assert roots(x**3 + x**2 - x + 1, x, cubics=True) == {
        -r1_3 - U*W - r4_9*(U*W)**(-1): 1,
        -r1_3 - V*W - r4_9*(V*W)**(-1): 1,
        -r1_3 - W - r4_9*(  W)**(-1): 1,
    }

    f = (x**2 + 2*x + 3).subs(x, 2*x**2 + 3*x).subs(x, 5*x - 4)

    r13_20, r1_20 = [ Rational(*r)
        for r in ((13, 20), (1, 20)) ]

    s2 = sqrt(2)
    assert roots(f, x) == {
        r13_20 + r1_20*sqrt(1 - 8*I*s2): 1,
        r13_20 - r1_20*sqrt(1 - 8*I*s2): 1,
        r13_20 + r1_20*sqrt(1 + 8*I*s2): 1,
        r13_20 - r1_20*sqrt(1 + 8*I*s2): 1,
    }

    f = x**4 + x**3 + x**2 + x + 1

    r1_4, r1_8, r5_8 = [ Rational(*r) for r in ((1, 4), (1, 8), (5, 8)) ]

    assert roots(f, x) == {
        -r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
        -r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
        -r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
        -r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
    }

    f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2

    assert roots(f, z) == {
        S.One: 1,
        S.Half + S.Half*y + S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1,
        S.Half + S.Half*y - S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1,
    }

    assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {}
    assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {}

    assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1}
    assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1}

    assert roots((x - 1)*(x + 1), x) == {S.One: 1, -S.One: 1}
    assert roots(
        (x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {S.One: 1}

    assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One]
    assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I]

    assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero]
    assert roots(1234, x, multiple=True) == []

    f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1

    assert roots(f) == {
        -I*sin(pi/7) + cos(pi/7): 1,
        -I*sin(2*pi/7) - cos(2*pi/7): 1,
        -I*sin(3*pi/7) + cos(3*pi/7): 1,
        I*sin(pi/7) + cos(pi/7): 1,
        I*sin(2*pi/7) - cos(2*pi/7): 1,
        I*sin(3*pi/7) + cos(3*pi/7): 1,
    }

    g = ((x**2 + 1)*f**2).expand()

    assert roots(g) == {
        -I*sin(pi/7) + cos(pi/7): 2,
        -I*sin(2*pi/7) - cos(2*pi/7): 2,
        -I*sin(3*pi/7) + cos(3*pi/7): 2,
        I*sin(pi/7) + cos(pi/7): 2,
        I*sin(2*pi/7) - cos(2*pi/7): 2,
        I*sin(3*pi/7) + cos(3*pi/7): 2,
        -I: 1, I: 1,
    }

    r = roots(x**3 + 40*x + 64)
    real_root = [rx for rx in r if rx.is_real][0]
    cr = 4 + 2*sqrt(1074)/9
    assert real_root == -2*root(cr, 3) + 20/(3*root(cr, 3))

    eq = Poly((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2, x, domain='EX')
    assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1}

    eq = Poly(41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 +
    175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x -
    26*x + 24, x, domain='EX')
    assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1,
                         -4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1}

    eq = Poly(x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 +
            14*sqrt(2), x, domain='EX')
    assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1}

    assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \
        {-sqrt(2) - root(7, 3)/2 - sqrt(3)*root(7, 3)*I/2: 1,
         -sqrt(2) - root(7, 3)/2 + sqrt(3)*root(7, 3)*I/2: 1,
         -sqrt(2) + root(7, 3): 1}
Пример #53
0
def test_issue_3109_fail():
    from sympy import root, Rational
    I = S.ImaginaryUnit
    assert sqrt(exp(5*I)) == -exp(5*I/2)
    assert root(exp(5*I), 3).exp == Rational(1, 3)
Пример #54
0
 ("x_a", Symbol('x_{a}')),
 ("x_{b}", Symbol('x_{b}')),
 ("h_\\theta", Symbol('h_{theta}')),
 ("h_{\\theta}", Symbol('h_{theta}')),
 ("h_{\\theta}(x_0, x_1)",
  Symbol('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
 ("x!", _factorial(x)),
 ("100!", _factorial(100)),
 ("\\theta!", _factorial(theta)),
 ("(x + 1)!", _factorial(_Add(x, 1))),
 ("(x!)!", _factorial(_factorial(x))),
 ("x!!!", _factorial(_factorial(_factorial(x)))),
 ("5!7!", _Mul(_factorial(5), _factorial(7))),
 ("\\sqrt{x}", sqrt(x)),
 ("\\sqrt{x + b}", sqrt(_Add(x, b))),
 ("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
 ("\\sqrt[y]{\\sin x}", root(sin(x), y)),
 ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
 ("x < y", StrictLessThan(x, y)),
 ("x \\leq y", LessThan(x, y)),
 ("x > y", StrictGreaterThan(x, y)),
 ("x \\geq y", GreaterThan(x, y)),
 ("\\mathit{x}", Symbol('x')),
 ("\\mathit{test}", Symbol('test')),
 ("\\mathit{TEST}", Symbol('TEST')),
 ("\\mathit{HELLO world}", Symbol('HELLO world')),
 ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
 ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
 ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
 ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
 ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
Пример #55
0
def test_unrad():
    s = symbols('s', cls=Dummy)

    # checkers to deal with possibility of answer coming
    # back with a sign change (cf issue 2104)
    def check(rv, ans):
        rv, ans = list(rv), list(ans)
        rv[0] = rv[0].expand()
        ans[0] = ans[0].expand()
        return rv[0] in [ans[0], -ans[0]] and rv[1:] == ans[1:]

    def s_check(rv, ans):
        # get the dummy
        rv = list(rv)
        d = rv[0].atoms(Dummy)
        reps = zip(d, [s]*len(d))
        # replace s with this dummy
        rv = (rv[0].subs(reps).expand(), [(p[0].subs(reps), p[1].subs(reps))
                                   for p in rv[1]],
              [a.subs(reps) for a in rv[2]])
        ans = (ans[0].subs(reps).expand(), [(p[0].subs(reps), p[1].subs(reps))
                                   for p in ans[1]],
               [a.subs(reps) for a in ans[2]])
        return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
            str(rv[1:]) == str(ans[1:])

    assert check(unrad(sqrt(x)),
                 (x, [], []))
    assert check(unrad(sqrt(x) + 1),
                 (x - 1, [], []))
    assert s_check(unrad(sqrt(x) + x**Rational(1, 3) + 2),
                   (2 + s**2 + s**3, [(s, x - s**6)], []))
    assert check(unrad(sqrt(x)*x**Rational(1, 3) + 2),
                 (x**5 - 64, [], []))
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
                 (x**3 - (x + 1)**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)),
                (-2*sqrt(2)*x - 2*x + 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + 2),
               (16*x - 9, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
               (-4*x + 5*x**2, [], []))
    assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)),
                ((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x)),
                (2*x - 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
                (9*x + (x - 5)**2 - 9, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
                (-5*x**2 + 2*x - 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3),
        (-25*x**4 - 376*x**3 - 1256*x**2 + 2272*x - 784, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)),
                (-41*x**4 - 40*x**3 - 232*x**2 + 160*x - 16, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1)), (S(1), [], []))

    eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
    assert check(unrad(eq),
               (16*x**3 - 9*x**2, [], []))
    assert set(solve(eq, check=False)) == set([S(0), S(9)/16])
    assert solve(eq) == []
    # but this one really does have those solutions
    assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \
        set([S.Zero, S(9)/16])

    '''NOTE
    real_root changes the value of the result if the solution is
    simplified; `a` in the text below is the root that is not 4/5:
    >>> eq
    sqrt(x) + sqrt(-x + 1) + sqrt(x + 1) - 6*sqrt(5)/5
    >>> eq.subs(x, a).n()
    -0.e-123 + 0.e-127*I
    >>> real_root(eq.subs(x, a)).n()
    -0.e-123 + 0.e-127*I
    >>> (eq.subs(x,simplify(a))).n()
    -0.e-126
    >>> real_root(eq.subs(x, simplify(a))).n()
    0.194825975605452 + 2.15093623885838*I

    >>> sqrt(x).subs(x, real_root(a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, (a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, simplify(a)).n()
    0.809823827278194 - 5.32999467690853e-25*I
    >>> sqrt(x).subs(x, real_root(simplify(a))).n()
    0.49864610868139 + 1.44572604257047*I
    '''
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
    ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 +
    114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 +
    sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''')
    rb = S(4)/5
    ans = solve(sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
    assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \
        len(ans) == 2 and \
        set([i.n(chop=True) for i in ans]) == \
        set([i.n(chop=True) for i in (ra, rb)])

    raises(ValueError, lambda:
        unrad(-root(x,3)**2 + 2**pi*root(x,3) - x + 2**pi))
    raises(ValueError, lambda:
        unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
    raises(ValueError, lambda:
        unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y)))
    # same as last but consider only y
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y), y),
           (4*y - (sqrt(x) + (x + 1)**(S(1)/3))**2, [], []))
    assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)),
                (x**3/(-x + 1)**3 - (x + 1)**2, [], [(-x + 1)**3]))
    # same as last but consider only y; no y-containing denominators now
    assert s_check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y),
           (x/(-x + 1) - 4*y, [], []))
    assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x),
           (x*(-x + 1) - 4, [], []))

    # http://tutorial.math.lamar.edu/
    #        Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
    assert solve(Eq(x, sqrt(x + 6))) == [3]
    assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
    assert solve(Eq(1, x + sqrt(2*x - 3))) == []
    assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == set([-S(1), S(2)])
    assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == set([S(5), S(13)])
    assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
    # http://www.purplemath.com/modules/solverad.htm
    assert solve((2*x - 5)**Rational(1, 3) - 3) == [16]
    assert solve((x**3 - 3*x**2)**Rational(1, 3) + 1 - x) == []
    assert set(solve(x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4))) == \
        set([-S(1)/2, -S(1)/3])
    assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == set([-S(8), S(2)])
    assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
    assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5]
    assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16]
    assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
    assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0]
    assert solve(sqrt(x) - 2 - 5) == [49]
    assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
    assert solve(sqrt(x - 1) - x + 7) == [10]
    assert solve(sqrt(x - 2) - 5) == [27]
    assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3]
    assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []

    # don't posify the expression in unrad and use _mexpand
    z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x)
    p = posify(z)[0]
    assert solve(p) == []
    assert solve(z) == []
    assert solve(z + 6*I) == [-S(1)/11]
    assert solve(p + 6*I) == []

    eq = sqrt(2 + I) + 2*I
    assert unrad(eq - x, x, all=True) == (x**4 + 4*x**2 + 8*x + 37, [], [])
    ans = (81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 -
        31608*x**2 - 189648*x + 141358, [], [])
    r = sqrt(sqrt(2)/3 + 7)
    eq = sqrt(r) + r - x
    assert unrad(eq, all=1)
    r2 = sqrt(sqrt(2) + 21)/sqrt(3)
    assert r != r2 and r.equals(r2)
    assert unrad(eq - r + r2, all=True) == ans
Пример #56
0
    def expr(self, it):
        name = self.name

        if name == "frac":
            it[0] = expr(self.upper) / expr(self.lower)
        elif name == "over":
            it.zip(lambda l,r: expr(l) / expr(r))
        elif name == "times":
            it.zip(lambda l,r: expr(l) * expr(r))

        elif name == "sin":
            it[0] = sympy.sin( expr(self.token) )
        elif name == "cos":
            it[0] = sympy.cos( expr(self.token) )
        elif name == "tan":
            it[0] = sympy.tan( expr(self.token) )
        elif name == "choose":
            it.zip(lambda l,r: sympy.binomial(expr(l), expr(r)))
        elif name == "sqrt":
            it[0] = sympy.root( expr(self.token), expr(self.n) )
        elif name == "pi":
            it[0] = sympy.pi
        elif name == "int":
            # TODO: This needs to work more like the parenthesis transform
            i = it.next()
            instart = True
            lower = None
            upper = None

            # TODO: Try to find spacing first, then fall back to mathrm
            # Pattern: [(int), (limits)?, (^|_){0-2}, (.+), (<spacing>)?, (mathrm of d or del), (.)
            while type(i[0]) != tex_commands["mathrm"] or str(i[0].token) != 'd': # TODO: Do better letter checking
                if instart:
                    t = i[0]
                    if type(t) == tex_commands["limits"]:
                        del i[0]
                    elif isinstance(t, TexSpecial) and t.data == "^":
                        upper = expr(t.arg)
                        del i[0]
                    elif isinstance(t, TexSpecial) and t.data == "_":
                        lower = expr(t.arg)
                        del i[0]
                    else:
                        instart = False

                i = i.next()

            inner = expr( it.get([1,i]) )
            var = expr(i[1])

            it.set([0, i.next().next()], sympy.integrate(inner, (var, lower, upper)))

        elif name == "sum":

            i = it.next()
            instart = True
            lower = None
            upper = None

            while i[0] != None and not is_space(i[0]):
                if instart:
                    t = i[0]
                    if type(t) == tex_commands["limits"]:
                        del i[0]
                    elif isinstance(t, TexSpecial) and t.data == "^":
                        upper = expr(t.arg)
                        del i[0]
                    elif isinstance(t, TexSpecial) and t.data == "_":
                        lower = expr(t.arg)
                        del i[0]
                    else:
                        instart = False

                i = i.next()



            inner = expr( it.get([1,i]) )
            var = expr(i[1])


            it.set([0, i], sympy.Sum(inner, (lower.lhs, lower.rhs, upper)).doit())



        elif name == "ds":
            it[0] = expr(self.sym)

        else:
            sym = getattr(sympy.abc, name, None)
            if sym:
                it[0] = sym