Exemplo n.º 1
0
def test_pow1():
    assert refine((-1)**x, Q.even(x)) == 1
    assert refine((-1)**x, Q.odd(x)) == -1
    assert refine((-2)**x, Q.even(x)) == 2**x

    # nested powers
    assert refine(sqrt(x**2)) != Abs(x)
    assert refine(sqrt(x**2), Q.complex(x)) != Abs(x)
    assert refine(sqrt(x**2), Q.real(x)) == Abs(x)
    assert refine(sqrt(x**2), Q.positive(x)) == x
    assert refine((x**3)**Rational(1, 3)) != x

    assert refine((x**3)**Rational(1, 3), Q.real(x)) != x
    assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x

    assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x)
    assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x)

    # powers of (-1)
    assert refine((-1)**(x + y), Q.even(x)) == (-1)**y
    assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y
    assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y
    assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1)
    assert refine((-1)**(x + 3)) == (-1)**(x + 1)

    # continuation
    assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x
    assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1)
    assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1)
Exemplo n.º 2
0
def apply(*given):

    forall_a, forall_b = given
    assert len(forall_a.limits) == len(forall_b.limits) == 1
    a, A = forall_a.limits[0]
    b, B = forall_b.limits[0]

    assert forall_a.function.is_And
    assert forall_b.function.is_And
    contains_a, equality_a = forall_a.function.args
    if contains_a.is_Equality:
        equality_a, contains_a = contains_a, equality_a

    contains_b, equality_b = forall_b.function.args
    if contains_b.is_Equality:
        equality_b, contains_b = contains_b, equality_b

    assert contains_a.is_Contains and contains_b.is_Contains
    assert equality_a.is_Equality and equality_b.is_Equality

    fa, _B = contains_a.args
    assert B == _B
    gb, _A = contains_b.args
    assert A == _A

    eqs = Equality(a, Lambda(b, gb)(fa))
    assert equality_a == eqs or equality_a.reversed == eqs

    eqs = Equality(b, Lambda(a, fa)(gb))
    assert equality_b == eqs or equality_b.reversed == eqs

    return Equality(Abs(A), Abs(B), given=given)
Exemplo n.º 3
0
def test_evalf_with_zoo():
    assert (1 / x).evalf(subs={x: 0}) == zoo  # issue 8242
    assert (-1 / x).evalf(subs={x: 0}) == zoo  # PR 16150
    assert (0**x).evalf(subs={x: -1}) == zoo  # PR 16150
    assert (0**x).evalf(subs={x: -1 + I}) == nan
    assert Mul(2, Pow(0, -1, evaluate=False),
               evaluate=False).evalf() == zoo  # issue 21147
    assert Mul(x, 1 / x, evaluate=False).evalf(subs={x: 0}) == Mul(
        x, 1 / x, evaluate=False).subs(x, 0) == nan
    assert Mul(1 / x, 1 / x, evaluate=False).evalf(subs={x: 0}) == zoo
    assert Mul(1 / x, Abs(1 / x), evaluate=False).evalf(subs={x: 0}) == zoo
    assert Abs(zoo, evaluate=False).evalf() == oo
    assert re(zoo, evaluate=False).evalf() == nan
    assert im(zoo, evaluate=False).evalf() == nan
    assert Add(zoo, zoo, evaluate=False).evalf() == nan
    assert Add(oo, zoo, evaluate=False).evalf() == nan
    assert Pow(zoo, -1, evaluate=False).evalf() == 0
    assert Pow(zoo, Rational(-1, 3), evaluate=False).evalf() == 0
    assert Pow(zoo, Rational(1, 3), evaluate=False).evalf() == zoo
    assert Pow(zoo, S.Half, evaluate=False).evalf() == zoo
    assert Pow(zoo, 2, evaluate=False).evalf() == zoo
    assert Pow(0, zoo, evaluate=False).evalf() == nan
    assert log(zoo, evaluate=False).evalf() == zoo
    assert zoo.evalf(chop=True) == zoo
    assert x.evalf(subs={x: zoo}) == zoo
Exemplo n.º 4
0
def test_section_modulus_and_polar_second_moment_of_area():
    d = Symbol('d', positive=True)
    c = Circle((3, 7), 8)
    assert c.polar_second_moment_of_area() == 2048*pi
    assert c.section_modulus() == (128*pi, 128*pi)
    c = Circle((2, 9), d/2)
    assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64
    assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32))

    a, b = symbols('a, b', positive=True)
    e = Ellipse((4, 6), a, b)
    assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4))
    assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
    e = e.rotate(pi/2) # no change in polar and section modulus
    assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4))
    assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)

    e = Ellipse((a, b), 2, 6)
    assert e.section_modulus() == (18*pi, 6*pi)
    assert e.polar_second_moment_of_area() == 120*pi

    e = Ellipse(Point(0, 0), 2, 2)
    assert e.section_modulus() == (2*pi, 2*pi)
    assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi)
    assert e.section_modulus((2, 2)) == (2*pi, 2*pi)
Exemplo n.º 5
0
def test_QR():
    A = Matrix([[1, 2], [2, 3]])
    Q, S = A.QRdecomposition()
    R = Rational
    assert Q == Matrix([[5**R(-1, 2), (R(2) / 5) * (R(1) / 5)**R(-1, 2)],
                        [2 * 5**R(-1, 2), (-R(1) / 5) * (R(1) / 5)**R(-1, 2)]])
    assert S == Matrix([[5**R(1, 2), 8 * 5**R(-1, 2)],
                        [0, (R(1) / 5)**R(1, 2)]])
    assert Q * S == A
    assert Q.T * Q == eye(2)

    A = Matrix([[1, 1, 1], [1, 1, 3], [2, 3, 4]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[12, 0, -51], [6, 0, 167], [-4, 0, 24]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    x = Symbol('x')
    A = Matrix([x])
    Q, R = A.QRdecomposition()
    assert Q == Matrix([x / Abs(x)])
    assert R == Matrix([Abs(x)])

    A = Matrix([[x, 0], [0, x]])
    Q, R = A.QRdecomposition()
    assert Q == x / Abs(x) * Matrix([[1, 0], [0, 1]])
    assert R == Abs(x) * Matrix([[1, 0], [0, 1]])
Exemplo n.º 6
0
def test_Dimension_functions():
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(cos(length)))
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(acos(angle)))
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(atan2(length, time)))
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(log(length)))
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(log(100, length)))
    raises(TypeError,
           lambda: dimsys_SI.get_dimensional_dependencies(log(length, 10)))

    assert dimsys_SI.get_dimensional_dependencies(pi) == {}

    assert dimsys_SI.get_dimensional_dependencies(cos(1)) == {}
    assert dimsys_SI.get_dimensional_dependencies(cos(angle)) == {}

    assert dimsys_SI.get_dimensional_dependencies(atan2(length, length)) == {}

    assert dimsys_SI.get_dimensional_dependencies(
        log(length / length, length / length)) == {}

    assert dimsys_SI.get_dimensional_dependencies(Abs(length)) == {length: 1}
    assert dimsys_SI.get_dimensional_dependencies(Abs(length / length)) == {}

    assert dimsys_SI.get_dimensional_dependencies(sqrt(-1)) == {}
Exemplo n.º 7
0
    def as_real_imag(self, deep=True, **hints):
        """
        Returns this function as a complex coordinate.

        Examples
        ========

        >>> from sympy import I
        >>> from sympy.abc import x
        >>> from sympy.functions import log
        >>> log(x).as_real_imag()
        (log(Abs(x)), arg(x))
        >>> log(I).as_real_imag()
        (0, pi/2)
        >>> log(1 + I).as_real_imag()
        (log(sqrt(2)), pi/4)
        >>> log(I*x).as_real_imag()
        (log(Abs(x)), arg(I*x))

        """
        from sympy import Abs, arg
        if deep:
            abs = Abs(self.args[0].expand(deep, **hints))
            arg = arg(self.args[0].expand(deep, **hints))
        else:
            abs = Abs(self.args[0])
            arg = arg(self.args[0])
        if hints.get('log', False):  # Expand the log
            hints['complex'] = False
            return (log(abs).expand(deep, **hints), arg)
        else:
            return (log(abs), arg)
Exemplo n.º 8
0
 def _abs(mul):
   from sympy.core.mul import _mulsort
   c, nc = mul.args_cnc()
   a = []
   o = []
   for i in c:
       if isinstance(i, Abs):
           a.append(i.args[0])
       elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real:
           a.append(i.base.args[0]**i.exp)
       else:
           o.append(i)
   if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)):
       return mul
   absarg = Mul(*a)
   A = Abs(absarg)
   args = [A]
   args.extend(o)
   if not A.has(Abs):
       args.extend(nc)
       return Mul(*args)
   if not isinstance(A, Abs):
       # reevaluate and make it unevaluated
       A = Abs(absarg, evaluate=False)
   args[0] = A
   _mulsort(args)
   args.extend(nc)  # nc always go last
   return Mul._from_args(args, is_commutative=not nc)
Exemplo n.º 9
0
def test_periodic_argument():
    from sympy.functions.elementary.complexes import (periodic_argument,
                                                      polar_lift,
                                                      principal_branch,
                                                      unbranched_argument)
    x = Symbol('x')
    p = Symbol('p', positive=True)

    assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
    assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
    assert N_equals(unbranched_argument((1 + I)**2), pi / 2)
    assert N_equals(unbranched_argument((1 - I)**2), -pi / 2)
    assert N_equals(periodic_argument((1 + I)**2, 3 * pi), pi / 2)
    assert N_equals(periodic_argument((1 - I)**2, 3 * pi), -pi / 2)

    assert unbranched_argument(principal_branch(x, pi)) == \
        periodic_argument(x, pi)

    assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
    assert periodic_argument(polar_lift(2 + I), 2*pi) == \
        periodic_argument(2 + I, 2*pi)
    assert periodic_argument(polar_lift(2 + I), 3*pi) == \
        periodic_argument(2 + I, 3*pi)
    assert periodic_argument(polar_lift(2 + I), pi) == \
        periodic_argument(polar_lift(2 + I), pi)

    assert unbranched_argument(polar_lift(1 + I)) == pi / 4
    assert periodic_argument(2 * p, p) == periodic_argument(p, p)
    assert periodic_argument(pi * p, p) == periodic_argument(p, p)

    assert Abs(polar_lift(1 + I)) == Abs(1 + I)
Exemplo n.º 10
0
def test_real_imag():
    x, y, z = symbols('x, y, z')
    X, Y, Z = symbols('X, Y, Z', commutative=False)
    a = Symbol('a', real=True)
    assert (2 * a * x).as_real_imag() == (2 * a * re(x), 2 * a * im(x))

    # issue 5395:
    assert (x * x.conjugate()).as_real_imag() == (Abs(x)**2, 0)
    assert im(x * x.conjugate()) == 0
    assert im(x * y.conjugate() * z * y) == im(x * z) * Abs(y)**2
    assert im(x * y.conjugate() * x * y) == im(x**2) * Abs(y)**2
    assert im(Z * y.conjugate() * X * y) == im(Z * X) * Abs(y)**2
    assert im(X * X.conjugate()) == im(X * X.conjugate(), evaluate=False)
    assert (sin(x)*sin(x).conjugate()).as_real_imag() == \
        (Abs(sin(x))**2, 0)

    # issue 6573:
    assert (x**2).as_real_imag() == (re(x)**2 - im(x)**2, 2 * re(x) * im(x))

    # issue 6428:
    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)
    assert (i * r * x).as_real_imag() == (I * i * r * im(x),
                                          -I * i * r * re(x))
    assert (i * r * x *
            (y + 2)).as_real_imag() == (I * i * r * (re(y) + 2) * im(x) +
                                        I * i * r * re(x) * im(y),
                                        -I * i * r * (re(y) + 2) * re(x) +
                                        I * i * r * im(x) * im(y))

    # issue 7106:
    assert ((1 + I) / (1 - I)).as_real_imag() == (0, 1)
    assert ((1 + 2 * I) * (1 + 3 * I)).as_real_imag() == (-5, 5)
Exemplo n.º 11
0
def test_pow2():
    assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1)
    assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x

    # powers of Abs
    assert refine(Abs(x)**2, Q.real(x)) == x**2
    assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3
    assert refine(Abs(x)**2) == Abs(x)**2
Exemplo n.º 12
0
def apply(n, Q=None):
    if Q is None:
        Q, w, x = mapping.Qu2v.predefined_symbols(n)
    else:
        x = Q.definition.function.variable
    P_quote = Symbol("P'", definition=conditionset(x[:n + 1], Equality(x[:n].set_comprehension(), Interval(0, n - 1, integer=True)) & Equality(x[n], n)))
    
    t = Q.definition.variable
    return Equality(Abs(Q[t]), Abs(P_quote))
Exemplo n.º 13
0
def apply(n, P_quote=None):    
    
    if P_quote is None:
        x = Symbol.x(shape=(oo,), integer=True, nonnegative=True)
        P_quote = Symbol("P'", definition=conditionset(x[:n + 1], Equality(x[:n].set_comprehension(), Interval(0, n - 1, integer=True)) & Equality(x[n], n)))
    else:
        x = P_quote.definition.variable.base
    
    P = Symbol.P(definition=conditionset(x[:n], Equality(x[:n].set_comprehension(), Interval(0, n - 1, integer=True))))    
    return Equality(Abs(P), Abs(P_quote))
Exemplo n.º 14
0
def test_extract_predargs():
    props = CNF.from_prop(Q.zero(Abs(x*y)) & Q.zero(x*y))
    assump = CNF.from_prop(Q.zero(x))
    context = CNF.from_prop(Q.zero(y))
    assert extract_predargs(props) == {Abs(x*y), x*y}
    assert extract_predargs(props, assump) == {Abs(x*y), x*y, x}
    assert extract_predargs(props, assump, context) == {Abs(x*y), x*y, x, y}

    props = CNF.from_prop(Eq(x, y))
    assump = CNF.from_prop(Gt(y, z))
    assert extract_predargs(props, assump) == {x, y, z}
Exemplo n.º 15
0
 def taylor_term(n, x, *previous_terms):
     if n < 0:
         return S.Zero
     else:
         x = sympify(x)
         if len(previous_terms) > 1:
             p = previous_terms[-1]
             return (3**(S(1)/3)*x * Abs(sin(2*pi*(n + S.One)/S(3))) * C.factorial((n - S.One)/S(3)) /
                     ((n + S.One) * Abs(cos(2*pi*(n + S.Half)/S(3))) * C.factorial((n - 2)/S(3))) * p)
         else:
             return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(2*pi*(n + S.One)/S(3))) /
                     C.factorial(n) * (root(3, 3)*x)**n)
Exemplo n.º 16
0
def apply(*given):
    equality_A, equality_B = given
    assert equality_A.is_Equality and equality_B.is_Equality
    image_B, A = equality_A.args
    image_A, B = equality_B.args

    gb, b, _B = image_B.image_set()
    fb, a, _A = image_A.image_set()

    assert A == _A and B == _B

    return Equality(Abs(A), Abs(B), given=given)
Exemplo n.º 17
0
 def _print_sign(self, expr):
     from sympy.functions.elementary.complexes import Abs
     arg, = expr.args
     if arg.is_integer:
         new_expr = merge(0, isign(1, arg), Eq(arg, 0))
     elif (arg.is_complex or arg.is_infinite):
         new_expr = merge(cmplx(literal_dp(0), literal_dp(0)),
                          arg / Abs(arg), Eq(Abs(arg), literal_dp(0)))
     else:
         new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg),
                          Eq(arg, literal_dp(0)))
     return self._print(new_expr)
Exemplo n.º 18
0
def test_numpy_numexpr():
    if not numpy:
        skip("numpy not installed.")
    if not numexpr:
        skip("numexpr not installed.")
    a, b, c = numpy.random.randn(3, 128, 128)
    # ensure that numpy and numexpr return same value for complicated expression
    expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
           Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
    npfunc = lambdify((x, y, z), expr, modules='numpy')
    nefunc = lambdify((x, y, z), expr, modules='numexpr')
    assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
Exemplo n.º 19
0
def test_derivatives_issue_4757():
    x = Symbol('x', real=True)
    y = Symbol('y', imaginary=True)
    f = Function('f')
    assert re(f(x)).diff(x) == re(f(x).diff(x))
    assert im(f(x)).diff(x) == im(f(x).diff(x))
    assert re(f(y)).diff(y) == -I * im(f(y).diff(y))
    assert im(f(y)).diff(y) == -I * re(f(y).diff(y))
    assert Abs(f(x)).diff(x).subs(f(x), 1 + I * x).doit() == x / sqrt(1 + x**2)
    assert arg(f(x)).diff(x).subs(f(x),
                                  1 + I * x**2).doit() == 2 * x / (1 + x**4)
    assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y / sqrt(1 - y**2)
    assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2 * y / (1 + y**4)
Exemplo n.º 20
0
def apply(*given):

    forall_a, forall_b, equality_a, equality_b = given
    A, B, a, b, fa, gb = analyze(forall_a, forall_b, equality_a)

    eqs = Equality(b, Lambda(a, fa)(gb))
    if equality_b.is_ForAll:
        assert equality_b.variable == b
        assert equality_b.limits == forall_b.limits
        equality_b = equality_b.function

    assert equality_b.is_Equal
    assert equality_b == eqs or equality_b.reversed == eqs

    return Equality(Abs(A), Abs(B), given=given)
Exemplo n.º 21
0
def test_log_expand():
    w = Symbol("w", positive=True)
    e = log(w**(log(5) / log(3)))
    assert e.expand() == log(5) / log(3) * log(w)
    x, y, z = symbols('x,y,z', positive=True)
    assert log(x * (y + z)).expand(mul=False) == log(x) + log(y + z)
    assert log(
        log(x**2) *
        log(y * z)).expand() == log(log(y) + log(z)) + log(log(x)) + log(2)
    assert log(x**log(x**2)).expand(deep=False) == log(x) * log(x**2)
    assert log(x**log(x**2)).expand() == 2 * log(x)**2
    x, y = symbols('x,y')
    # if we don't know whether variables are real or complex, we can't expand
    assert log(x**2 * y**3).expand() == log(x**2 * y**3)
    assert log(x * y).expand(force=True) == log(x) + log(y)
    assert log(x**y).expand(force=True) == y * log(x)
    assert log(exp(x)).expand(force=True) == x

    x, y, z = symbols('x,y,z', real=True)
    assert log(y**2 * x**3 *
               z).expand() == 2 * log(Abs(y)) + 3 * log(x) + log(z)

    # there's generally no need to expand out logs since this requires
    # factoring and if simplification is sought, it's cheaper to put
    # logs together than it is to take them apart.
    assert log(2 * 3**2).expand() != 2 * log(3) + log(2)
Exemplo n.º 22
0
 def eval(cls, s, z):
     s, z = sympify((s, z))
     if z == 1:
         return zeta(s)
     elif z == -1:
         return -dirichlet_eta(s)
     elif z == 0:
         return S.Zero
     elif s == 2:
         if z == S.Half:
             return pi**2 / 12 - log(2)**2 / 2
         elif z == 2:
             return pi**2 / 4 - I * pi * log(2)
         elif z == -(sqrt(5) - 1) / 2:
             return -pi**2 / 15 + log((sqrt(5) - 1) / 2)**2 / 2
         elif z == -(sqrt(5) + 1) / 2:
             return -pi**2 / 10 - log((sqrt(5) + 1) / 2)**2
         elif z == (3 - sqrt(5)) / 2:
             return pi**2 / 15 - log((sqrt(5) - 1) / 2)**2
         elif z == (sqrt(5) - 1) / 2:
             return pi**2 / 10 - log((sqrt(5) - 1) / 2)**2
     # For s = 0 or -1 use explicit formulas to evaluate, but
     # automatically expanding polylog(1, z) to -log(1-z) seems undesirable
     # for summation methods based on hypergeometric functions
     elif s == 0:
         return z / (1 - z)
     elif s == -1:
         return z / (1 - z)**2
     # polylog is branched, but not over the unit disk
     from sympy.functions.elementary.complexes import (Abs, unpolarify,
                                                       polar_lift)
     if z.has(exp_polar, polar_lift) and (Abs(z) <= S.One) == True:
         return cls(s, unpolarify(z))
Exemplo n.º 23
0
def test_quaternion_conversions():
    q1 = Quaternion(1, 2, 3, 4)

    assert q1.to_axis_angle() == ((2 * sqrt(29)/29,
                                   3 * sqrt(29)/29,
                                   4 * sqrt(29)/29),
                                   2 * acos(sqrt(30)/30))

    assert q1.to_rotation_matrix() == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)],
                                              [Rational(2, 3), Rational(-1, 3), Rational(2, 3)],
                                              [Rational(1, 3), Rational(14, 15), Rational(2, 15)]])

    assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)],
                                                       [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero],
                                                       [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)],
                                                       [S.Zero, S.Zero, S.Zero, S.One]])

    theta = symbols("theta", real=True)
    q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2))

    assert trigsimp(q2.to_rotation_matrix()) == Matrix([
                                               [cos(theta), -sin(theta), 0],
                                               [sin(theta),  cos(theta), 0],
                                               [0,           0,          1]])

    assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))),
                                   2*acos(cos(theta/2)))

    assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([
               [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1],
               [sin(theta),  cos(theta), 0, -sin(theta) - cos(theta) + 1],
               [0,           0,          1,  0],
               [0,           0,          0,  1]])
Exemplo n.º 24
0
def test_solve_univariate_inequality():
    assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2),
        Interval(2, oo))
    assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2),
        Lt(-oo, x)))
    assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \
        Union(Interval(1, 2), Interval(3, oo))
    assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \
        Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo)))
    assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain = FiniteSet(0, 3)) == \
        Or(Eq(x, 0), Eq(x, 3))
    # issue 2785:
    assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \
        Union(Interval(-1, -sqrt(5)/2 + S.Half, True, True),
              Interval(S.Half + sqrt(5)/2, oo, True, True))
    # issue 2794:
    assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \
        Interval(1, oo, True)
    #issue 13105
    assert isolve((x + I)*(x + 2*I) < 0, x) == Eq(x, 0)
    assert isolve(((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I) < 0, x) == Or(Eq(x, 1), Eq(x, 2))
    assert isolve((((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I))/(x - 2) > 0, x) == Eq(x, 1)
    raises (ValueError, lambda: isolve((x**2 - 3*x*I + 2)/x < 0, x))

    # numerical testing in valid() is needed
    assert isolve(x**7 - x - 2 > 0, x) == \
        And(rootof(x**7 - x - 2, 0) < x, x < oo)

    # handle numerator and denominator; although these would be handled as
    # rational inequalities, these test confirm that the right thing is done
    # when the domain is EX (e.g. when 2 is replaced with sqrt(2))
    assert isolve(1/(x - 2) > 0, x) == And(S(2) < x, x < oo)
    den = ((x - 1)*(x - 2)).expand()
    assert isolve((x - 1)/den <= 0, x) == \
        (x > -oo) & (x < 2) & Ne(x, 1)

    n = Dummy('n')
    raises(NotImplementedError, lambda: isolve(Abs(x) <= n, x, relational=False))
    c1 = Dummy("c1", positive=True)
    raises(NotImplementedError, lambda: isolve(n/c1 < 0, c1))
    n = Dummy('n', negative=True)
    assert isolve(n/c1 > -2, c1) == (-n/2 < c1)
    assert isolve(n/c1 < 0, c1) == True
    assert isolve(n/c1 > 0, c1) == False

    zero = cos(1)**2 + sin(1)**2 - 1
    raises(NotImplementedError, lambda: isolve(x**2 < zero, x))
    raises(NotImplementedError, lambda: isolve(
        x**2 < zero*I, x))
    raises(NotImplementedError, lambda: isolve(1/(x - y) < 2, x))
    raises(NotImplementedError, lambda: isolve(1/(x - y) < 0, x))
    raises(TypeError, lambda: isolve(x - I < 0, x))

    zero = x**2 + x - x*(x + 1)
    assert isolve(zero < 0, x, relational=False) is S.EmptySet
    assert isolve(zero <= 0, x, relational=False) is S.Reals

    # make sure iter_solutions gets a default value
    raises(NotImplementedError, lambda: isolve(
        Eq(cos(x)**2 + sin(x)**2, 1), x))
Exemplo n.º 25
0
def test_singular_values():
    x = Symbol('x', real=True)

    A = EigenOnlyMatrix([[0, 1*I], [2, 0]])
    # if singular values can be sorted, they should be in decreasing order
    assert A.singular_values() == [2, 1]

    A = eye(3)
    A[1, 1] = x
    A[2, 2] = 5
    vals = A.singular_values()
    # since Abs(x) cannot be sorted, test set equality
    assert set(vals) == set([5, 1, Abs(x)])

    A = EigenOnlyMatrix([[sin(x), cos(x)], [-cos(x), sin(x)]])
    vals = [sv.trigsimp() for sv in A.singular_values()]
    assert vals == [S(1), S(1)]

    A = EigenOnlyMatrix([
        [2, 4],
        [1, 3],
        [0, 0],
        [0, 0]
        ])
    assert A.singular_values() == \
        [sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221))]
    assert A.T.singular_values() == \
        [sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221)), 0, 0]
Exemplo n.º 26
0
def real_root(arg, n=None, evaluate=None):
    """Return the real *n*'th-root of *arg* if possible.

    Parameters
    ==========

    n : int or None, optional
        If *n* is ``None``, then all instances of
        ``(-n)**(1/odd)`` will be changed to ``-n**(1/odd)``.
        This will only create a real root of a principal root.
        The presence of other factors may cause the result to not be
        real.

    evaluate : bool, optional
        The parameter determines if the expression should be evaluated.
        If ``None``, its value is taken from
        ``global_parameters.evaluate``.

    Examples
    ========

    >>> from sympy import root, real_root

    >>> real_root(-8, 3)
    -2
    >>> root(-8, 3)
    2*(-1)**(1/3)
    >>> real_root(_)
    -2

    If one creates a non-principal root and applies real_root, the
    result will not be real (so use with caution):

    >>> root(-8, 3, 2)
    -2*(-1)**(2/3)
    >>> real_root(_)
    -2*(-1)**(2/3)

    See Also
    ========

    sympy.polys.rootoftools.rootof
    sympy.core.power.integer_nthroot
    root, sqrt
    """
    from sympy.functions.elementary.complexes import Abs, im, sign
    from sympy.functions.elementary.piecewise import Piecewise
    if n is not None:
        return Piecewise((root(arg, n, evaluate=evaluate),
                          Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
                         (Mul(sign(arg),
                              root(Abs(arg), n, evaluate=evaluate),
                              evaluate=evaluate),
                          And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
                         (root(arg, n, evaluate=evaluate), True))
    rv = sympify(arg)
    n1pow = Transform(
        lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative
        and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2)
    return rv.xreplace(n1pow)
Exemplo n.º 27
0
def test_dft():
    n, i, j = symbols('n i j')
    assert DFT(4).shape == (4, 4)
    assert ask(Q.unitary(DFT(4)))
    assert Abs(simplify(det(Matrix(DFT(4))))) == 1
    assert DFT(n) * IDFT(n) == Identity(n)
    assert DFT(n)[i, j] == exp(-2 * S.Pi * I / n)**(i * j) / sqrt(n)
Exemplo n.º 28
0
def test_numpy_translation_abs():
    if not numpy:
        skip("numpy not installed.")

    f = lambdify(x, Abs(x), "numpy")
    assert f(-1) == 1
    assert f(1) == 1
Exemplo n.º 29
0
    def as_real_imag(self, deep=True, **hints):
        """
        Returns this function as a complex coordinate.

        Examples
        ========

        >>> from sympy import I, log
        >>> from sympy.abc import x
        >>> log(x).as_real_imag()
        (log(Abs(x)), arg(x))
        >>> log(I).as_real_imag()
        (0, pi/2)
        >>> log(1 + I).as_real_imag()
        (log(sqrt(2)), pi/4)
        >>> log(I*x).as_real_imag()
        (log(Abs(x)), arg(I*x))

        """
        from sympy.functions.elementary.complexes import (Abs, arg)
        sarg = self.args[0]
        if deep:
            sarg = self.args[0].expand(deep, **hints)
        abs = Abs(sarg)
        if abs == sarg:
            return self, S.Zero
        arg = arg(sarg)
        if hints.get('log', False):  # Expand the log
            hints['complex'] = False
            return (log(abs).expand(deep, **hints), arg)
        else:
            return log(abs), arg
Exemplo n.º 30
0
def test_issue_11413():
    from sympy.simplify.simplify import simplify
    v0 = Symbol('v0')
    v1 = Symbol('v1')
    v2 = Symbol('v2')
    V = Matrix([[v0], [v1], [v2]])
    U = V.normalized()
    assert U == Matrix([[v0 / sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
                        [v1 / sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
                        [v2 / sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
    U.norm = sqrt(v0**2 / (v0**2 + v1**2 + v2**2) + v1**2 /
                  (v0**2 + v1**2 + v2**2) + v2**2 / (v0**2 + v1**2 + v2**2))
    assert simplify(U.norm) == 1