Example #1
0
    def _generic_mul(q1, q2):

        q1 = sympify(q1)
        q2 = sympify(q2)

        # None is a Quaternion:
        if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
            return q1 * q2

        # If q1 is a number or a sympy expression instead of a quaternion
        if not isinstance(q1, Quaternion):
            if q2.real_field:
                if q1.is_complex:
                    return q2 * Quaternion(re(q1), im(q1), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)


        # If q2 is a number or a sympy expression instead of a quaternion
        if not isinstance(q2, Quaternion):
            if q1.real_field:
                if q2.is_complex:
                    return q1 * Quaternion(re(q2), im(q2), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)

        return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a,
                          q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b,
                          -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c,
                          q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d)
Example #2
0
def velocity_field(psi): #takes a symbolic function and returns two lambda functions
#to evaluate the derivatives in both x and y.
   global w
   if velocity_components:
      u = lambdify((x,y), eval(x_velocity), modules='numpy')
      v = lambdify((x,y), eval(y_velocity), modules='numpy')
   else:
      if is_complex_potential:
         print "Complex potential, w(z) given"
         #define u, v symbolically as the imaginary part of the derivatives
         u = lambdify((x, y), sympy.im(psi.diff(y)), modules='numpy')
         v = lambdify((x, y), -sympy.im(psi.diff(x)), modules='numpy')
      else:
         #define u,v as the derivatives 
         print "Stream function, psi given"
         u = sympy.lambdify((x, y), psi.diff(y), 'numpy')
         v = sympy.lambdify((x, y), -psi.diff(x), 'numpy')
   if (branch_cuts): # If it's indicated that there are branch cuts in the mapping,
                      # then we need to return vectorized numpy functions to evaluate
                      # everything numerically, instead of symbolically 
                      # This of course results in a SIGNIFICANT time increase
                      #   (I don't know how to handle more than the primitive root
                      #   (symbolically in Sympy
      return np.vectorize(u),np.vectorize(v)
   else:
       # If there are no branch cuts, then return the symbolic lambda functions (MUCH faster)
      return u,v
Example #3
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

    # issue 6261
    x = Symbol('x')
    assert sqrt(x).as_real_imag() == \
        ((re(x)**2 + im(x)**2)**(S(1)/4)*cos(atan2(im(x), re(x))/2),
     (re(x)**2 + im(x)**2)**(S(1)/4)*sin(atan2(im(x), re(x))/2))

    # issue 3853
    a, b = symbols('a,b', real=True)
    assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
           (
               (a**2 + b**2)**Rational(
                   1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2),
               (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)

    assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
    i = symbols('i', imaginary=True)
    assert sqrt(i**2).as_real_imag() == (0, abs(i))
Example #4
0
def test_f_expand_complex():
    x = Symbol("x", real=True)

    assert f(x).expand(complex=True) == I * im(f(x)) + re(f(x))
    assert exp(x).expand(complex=True) == exp(x)
    assert exp(I * x).expand(complex=True) == cos(x) + I * sin(x)
    assert exp(z).expand(complex=True) == cos(im(z)) * exp(re(z)) + I * sin(im(z)) * exp(re(z))
Example #5
0
def test_re():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert re(x) == re(x)
    assert re(x*I) == -im(x)
    assert re(r*I) == 0
    assert re(r) == r
    assert re(i*I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x + y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y*I) == re(x) - im(y)
    assert re(x + r*I) == re(x)

    assert re(log(2*I)) == log(2)

    assert re((2 + I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i*r*x).diff(r) == re(i*x)
    assert re(i*r*x).diff(i) == I*r*im(x)

    assert re(
        sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
    assert re(a * (2 + b*I)) == 2*a

    assert re((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2)

    assert re(x).rewrite(im) == x - im(x)
    assert (x + re(y)).rewrite(re, im) == x + y - im(y)
Example #6
0
def test_reduce_inequalities_multivariate():
    x = Symbol('x')
    y = Symbol('y')

    assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == \
        And(Eq(im(x), 0), Eq(im(y), 0), Or(And(Le(1, re(x)), Lt(re(x), oo)),
                                           And(Le(re(x), -1), Lt(-oo, re(x)))),
            Or(And(Le(1, re(y)), Lt(re(y), oo)), And(Le(re(y), -1), Lt(-oo, re(y)))))
Example #7
0
def test_derivatives_issue1658():
    x = Symbol('x')
    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))

    x = Symbol('x', real=True)
    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)
Example #8
0
def test_f_expand_complex():
    f = Function('f')
    x = Symbol('x', real=True)
    z = Symbol('z')

    assert f(x).expand(complex=True)        == I*im(f(x)) + re(f(x))
    assert exp(x).expand(complex=True)      == exp(x)
    assert exp(I*x).expand(complex=True)    == cos(x) + I*sin(x)
    assert exp(z).expand(complex=True)      == cos(im(z))*exp(re(z)) + \
                                             I*sin(im(z))*exp(re(z))
Example #9
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 )}'
Example #10
0
 def _eval_evalf(self, prec):
     """ Careful! any evalf of polar numbers is flaky """
     from sympy import im, pi, re
     i = im(self.args[0])
     if i <= -pi or i > pi:
         return self  # cannot evalf for this argument
     res = exp(self.args[0])._eval_evalf(prec)
     if i > 0 and im(res) < 0:
         # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
         return re(res)
     return res
Example #11
0
def test_map_coeffs():
    p = Poly(x**2 + 2*x*y, x, y)
    q = p.map_coeffs(lambda c: 2*c)

    assert q.as_basic() == 2*x**2 + 4*x*y

    p = Poly(u*x**2 + v*x*y, x, y)
    q = p.map_coeffs(expand, complex=True)

    assert q.as_basic() == x**2*(I*im(u) + re(u)) + x*y*(I*im(v) + re(v))

    raises(PolynomialError, "p.map_coeffs(lambda c: x*c)")
Example #12
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)
Example #13
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

    # issue 3162
    x = Symbol('x')
    assert sqrt(x).as_real_imag() == \
    ((re(x)**2 + im(x)**2)**(S(1)/4)*cos(atan2(im(x), re(x))/2), \
     (re(x)**2 + im(x)**2)**(S(1)/4)*sin(atan2(im(x), re(x))/2))
Example #14
0
    def eval(cls, arg):
        from sympy import im
        if arg.is_integer or arg.is_finite is False:
            return arg
        if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
            i = im(arg)
            if not i.has(S.ImaginaryUnit):
                return cls(i)*S.ImaginaryUnit
            return cls(arg, evaluate=False)

        v = cls._eval_number(arg)
        if v is not None:
            return v

        # Integral, numerical, symbolic part
        ipart = npart = spart = S.Zero

        # Extract integral (or complex integral) terms
        terms = Add.make_args(arg)

        for t in terms:
            if t.is_integer or (t.is_imaginary and im(t).is_integer):
                ipart += t
            elif t.has(Symbol):
                spart += t
            else:
                npart += t

        if not (npart or spart):
            return ipart

        # Evaluate npart numerically if independent of spart
        if npart and (
            not spart or
            npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
                npart.is_imaginary and spart.is_real):
            try:
                r, i = get_integer_part(
                    npart, cls._dir, {}, return_ints=True)
                ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
                npart = S.Zero
            except (PrecisionExhausted, NotImplementedError):
                pass

        spart += npart
        if not spart:
            return ipart
        elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
            return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
        else:
            return ipart + cls(spart, evaluate=False)
Example #15
0
def test_zero_assumptions():
    nr = Symbol('nonreal', real=False)
    ni = Symbol('nonimaginary', imaginary=False)
    # imaginary implies not zero
    nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)

    assert re(nr).is_zero is None
    assert im(nr).is_zero is False

    assert re(ni).is_zero is None
    assert im(ni).is_zero is None

    assert re(nzni).is_zero is False
    assert im(nzni).is_zero is None
Example #16
0
def test_diff_no_eval_derivative():
    class My(Expr):
        def __new__(cls, x):
            return Expr.__new__(cls, x)

    x, y = symbols('x y')
    # My doesn't have its own _eval_derivative method
    assert My(x).diff(x).func is Derivative
    assert My(x).diff(x, 3).func is Derivative
    assert re(x).diff(x, 2) == Derivative(re(x), (x, 2))  # issue 15518
    assert diff(NDimArray([re(x), im(x)]), (x, 2)) == NDimArray(
        [Derivative(re(x), (x, 2)), Derivative(im(x), (x, 2))])
    # it doesn't have y so it shouldn't need a method for this case
    assert My(x).diff(y) == 0
Example #17
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 2296:
    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)
Example #18
0
def test_re():
    x, y = symbols('x,y')

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert re(x) == re(x)
    assert re(x*I) == -im(x)
    assert re(r*I) == 0
    assert re(r) == r
    assert re(i*I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x + y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y*I) == re(x) - im(y)
    assert re(x + r*I) == re(x)

    assert re(log(2*I)) == log(2)

    assert re((2+I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i*r*x).diff(r) == re(i*x)
    assert re(i*r*x).diff(i) == -I * im(r*x)
Example #19
0
    def plot_initial_monodromy_path(self, i, Npts=4, eps=0.1):
        """
        Plots the initial monodromy path. Used for testing and
        debugging purposes.
        """
        # plot the monodromy graph
        self.show_paths()
        fig = plt.gcf()
        ax  = fig.gca()

        # compute the path points
        path_points = self._initial_monodromy_path(i, Npts=Npts)
        N = len(path_points)

        # plot forward path
        topos = lambda pp: (sympy.re(pp), sympy.im(pp))
        for n in xrange(N/2):
            pos = topos(path_points[n])
            ax.text(pos[0], pos[1], '%d'%n, size='x-small',
                    verticalalignment='top')

        # plot return path
        for n in xrange(N/2,N):
            pos = topos(path_points[n])
            ax.text(pos[0], pos[1], '%d'%n, size='x-small',
                    verticalalignment='bottom')

        ax.axis('tight')
        fig.show()
Example #20
0
def test_evalc():
    x = Symbol("x", real=True)
    y = Symbol("y", real=True)
    z = Symbol("z")
    assert ((x+I*y)**2).expand(complex=True) == x**2+2*I*x*y - y**2
    assert expand_complex(z**(2*I)) == I*im(z**(2*I)) + re(z**(2*I))

    assert exp(I*x) != cos(x)+I*sin(x)
    assert exp(I*x).expand(complex=True) == cos(x)+I*sin(x)
    assert exp(I*x+y).expand(complex=True) == exp(y)*cos(x)+I*sin(x)*exp(y)

    assert sin(I*x).expand(complex=True) == I * sinh(x)
    assert sin(x+I*y).expand(complex=True) == sin(x)*cosh(y) + \
            I * sinh(y) * cos(x)

    assert cos(I*x).expand(complex=True) == cosh(x)
    assert cos(x+I*y).expand(complex=True) == cos(x)*cosh(y) - \
            I * sinh(y) * sin(x)

    assert tan(I*x).expand(complex=True) == tanh(x) * I
    assert tan(x+I*y).expand(complex=True) == \
            ((sin(x)*cos(x) + I*cosh(y)*sinh(y)) / (cos(x)**2 + sinh(y)**2)).expand()

    assert sinh(I*x).expand(complex=True) == I * sin(x)
    assert sinh(x+I*y).expand(complex=True) == sinh(x)*cos(y) + \
            I * sin(y) * cosh(x)

    assert cosh(I*x).expand(complex=True) == cos(x)
    assert cosh(x+I*y).expand(complex=True) == cosh(x)*cos(y) + \
            I * sin(y) * sinh(x)

    assert tanh(I*x).expand(complex=True) == tan(x) * I
    assert tanh(x+I*y).expand(complex=True) == \
            ((sinh(x)*cosh(x) + I*cos(y)*sin(y)) / (sinh(x)**2 + cos(y)**2)).expand()
Example #21
0
def test_imag_real():
    f_re = lambdify([z], sympy.re(z))
    val = 3+2j
    assert f_re(val) == val.real

    f_im = lambdify([z], sympy.im(z))  # see #15400
    assert f_im(val) == val.imag
def test_catalan():
    n = Symbol('n', integer=True)
    m = Symbol('n', integer=True, positive=True)

    catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
    for i, c in enumerate(catalans):
        assert catalan(i) == c
        assert catalan(n).rewrite(factorial).subs(n, i) == c
        assert catalan(n).rewrite(Product).subs(n, i).doit() == c

    assert catalan(x) == catalan(x)
    assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8/(3*pi)
    assert catalan(Rational(1, 2)).rewrite(factorial).rewrite(gamma) ==\
        8 / (3 * pi)
    assert catalan(3*x).rewrite(gamma) == 4**(
        3*x)*gamma(3*x + Rational(1, 2))/(sqrt(pi)*gamma(3*x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)

    assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
                                                              * factorial(n))
    assert isinstance(catalan(n).rewrite(Product), catalan)
    assert isinstance(catalan(m).rewrite(Product), Product)

    assert diff(catalan(x), x) == (polygamma(
        0, x + Rational(1, 2)) - polygamma(0, x + 2) + log(4))*catalan(x)

    assert catalan(x).evalf() == catalan(x)
    c = catalan(S.Half).evalf()
    assert str(c) == '0.848826363156775'
    c = catalan(I).evalf(3)
    assert str((re(c), im(c))) == '(0.398, -0.0209)'
Example #23
0
 def _eval_evalf(self, prec):
     """ Careful! any evalf of polar numbers is flaky """
     from sympy import im, pi
     i = im(self.args[0])
     if i <= -pi or i > pi:
         return self # cannot evalf for this argument
     return exp(self.args[0])._eval_evalf(prec)
Example #24
0
def get_integer_part(expr, no, options, return_ints=False):
    """
    With no = 1, computes ceiling(expr)
    With no = -1, computes floor(expr)

    Note: this function either gives the exact result or signals failure.
    """
    import sympy
    # The expression is likely less than 2^30 or so
    assumed_size = 30
    ire, iim, ire_acc, iim_acc = evalf(expr, assumed_size, options)

    # We now know the size, so we can calculate how much extra precision
    # (if any) is needed to get within the nearest integer
    if ire and iim:
        gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
    elif ire:
        gap = fastlog(ire) - ire_acc
    elif iim:
        gap = fastlog(iim) - iim_acc
    else:
        # ... or maybe the expression was exactly zero
        return None, None, None, None

    margin = 10

    if gap >= -margin:
        ire, iim, ire_acc, iim_acc = \
            evalf(expr, margin + assumed_size + gap, options)

    # We can now easily find the nearest integer, but to find floor/ceil, we
    # must also calculate whether the difference to the nearest integer is
    # positive or negative (which may fail if very close).
    def calc_part(expr, nexpr):
        from sympy import Add
        nint = int(to_int(nexpr, rnd))
        n, c, p, b = nexpr
        if (c != 1 and p != 0) or p < 0:
            expr = Add(expr, -nint, evaluate=False)
            x, _, x_acc, _ = evalf(expr, 10, options)
            try:
                check_target(expr, (x, None, x_acc, None), 3)
            except PrecisionExhausted:
                if not expr.equals(0):
                    raise PrecisionExhausted
                x = fzero
            nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
        nint = from_int(nint)
        return nint, fastlog(nint) + 10

    re, im, re_acc, im_acc = None, None, None, None

    if ire:
        re, re_acc = calc_part(sympy.re(expr, evaluate=False), ire)
    if iim:
        im, im_acc = calc_part(sympy.im(expr, evaluate=False), iim)

    if return_ints:
        return int(to_int(re or fzero)), int(to_int(im or fzero))
    return re, im, re_acc, im_acc
Example #25
0
    def eval(cls, arg):
        from sympy import AccumBounds, im

        def _eval(arg):
            if arg is S.Infinity or arg is S.NegativeInfinity:
                return AccumBounds(0, 1)
            if arg.is_integer:
                return S.Zero
            if arg.is_number:
                if arg is S.NaN:
                    return S.NaN
                elif arg is S.ComplexInfinity:
                    return None
                else:
                    return arg - floor(arg)
            return cls(arg, evaluate=False)

        terms = Add.make_args(arg)
        real, imag = S.Zero, S.Zero
        for t in terms:
            # Two checks are needed for complex arguments
            # see issue-7649 for details
            if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
                i = im(t)
                if not i.has(S.ImaginaryUnit):
                    imag += i
                else:
                    real += t
            else:
                real += t

        real = _eval(real)
        imag = _eval(imag)
        return real + S.ImaginaryUnit*imag
Example #26
0
def real_root(arg, n=None):
    """Return the real nth-root of arg if possible. If n is omitted then
    all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this
    will only create a real root of a principle root -- the presence of
    other factors may cause the result to not be real.

    Examples
    ========

    >>> from sympy import root, real_root, Rational
    >>> from sympy.abc import x, n

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

    If one creates a non-principle 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 import im, Piecewise
    if n is not None:
        try:
            n = as_int(n)
            arg = sympify(arg)
            if arg.is_positive or arg.is_negative:
                rv = root(arg, n)
            else:
                raise ValueError
        except ValueError:
            return root(arg, n)*Piecewise(
                (S.One, ~Equality(im(arg), 0)),
                (Pow(S.NegativeOne, S.One/n)**(2*floor(n/2)), And(
                    Equality(n % 2, 1),
                    arg < 0)),
                (S.One, True))
    else:
        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)
def test_reduce_poly_inequalities_complex_relational():
    cond = Eq(im(x), 0)

    assert reduce_poly_inequalities(
        [[Eq(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities(
        [[Le(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities(
        [[Lt(x**2, 0)]], x, relational=True) is False
    assert reduce_poly_inequalities(
        [[Ge(x**2, 0)]], x, relational=True) == cond
    assert reduce_poly_inequalities([[Gt(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1)]], x, relational=True) == And(Or(Eq(re(x), -1), Eq(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1)]], x, relational=True) == And(And(Le(-1, re(x)), Le(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1)]], x, relational=True) == And(And(Lt(-1, re(x)), Lt(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1)]], x, relational=True) == And(Or(Le(re(x), -1), Le(1, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), Lt(1, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), And(Lt(-1, re(x)), Lt(re(x), 1)), Lt(1, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1.0)]], x, relational=True).evalf() == And(Or(Eq(re(x), -1.0), Eq(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1.0)]], x, relational=True) == And(And(Le(-1.0, re(x)), Le(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == And(And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == And(Or(Le(re(x), -1.0), Le(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), Lt(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), Lt(1.0, re(x))), cond)
Example #28
0
def attr_draw( z, func, scale, displays ):

    niter = 12  
    recurse = z - func / sympy.diff( func, z )   
    for x in range( -width/2, width/2 ):
        for y in range( -height/2, height/2 ):

            val = y*scale*sympy.I + x*scale
            for i in range( niter ):
                val = recurse.subs( z, val ).evalf()

            outx = sympy.re( val ).evalf()
            outy = sympy.im( val ).evalf()
            del val

            for disp in displays:
                if (outx - disp.x)**2 + (outy - disp.y)**2 < 0.2:
                    out = (x+width/2,height-(y+height/2))
                    print out
                    
                    screen.set_at( out, disp.c )
                    break

        print "Vertical line %d complete" % ( x )
        sympy.core.cache.clear_cache()

        event = pygame.event.poll()
        while event.type != pygame.NOEVENT:
            if event.type == pygame.QUIT:
                return False
            event = pygame.event.poll()
        pygame.display.flip()
Example #29
0
def test_quaternion_complex_real_addition():
    a = symbols("a", complex=True)
    b = symbols("b", real=True)
    # This symbol is not complex:
    c = symbols("c", commutative=False)

    q = Quaternion(x, y, z, w)
    assert a + q == Quaternion(x + re(a), y + im(a), z, w)
    assert 1 + q == Quaternion(1 + x, y, z, w)
    assert I + q == Quaternion(x, 1 + y, z, w)
    assert b + q == Quaternion(x + b, y, z, w)
    assert c + q == Add(c, Quaternion(x, y, z, w), evaluate=False)
    assert q * c == Mul(Quaternion(x, y, z, w), c, evaluate=False)
    assert c * q == Mul(c, Quaternion(x, y, z, w), evaluate=False)

    assert -q == Quaternion(-x, -y, -z, -w)

    q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
    q2 = Quaternion(1, 4, 7, 8)

    assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I)
    assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8)
    assert q1 * (2 + 3*I) == \
    Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I))
    assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5)
Example #30
0
def test_Pow_is_real():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True, positive=True)

    assert (x**2).is_real is True
    assert (x**3).is_real is True
    assert (x**x).is_real is None
    assert (y**x).is_real is True

    assert (x**Rational(1, 3)).is_real is None
    assert (y**Rational(1, 3)).is_real is True

    assert sqrt(-1 - sqrt(2)).is_real is False

    i = Symbol('i', imaginary=True)
    assert (i**i).is_real is None
    assert (I**i).is_real is None
    assert ((-I)**i).is_real is None
    assert (2**i).is_real is None  # (2**(pi/log(2) * I)) is real, 2**I is not
    assert (2**I).is_real is False
    assert (2**-I).is_real is False
    assert (i**2).is_real
    assert (i**3).is_real is False
    assert (i**x).is_real is None  # could be (-I)**(2/3)
    e = Symbol('e', even=True)
    o = Symbol('o', odd=True)
    k = Symbol('k', integer=True)
    assert (i**e).is_real
    assert (i**o).is_real is False
    assert (i**k).is_real is None

    x = Symbol("x", nonnegative=True)
    y = Symbol("y", nonnegative=True)
    assert im(x**y).expand(complex=True) is S.Zero
    assert (x**y).is_real
Example #31
0
def test_reduce_inequalities_multivariate():
    assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == \
        And(And(Or(Le(re(x), -1), Ge(re(x), 1)), Eq(im(x), 0)),
            And(Or(Le(re(y), -1), Ge(re(y), 1)), Eq(im(y), 0)))
Example #32
0
def reim(expr: Expr):
    return re(expr), im(expr)
Example #33
0
def test_coth():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert coth(nan) is nan
    assert coth(zoo) is nan

    assert coth(oo) == 1
    assert coth(-oo) == -1

    assert coth(0) is zoo
    assert unchanged(coth, 1)
    assert coth(-1) == -coth(1)

    assert unchanged(coth, x)
    assert coth(-x) == -coth(x)

    assert coth(pi * I) == -I * cot(pi)
    assert coth(-pi * I) == cot(pi) * I

    assert unchanged(coth, 2**1024 * E)
    assert coth(-2**1024 * E) == -coth(2**1024 * E)

    assert coth(pi * I) == -I * cot(pi)
    assert coth(-pi * I) == I * cot(pi)
    assert coth(2 * pi * I) == -I * cot(2 * pi)
    assert coth(-2 * pi * I) == I * cot(2 * pi)
    assert coth(-3 * 10**73 * pi * I) == I * cot(3 * 10**73 * pi)
    assert coth(7 * 10**103 * pi * I) == -I * cot(7 * 10**103 * pi)

    assert coth(pi * I / 2) == 0
    assert coth(-pi * I / 2) == 0
    assert coth(pi * I * Rational(5, 2)) == 0
    assert coth(pi * I * Rational(7, 2)) == 0

    assert coth(pi * I / 3) == -I / sqrt(3)
    assert coth(pi * I * Rational(-2, 3)) == -I / sqrt(3)

    assert coth(pi * I / 4) == -I
    assert coth(-pi * I / 4) == I
    assert coth(pi * I * Rational(17, 4)) == -I
    assert coth(pi * I * Rational(-3, 4)) == -I

    assert coth(pi * I / 6) == -sqrt(3) * I
    assert coth(-pi * I / 6) == sqrt(3) * I
    assert coth(pi * I * Rational(7, 6)) == -sqrt(3) * I
    assert coth(pi * I * Rational(-5, 6)) == -sqrt(3) * I

    assert coth(pi * I / 105) == -cot(pi / 105) * I
    assert coth(-pi * I / 105) == cot(pi / 105) * I

    assert unchanged(coth, 2 + 3 * I)

    assert coth(x * I) == -cot(x) * I

    assert coth(k * pi * I) == -cot(k * pi) * I
    assert coth(17 * k * pi * I) == -cot(17 * k * pi) * I

    assert coth(k * pi * I) == -cot(k * pi) * I

    assert coth(log(tan(2))) == coth(log(-tan(2)))
    assert coth(1 + I * pi / 2) == tanh(1)

    assert coth(x).as_real_imag(
        deep=False) == (sinh(re(x)) * cosh(re(x)) /
                        (sin(im(x))**2 + sinh(re(x))**2), -sin(im(x)) *
                        cos(im(x)) / (sin(im(x))**2 + sinh(re(x))**2))
    x = Symbol('x', extended_real=True)
    assert coth(x).as_real_imag(deep=False) == (coth(x), 0)

    assert expand_trig(coth(2 * x)) == (coth(x)**2 + 1) / (2 * coth(x))
    assert expand_trig(coth(
        3 * x)) == (coth(x)**3 + 3 * coth(x)) / (1 + 3 * coth(x)**2)

    assert expand_trig(
        coth(x + y)) == (1 + coth(x) * coth(y)) / (coth(x) + coth(y))
def test_fresnel():
    assert fresnels(0) == 0
    assert fresnels(oo) == S.Half
    assert fresnels(-oo) == Rational(-1, 2)
    assert fresnels(I * oo) == -I * S.Half

    assert unchanged(fresnels, z)
    assert fresnels(-z) == -fresnels(z)
    assert fresnels(I * z) == -I * fresnels(z)
    assert fresnels(-I * z) == I * fresnels(z)

    assert conjugate(fresnels(z)) == fresnels(conjugate(z))

    assert fresnels(z).diff(z) == sin(pi * z**2 / 2)

    assert fresnels(z).rewrite(erf) == (S.One + I) / 4 * (erf(
        (S.One + I) / 2 * sqrt(pi) * z) - I * erf(
            (S.One - I) / 2 * sqrt(pi) * z))

    assert fresnels(z).rewrite(hyper) == \
        pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16)

    assert fresnels(z).series(z, n=15) == \
        pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15)

    assert fresnels(w).is_extended_real is True
    assert fresnels(w).is_finite is True

    assert fresnels(z).is_extended_real is None
    assert fresnels(z).is_finite is None

    assert fresnels(z).as_real_imag() == (
        fresnels(re(z) - I * im(z)) / 2 + fresnels(re(z) + I * im(z)) / 2,
        -I * (-fresnels(re(z) - I * im(z)) + fresnels(re(z) + I * im(z))) / 2)

    assert fresnels(z).as_real_imag(deep=False) == (
        fresnels(re(z) - I * im(z)) / 2 + fresnels(re(z) + I * im(z)) / 2,
        -I * (-fresnels(re(z) - I * im(z)) + fresnels(re(z) + I * im(z))) / 2)

    assert fresnels(w).as_real_imag() == (fresnels(w), 0)
    assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0)

    assert fresnels(2 + 3 * I).as_real_imag() == (
        fresnels(2 + 3 * I) / 2 + fresnels(2 - 3 * I) / 2,
        -I * (fresnels(2 + 3 * I) - fresnels(2 - 3 * I)) / 2)

    assert expand_func(integrate(fresnels(z), z)) == \
        z*fresnels(z) + cos(pi*z**2/2)/pi

    assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \
        meijerg(((), (1,)), ((Rational(3, 4),),
        (Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4))

    assert fresnelc(0) == 0
    assert fresnelc(oo) == S.Half
    assert fresnelc(-oo) == Rational(-1, 2)
    assert fresnelc(I * oo) == I * S.Half

    assert unchanged(fresnelc, z)
    assert fresnelc(-z) == -fresnelc(z)
    assert fresnelc(I * z) == I * fresnelc(z)
    assert fresnelc(-I * z) == -I * fresnelc(z)

    assert conjugate(fresnelc(z)) == fresnelc(conjugate(z))

    assert fresnelc(z).diff(z) == cos(pi * z**2 / 2)

    assert fresnelc(z).rewrite(erf) == (S.One - I) / 4 * (erf(
        (S.One + I) / 2 * sqrt(pi) * z) + I * erf(
            (S.One - I) / 2 * sqrt(pi) * z))

    assert fresnelc(z).rewrite(hyper) == \
        z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16)

    assert fresnelc(w).is_extended_real is True

    assert fresnelc(z).as_real_imag() == \
        (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2,
         -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2)

    assert fresnelc(z).as_real_imag(deep=False) == \
        (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2,
         -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2)

    assert fresnelc(2 + 3 * I).as_real_imag() == (
        fresnelc(2 - 3 * I) / 2 + fresnelc(2 + 3 * I) / 2,
        -I * (fresnelc(2 + 3 * I) - fresnelc(2 - 3 * I)) / 2)

    assert expand_func(integrate(fresnelc(z), z)) == \
        z*fresnelc(z) - sin(pi*z**2/2)/pi

    assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \
        meijerg(((), (1,)), ((Rational(1, 4),),
        (Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4))

    from sympy.testing.randtest import verify_numerically

    verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z)
    verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z)
    verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z)
    verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z)

    verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z)
    verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z)
    verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z)
    verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z)

    raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2))
    raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2))

    assert fresnels(x).taylor_term(-1, x) is S.Zero
    assert fresnelc(x).taylor_term(-1, x) is S.Zero
    assert fresnelc(x).taylor_term(1, x) == -pi**2 * x**5 / 40
Example #35
0
def test_expand_function():
    assert expand(x + y) == x + y
    assert expand(x + y, complex=True) == I * im(x) + I * im(y) + re(x) + re(y)
    assert expand((x + y)**11, modulus=11) == x**11 + y**11
Example #36
0
def test_sign():
    assert sign(1.2) == 1
    assert sign(-1.2) == -1
    assert sign(3 * I) == I
    assert sign(-3 * I) == -I
    assert sign(0) == 0
    assert sign(nan) == nan
    assert sign(2 + 2 * I).doit() == sqrt(2) * (2 + 2 * I) / 4
    assert sign(2 + 3 * I).simplify() == sign(2 + 3 * I)
    assert sign(2 + 2 * I).simplify() == sign(1 + I)
    assert sign(im(sqrt(1 - sqrt(3)))) == 1
    assert sign(sqrt(1 - sqrt(3))) == I

    x = Symbol('x')
    assert sign(x).is_finite is True
    assert sign(x).is_complex is True
    assert sign(x).is_imaginary is None
    assert sign(x).is_integer is None
    assert sign(x).is_real is None
    assert sign(x).is_zero is None
    assert sign(x).doit() == sign(x)
    assert sign(1.2 * x) == sign(x)
    assert sign(2 * x) == sign(x)
    assert sign(I * x) == I * sign(x)
    assert sign(-2 * I * x) == -I * sign(x)
    assert sign(conjugate(x)) == conjugate(sign(x))

    p = Symbol('p', positive=True)
    n = Symbol('n', negative=True)
    m = Symbol('m', negative=True)
    assert sign(2 * p * x) == sign(x)
    assert sign(n * x) == -sign(x)
    assert sign(n * m * x) == sign(x)

    x = Symbol('x', imaginary=True)
    assert sign(x).is_imaginary is True
    assert sign(x).is_integer is False
    assert sign(x).is_real is False
    assert sign(x).is_zero is False
    assert sign(x).diff(x) == 2 * DiracDelta(-I * x)
    assert sign(x).doit() == x / Abs(x)
    assert conjugate(sign(x)) == -sign(x)

    x = Symbol('x', real=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is None
    assert sign(x).diff(x) == 2 * DiracDelta(x)
    assert sign(x).doit() == sign(x)
    assert conjugate(sign(x)) == sign(x)

    x = Symbol('x', nonzero=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = Symbol('x', positive=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = 0
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is True
    assert sign(x).doit() == 0
    assert sign(Abs(x)) == 0
    assert Abs(sign(x)) == 0

    nz = Symbol('nz', nonzero=True, integer=True)
    assert sign(nz).is_imaginary is False
    assert sign(nz).is_integer is True
    assert sign(nz).is_real is True
    assert sign(nz).is_zero is False
    assert sign(nz)**2 == 1
    assert (sign(nz)**3).args == (sign(nz), 3)

    assert sign(Symbol('x', nonnegative=True)).is_nonnegative
    assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
    assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
    assert sign(Symbol('x', nonpositive=True)).is_nonpositive
    assert sign(Symbol('x', real=True)).is_nonnegative is None
    assert sign(Symbol('x', real=True)).is_nonpositive is None
    assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None

    x, y = Symbol('x', real=True), Symbol('y')
    assert sign(x).rewrite(Piecewise) == \
        Piecewise((1, x > 0), (-1, x < 0), (0, True))
    assert sign(y).rewrite(Piecewise) == sign(y)
    assert sign(x).rewrite(Heaviside) == 2 * Heaviside(x) - 1
    assert sign(y).rewrite(Heaviside) == sign(y)

    # evaluate what can be evaluated
    assert sign(exp_polar(I * pi) * pi) is S.NegativeOne

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert sign(eq).func is sign or sign(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert sign(d).func is sign or sign(d) == 0
Example #37
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo * I) == oo
    assert im(-oo * I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E * I) == E
    assert im(-E * I) == -E

    assert im(x) == im(x)
    assert im(x * I) == re(x)
    assert im(r * I) == r
    assert im(r) == 0
    assert im(i * I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r * I) == im(x) + r

    assert im(im(x) * I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y * I) == im(x) + re(y)
    assert im(x + r * I) == im(x) + r

    assert im(log(2 * I)) == pi / 2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i * r * x).diff(r) == im(i * x)
    assert im(i * r * x).diff(i) == -I * re(r * x)

    assert im(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * sin(atan2(b, a) / 2)
    assert im(a * (2 + b * I)) == a * b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == x - re(x)
    assert (x + im(y)).rewrite(im, re) == x + y - re(y)
Example #38
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo * I) == oo
    assert im(-oo * I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E * I) == E
    assert im(-E * I) == -E

    assert unchanged(im, x)
    assert im(x * I) == re(x)
    assert im(r * I) == r
    assert im(r) == 0
    assert im(i * I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x) + im(y)
    assert im(x + r) == im(x)
    assert im(x + r * I) == im(x) + r

    assert im(im(x) * I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y * I) == im(x) + re(y)
    assert im(x + r * I) == im(x) + r

    assert im(log(2 * I)) == pi / 2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i * r * x).diff(r) == im(i * x)
    assert im(i * r * x).diff(i) == -I * re(r * x)

    assert im(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * sin(atan2(b, a) / 2)
    assert im(a * (2 + b * I)) == a * b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
    assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False

    assert im(S.ComplexInfinity) == S.NaN

    n, m, l = symbols('n m l')
    A = MatrixSymbol('A', n, m)

    assert im(A) == (S(1) / (2 * I)) * (A - conjugate(A))

    A = Matrix([[1 + 4 * I, 2], [0, -3 * I]])
    assert im(A) == Matrix([[4, 0], [0, -3]])

    A = ImmutableMatrix([[1 + 3 * I, 3 - 2 * I], [0, 2 * I]])
    assert im(A) == ImmutableMatrix([[3, -2], [0, 2]])

    X = ImmutableSparseMatrix([[i * I + i for i in range(5)]
                               for i in range(5)])
    Y = SparseMatrix([[i for i in range(5)] for i in range(5)])
    assert im(X).as_immutable() == Y

    X = FunctionMatrix(3, 3, Lambda((n, m), n + m * I))
    assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
Example #39
0
 def as_real_imag(self, deep=True, **hints):
     from sympy import im, re
     if hints.get('ignore') == self:
         return None
     else:
         return (re(self), im(self))
Example #40
0
def test_issue_12996():
    # foo=True imitates the sort of arguments that Derivative can get
    # from Integral when it passes doit to the expression
    assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x)
Example #41
0
def test_Abs():
    raises(TypeError, lambda: Abs(Interval(2, 3)))  # issue 8717

    x, y = symbols('x,y')
    assert sign(sign(x)) == sign(x)
    assert sign(x * y).func is sign
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1) == 1
    assert Abs(I) == 1
    assert Abs(-I) == 1
    assert Abs(nan) == nan
    assert Abs(zoo) == oo
    assert Abs(I * pi) == pi
    assert Abs(-I * pi) == pi
    assert Abs(I * x) == Abs(x)
    assert Abs(-I * x) == Abs(x)
    assert Abs(-2 * x) == 2 * Abs(x)
    assert Abs(-2.0 * x) == 2.0 * Abs(x)
    assert Abs(2 * pi * x * y) == 2 * pi * Abs(x * y)
    assert Abs(conjugate(x)) == Abs(x)
    assert conjugate(Abs(x)) == Abs(x)
    assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)

    a = Symbol('a', positive=True)
    assert Abs(2 * pi * x * a) == 2 * pi * a * Abs(x)
    assert Abs(2 * pi * I * x * a) == 2 * pi * a * Abs(x)

    x = Symbol('x', real=True)
    n = Symbol('n', integer=True)
    assert Abs((-1)**n) == 1
    assert x**(2 * n) == Abs(x)**(2 * n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x)  # Python built-in
    assert Abs(x)**3 == x**2 * Abs(x)
    assert Abs(x)**4 == x**4
    assert (Abs(x)**(3 * n)).args == (Abs(x), 3 * n
                                      )  # leave symbolic odd unchanged
    assert (1 / Abs(x)).args == (Abs(x), -1)
    assert 1 / Abs(x)**3 == 1 / (x**2 * Abs(x))
    assert Abs(x)**-3 == Abs(x) / (x**4)
    assert Abs(x**3) == x**2 * Abs(x)
    assert Abs(I**I) == exp(-pi / 2)
    assert Abs((4 + 5 * I)**(6 + 7 * I)) == 68921 * exp(-7 * atan(S(5) / 4))
    y = Symbol('y', real=True)
    assert Abs(I**y) == 1
    y = Symbol('y')
    assert Abs(I**y) == exp(-pi * im(y) / 2)

    x = Symbol('x', imaginary=True)
    assert Abs(x).diff(x) == -sign(x)

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when you can and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert abs(eq).func is Abs or abs(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert abs(d).func is Abs or abs(d) == 0

    assert Abs(4 * exp(pi * I / 4)) == 4
    assert Abs(3**(2 + I)) == 9
    assert Abs((-3)**(1 - I)) == 3 * exp(pi)

    assert Abs(oo) is oo
    assert Abs(-oo) is oo
    assert Abs(oo + I) is oo
    assert Abs(oo + I * oo) is oo

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
    assert Abs(x).fdiff() == sign(x)
    raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))

    # doesn't have recursion error
    arg = sqrt(acos(1 - I) * acos(1 + I))
    assert abs(arg) == arg

    # special handling to put Abs in denom
    assert abs(1 / x) == 1 / Abs(x)
    e = abs(2 / x**2)
    assert e.is_Mul and e == 2 / Abs(x**2)
    assert unchanged(Abs, y / x)
    assert unchanged(Abs, x / (x + 1))
    assert unchanged(Abs, x * y)
    p = Symbol('p', positive=True)
    assert abs(x / p) == abs(x) / p

    # coverage
    assert unchanged(Abs, Symbol('x', real=True)**y)
Example #42
0
def test_cosh():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert cosh(nan) is nan
    assert cosh(zoo) is nan

    assert cosh(oo) is oo
    assert cosh(-oo) is oo

    assert cosh(0) == 1

    assert unchanged(cosh, 1)
    assert cosh(-1) == cosh(1)

    assert unchanged(cosh, x)
    assert cosh(-x) == cosh(x)

    assert cosh(pi * I) == cos(pi)
    assert cosh(-pi * I) == cos(pi)

    assert unchanged(cosh, 2**1024 * E)
    assert cosh(-2**1024 * E) == cosh(2**1024 * E)

    assert cosh(pi * I / 2) == 0
    assert cosh(-pi * I / 2) == 0
    assert cosh((-3 * 10**73 + 1) * pi * I / 2) == 0
    assert cosh((7 * 10**103 + 1) * pi * I / 2) == 0

    assert cosh(pi * I) == -1
    assert cosh(-pi * I) == -1
    assert cosh(5 * pi * I) == -1
    assert cosh(8 * pi * I) == 1

    assert cosh(pi * I / 3) == S.Half
    assert cosh(pi * I * Rational(-2, 3)) == Rational(-1, 2)

    assert cosh(pi * I / 4) == S.Half * sqrt(2)
    assert cosh(-pi * I / 4) == S.Half * sqrt(2)
    assert cosh(pi * I * Rational(11, 4)) == Rational(-1, 2) * sqrt(2)
    assert cosh(pi * I * Rational(-3, 4)) == Rational(-1, 2) * sqrt(2)

    assert cosh(pi * I / 6) == S.Half * sqrt(3)
    assert cosh(-pi * I / 6) == S.Half * sqrt(3)
    assert cosh(pi * I * Rational(7, 6)) == Rational(-1, 2) * sqrt(3)
    assert cosh(pi * I * Rational(-5, 6)) == Rational(-1, 2) * sqrt(3)

    assert cosh(pi * I / 105) == cos(pi / 105)
    assert cosh(-pi * I / 105) == cos(pi / 105)

    assert unchanged(cosh, 2 + 3 * I)

    assert cosh(x * I) == cos(x)

    assert cosh(k * pi * I) == cos(k * pi)
    assert cosh(17 * k * pi * I) == cos(17 * k * pi)

    assert unchanged(cosh, k * pi)

    assert cosh(x).as_real_imag(deep=False) == (cos(im(x)) * cosh(re(x)),
                                                sin(im(x)) * sinh(re(x)))
    x = Symbol('x', extended_real=True)
    assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)

    x = Symbol('x', real=True)
    assert cosh(I * x).is_finite is True
    assert cosh(I * x).is_real is True
    assert cosh(I * 2 + 1).is_real is False
Example #43
0
def test_re_im1652():
    x = Symbol('x')
    assert re(x) == re(conjugate(x))
    assert im(x) == - im(conjugate(x))
    assert im(x)*re(conjugate(x)) + im(conjugate(x)) * re(x) == 0
Example #44
0
def test_polygamma():
    from sympy import I

    assert polygamma(n, nan) == nan

    assert polygamma(0, oo) == oo
    assert polygamma(0, -oo) == oo
    assert polygamma(0, I*oo) == oo
    assert polygamma(0, -I*oo) == oo
    assert polygamma(1, oo) == 0
    assert polygamma(5, oo) == 0

    assert polygamma(0, -9) == zoo

    assert polygamma(0, -9) == zoo
    assert polygamma(0, -1) == zoo

    assert polygamma(0, 0) == zoo

    assert polygamma(0, 1) == -EulerGamma
    assert polygamma(0, 7) == Rational(49, 20) - EulerGamma

    assert polygamma(1, 1) == pi**2/6
    assert polygamma(1, 2) == pi**2/6 - 1
    assert polygamma(1, 3) == pi**2/6 - Rational(5, 4)
    assert polygamma(3, 1) == pi**4 / 15
    assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90)
    assert polygamma(5, 1) == 8 * pi**6 / 63

    def t(m, n):
        x = S(m)/n
        r = polygamma(0, x)
        if r.has(polygamma):
            return False
        return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10
    assert t(1, 2)
    assert t(3, 2)
    assert t(-1, 2)
    assert t(1, 4)
    assert t(-3, 4)
    assert t(1, 3)
    assert t(4, 3)
    assert t(3, 4)
    assert t(2, 3)
    assert t(123, 5)

    assert polygamma(0, x).rewrite(zeta) == polygamma(0, x)
    assert polygamma(1, x).rewrite(zeta) == zeta(2, x)
    assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x)
    assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2)
    n1 = Symbol('n1')
    n2 = Symbol('n2', real=True)
    n3 = Symbol('n3', integer=True)
    n4 = Symbol('n4', positive=True)
    n5 = Symbol('n5', positive=True, integer=True)
    assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x)
    assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x)
    assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x)
    assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x)
    assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x)

    assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x)

    assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma
    assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3)
    ni = Symbol("n", integer=True)
    assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1)
                                                                 + zeta(ni + 1))*factorial(ni)

    # Polygamma of non-negative integer order is unbranched:
    from sympy import exp_polar
    k = Symbol('n', integer=True, nonnegative=True)
    assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x)

    # but negative integers are branched!
    k = Symbol('n', integer=True)
    assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x)

    # Polygamma of order -1 is loggamma:
    assert polygamma(-1, x) == loggamma(x)

    # But smaller orders are iterated integrals and don't have a special name
    assert polygamma(-2, x).func is polygamma

    # Test a bug
    assert polygamma(0, -x).expand(func=True) == polygamma(0, -x)

    assert polygamma(2, 2.5).is_positive == False
    assert polygamma(2, -2.5).is_positive == False
    assert polygamma(3, 2.5).is_positive == True
    assert polygamma(3, -2.5).is_positive is None
    assert polygamma(-2, -2.5).is_positive is None
    assert polygamma(-3, -2.5).is_positive is None

    assert polygamma(2, 2.5).is_negative == True
    assert polygamma(3, 2.5).is_negative == False
    assert polygamma(3, -2.5).is_negative == False
    assert polygamma(2, -2.5).is_negative is None
    assert polygamma(-2, -2.5).is_negative is None
    assert polygamma(-3, -2.5).is_negative is None

    assert polygamma(I, 2).is_positive is None
    assert polygamma(I, 3).is_negative is None

    # issue 17350
    assert polygamma(pi, 3).evalf() == polygamma(pi, 3)
    assert (I*polygamma(I, pi)).as_real_imag() == \
           (-im(polygamma(I, pi)), re(polygamma(I, pi)))
    assert (tanh(polygamma(I, 1))).rewrite(exp) == \
           (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1)))
    assert (I / polygamma(I, 4)).rewrite(exp) == \
           I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\
           /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4)))
    assert unchanged(polygamma, 2.3, 1.0)

    # issue 12569
    assert unchanged(im, polygamma(0, I))
    assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True
    assert polygamma(0, I).is_real is None
Example #45
0
    def eval(cls, arg):
        from sympy.calculus import AccumBounds
        from sympy.sets.setexpr import SetExpr
        from sympy.matrices.matrices import MatrixBase
        from sympy import im, logcombine, re
        if isinstance(arg, MatrixBase):
            return arg.exp()
        elif global_parameters.exp_is_pow:
            return Pow(S.Exp1, arg)
        elif arg.is_Number:
            if arg is S.NaN:
                return S.NaN
            elif arg.is_zero:
                return S.One
            elif arg is S.One:
                return S.Exp1
            elif arg is S.Infinity:
                return S.Infinity
            elif arg is S.NegativeInfinity:
                return S.Zero
        elif arg is S.ComplexInfinity:
            return S.NaN
        elif isinstance(arg, log):
            return arg.args[0]
        elif isinstance(arg, AccumBounds):
            return AccumBounds(exp(arg.min), exp(arg.max))
        elif isinstance(arg, SetExpr):
            return arg._eval_func(cls)
        elif arg.is_Mul:
            coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
            if coeff:
                if (2*coeff).is_integer:
                    if coeff.is_even:
                        return S.One
                    elif coeff.is_odd:
                        return S.NegativeOne
                    elif (coeff + S.Half).is_even:
                        return -S.ImaginaryUnit
                    elif (coeff + S.Half).is_odd:
                        return S.ImaginaryUnit
                elif coeff.is_Rational:
                    ncoeff = coeff % 2 # restrict to [0, 2pi)
                    if ncoeff > 1: # restrict to (-pi, pi]
                        ncoeff -= 2
                    if ncoeff != coeff:
                        return cls(ncoeff*S.Pi*S.ImaginaryUnit)

            # Warning: code in risch.py will be very sensitive to changes
            # in this (see DifferentialExtension).

            # look for a single log factor

            coeff, terms = arg.as_coeff_Mul()

            # but it can't be multiplied by oo
            if coeff in [S.NegativeInfinity, S.Infinity]:
                if terms.is_number:
                    if coeff is S.NegativeInfinity:
                        terms = -terms
                    if re(terms).is_zero and terms is not S.Zero:
                        return S.NaN
                    if re(terms).is_positive and im(terms) is not S.Zero:
                        return S.ComplexInfinity
                    if re(terms).is_negative:
                        return S.Zero
                return None

            coeffs, log_term = [coeff], None
            for term in Mul.make_args(terms):
                term_ = logcombine(term)
                if isinstance(term_, log):
                    if log_term is None:
                        log_term = term_.args[0]
                    else:
                        return None
                elif term.is_comparable:
                    coeffs.append(term)
                else:
                    return None

            return log_term**Mul(*coeffs) if log_term else None

        elif arg.is_Add:
            out = []
            add = []
            argchanged = False
            for a in arg.args:
                if a is S.One:
                    add.append(a)
                    continue
                newa = cls(a)
                if isinstance(newa, cls):
                    if newa.args[0] != a:
                        add.append(newa.args[0])
                        argchanged = True
                    else:
                        add.append(a)
                else:
                    out.append(newa)
            if out or argchanged:
                return Mul(*out)*cls(Add(*add), evaluate=False)

        if arg.is_zero:
            return S.One
Example #46
0
def inverse_laplace_ratfun(expr, s, t):

    N, D, delay = Ratfun(expr, s).as_ratfun_delay()
    # The delay should be zero

    Q, M = sym.div(N, D, s)

    result1 = sym.S.Zero

    if Q:
        Qpoly = sym.Poly(Q, s)        
        C = Qpoly.all_coeffs()
        for n, c in enumerate(C):
            result1 += c * sym.diff(sym.DiracDelta(t), t, len(C) - n - 1)

    expr = M / D
    for factor in expr.as_ordered_factors():
        if factor == sym.oo:
            return factor

    sexpr = Ratfun(expr, s)
    P = sexpr.poles()
    result2 = sym.S.Zero

    P2 = P.copy()

    for p in P2:

        # Number of occurrences of the pole.
        N = P2[p]

        if N == 0:
            continue

        f = s - p

        if N == 1:
            r = sexpr.residue(p, P)

            pc = p.conjugate()
            if pc != p and pc in P:
                # Remove conjugate from poles and process pole with its
                # conjugate.  Unfortunately, for symbolic expressions
                # we cannot tell if a quadratic has two real poles,
                # a repeat real pole, or a complex conjugate pair of poles.
                P2[pc] = 0
                
                p_re = sym.re(p)
                p_im = sym.im(p)
                r_re = sym.re(r)
                r_im = sym.im(r)
                et = sym.exp(p_re * t)
                result2 += 2 * r_re * et * sym.cos(p_im * t)
                result2 -= 2 * r_im * et * sym.sin(p_im * t)
            else:
                result2 += r * sym.exp(p * t)
            continue

        # Handle repeated poles.
        expr2 = expr * f ** N
        for n in range(1, N + 1):
            m = N - n
            r = sym.limit(
                sym.diff(expr2, s, m), s, p) / sym.factorial(m)
            result2 += r * sym.exp(p * t) * t**(n - 1)

    # result1 is a sum of Dirac deltas and its derivatives so is known
    # to be causal.

    return result1, result2
    Uravnenie_all.append(expr2)

print(
    "\nСистема уравнений или условия Куна-Таккера имеют следующий вид (при этом Nu1, Nu2 ,... >= 0 и все лямбды имеют произвольный знак)\n",
    Uravnenie_all)

#Решение системы уравнений дает множество решений, далее мы их будем фильтровать
Solution = solve((Uravnenie_all), dict=True)

#избавляемся от решений с мнимыми числами
Non_imaginary = []
count_imag = 0
for i in range(len(Solution)):
    count_imag = 0
    for j in range(0, len(keys_lambda)):
        if im(Solution[i][keys_lambda[j]]) != 0:
            count_imag = count_imag + 1
    if count_imag == 0:
        Non_imaginary.append(Solution[i])

#Находим решения где все x и Nu >= 0
count_Nu = 0
Non_zero_Nu = []
for i in range(0, len(Non_imaginary)):
    count_Nu = 0
    for j in range(0, len(keys_Nu)):
        if Non_imaginary[i][keys_Nu[j]] < 0:
            count_Nu = count_Nu + 1
    if count_Nu == 0:
        Non_zero_Nu.append(Non_imaginary[i])
Example #48
0
def test_sinh():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert sinh(nan) is nan
    assert sinh(zoo) is nan

    assert sinh(oo) is oo
    assert sinh(-oo) is -oo

    assert sinh(0) == 0

    assert unchanged(sinh, 1)
    assert sinh(-1) == -sinh(1)

    assert unchanged(sinh, x)
    assert sinh(-x) == -sinh(x)

    assert unchanged(sinh, pi)
    assert sinh(-pi) == -sinh(pi)

    assert unchanged(sinh, 2**1024 * E)
    assert sinh(-2**1024 * E) == -sinh(2**1024 * E)

    assert sinh(pi * I) == 0
    assert sinh(-pi * I) == 0
    assert sinh(2 * pi * I) == 0
    assert sinh(-2 * pi * I) == 0
    assert sinh(-3 * 10**73 * pi * I) == 0
    assert sinh(7 * 10**103 * pi * I) == 0

    assert sinh(pi * I / 2) == I
    assert sinh(-pi * I / 2) == -I
    assert sinh(pi * I * Rational(5, 2)) == I
    assert sinh(pi * I * Rational(7, 2)) == -I

    assert sinh(pi * I / 3) == S.Half * sqrt(3) * I
    assert sinh(pi * I * Rational(-2, 3)) == Rational(-1, 2) * sqrt(3) * I

    assert sinh(pi * I / 4) == S.Half * sqrt(2) * I
    assert sinh(-pi * I / 4) == Rational(-1, 2) * sqrt(2) * I
    assert sinh(pi * I * Rational(17, 4)) == S.Half * sqrt(2) * I
    assert sinh(pi * I * Rational(-3, 4)) == Rational(-1, 2) * sqrt(2) * I

    assert sinh(pi * I / 6) == S.Half * I
    assert sinh(-pi * I / 6) == Rational(-1, 2) * I
    assert sinh(pi * I * Rational(7, 6)) == Rational(-1, 2) * I
    assert sinh(pi * I * Rational(-5, 6)) == Rational(-1, 2) * I

    assert sinh(pi * I / 105) == sin(pi / 105) * I
    assert sinh(-pi * I / 105) == -sin(pi / 105) * I

    assert unchanged(sinh, 2 + 3 * I)

    assert sinh(x * I) == sin(x) * I

    assert sinh(k * pi * I) == 0
    assert sinh(17 * k * pi * I) == 0

    assert sinh(k * pi * I / 2) == sin(k * pi / 2) * I

    assert sinh(x).as_real_imag(deep=False) == (cos(im(x)) * sinh(re(x)),
                                                sin(im(x)) * cosh(re(x)))
    x = Symbol('x', extended_real=True)
    assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)

    x = Symbol('x', real=True)
    assert sinh(I * x).is_finite is True
    assert sinh(x).is_real is True
    assert sinh(I).is_real is False
def test_erf():
    assert erf(nan) is nan

    assert erf(oo) == 1
    assert erf(-oo) == -1

    assert erf(0) == 0

    assert erf(I * oo) == oo * I
    assert erf(-I * oo) == -oo * I

    assert erf(-2) == -erf(2)
    assert erf(-x * y) == -erf(x * y)
    assert erf(-x - y) == -erf(x + y)

    assert erf(erfinv(x)) == x
    assert erf(erfcinv(x)) == 1 - x
    assert erf(erf2inv(0, x)) == x
    assert erf(erf2inv(0, x, evaluate=False)) == x  # To cover code in erf
    assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x

    assert erf(I).is_real is False
    assert erf(0).is_real is True

    assert conjugate(erf(z)) == erf(conjugate(z))

    assert erf(x).as_leading_term(x) == 2 * x / sqrt(pi)
    assert erf(x * y).as_leading_term(y) == 2 * x * y / sqrt(pi)
    assert (erf(x * y) / erf(y)).as_leading_term(y) == x
    assert erf(1 / x).as_leading_term(x) == S.One

    assert erf(z).rewrite('uppergamma') == sqrt(z**
                                                2) * (1 - erfc(sqrt(z**2))) / z
    assert erf(z).rewrite('erfc') == S.One - erfc(z)
    assert erf(z).rewrite('erfi') == -I * erfi(I * z)
    assert erf(z).rewrite('fresnels') == (1 + I) * (
        fresnelc(z * (1 - I) / sqrt(pi)) - I * fresnels(z *
                                                        (1 - I) / sqrt(pi)))
    assert erf(z).rewrite('fresnelc') == (1 + I) * (
        fresnelc(z * (1 - I) / sqrt(pi)) - I * fresnels(z *
                                                        (1 - I) / sqrt(pi)))
    assert erf(z).rewrite('hyper') == 2 * z * hyper([S.Half], [3 * S.Half],
                                                    -z**2) / sqrt(pi)
    assert erf(z).rewrite('meijerg') == z * meijerg(
        [S.Half], [], [0], [Rational(-1, 2)], z**2) / sqrt(pi)
    assert erf(z).rewrite(
        'expint') == sqrt(z**2) / z - z * expint(S.Half, z**2) / sqrt(S.Pi)

    assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \
        2/sqrt(pi)
    assert limit((1 - erf(z)) * exp(z**2) * z, z, oo) == 1 / sqrt(pi)
    assert limit((1 - erf(x)) * exp(x**2) * sqrt(pi) * x, x, oo) == 1
    assert limit(((1 - erf(x)) * exp(x**2) * sqrt(pi) * x - 1) * 2 * x**2, x,
                 oo) == -1
    assert limit(erf(x) / x, x, 0) == 2 / sqrt(pi)
    assert limit(x**(-4) - sqrt(pi) * erf(x**2) / (2 * x**6), x, 0) == S(1) / 3

    assert erf(x).as_real_imag() == \
        (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2,
         -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2)

    assert erf(x).as_real_imag(deep=False) == \
        (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2,
         -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2)

    assert erf(w).as_real_imag() == (erf(w), 0)
    assert erf(w).as_real_imag(deep=False) == (erf(w), 0)
    # issue 13575
    assert erf(I).as_real_imag() == (0, -I * erf(I))

    raises(ArgumentIndexError, lambda: erf(x).fdiff(2))

    assert erf(x).inverse() == erfinv
Example #50
0
def test_tanh():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert tanh(nan) is nan
    assert tanh(zoo) is nan

    assert tanh(oo) == 1
    assert tanh(-oo) == -1

    assert tanh(0) == 0

    assert unchanged(tanh, 1)
    assert tanh(-1) == -tanh(1)

    assert unchanged(tanh, x)
    assert tanh(-x) == -tanh(x)

    assert unchanged(tanh, pi)
    assert tanh(-pi) == -tanh(pi)

    assert unchanged(tanh, 2**1024 * E)
    assert tanh(-2**1024 * E) == -tanh(2**1024 * E)

    assert tanh(pi * I) == 0
    assert tanh(-pi * I) == 0
    assert tanh(2 * pi * I) == 0
    assert tanh(-2 * pi * I) == 0
    assert tanh(-3 * 10**73 * pi * I) == 0
    assert tanh(7 * 10**103 * pi * I) == 0

    assert tanh(pi * I / 2) is zoo
    assert tanh(-pi * I / 2) is zoo
    assert tanh(pi * I * Rational(5, 2)) is zoo
    assert tanh(pi * I * Rational(7, 2)) is zoo

    assert tanh(pi * I / 3) == sqrt(3) * I
    assert tanh(pi * I * Rational(-2, 3)) == sqrt(3) * I

    assert tanh(pi * I / 4) == I
    assert tanh(-pi * I / 4) == -I
    assert tanh(pi * I * Rational(17, 4)) == I
    assert tanh(pi * I * Rational(-3, 4)) == I

    assert tanh(pi * I / 6) == I / sqrt(3)
    assert tanh(-pi * I / 6) == -I / sqrt(3)
    assert tanh(pi * I * Rational(7, 6)) == I / sqrt(3)
    assert tanh(pi * I * Rational(-5, 6)) == I / sqrt(3)

    assert tanh(pi * I / 105) == tan(pi / 105) * I
    assert tanh(-pi * I / 105) == -tan(pi / 105) * I

    assert unchanged(tanh, 2 + 3 * I)

    assert tanh(x * I) == tan(x) * I

    assert tanh(k * pi * I) == 0
    assert tanh(17 * k * pi * I) == 0

    assert tanh(k * pi * I / 2) == tan(k * pi / 2) * I

    assert tanh(x).as_real_imag(
        deep=False) == (sinh(re(x)) * cosh(re(x)) /
                        (cos(im(x))**2 + sinh(re(x))**2), sin(im(x)) *
                        cos(im(x)) / (cos(im(x))**2 + sinh(re(x))**2))
    x = Symbol('x', extended_real=True)
    assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
    assert tanh(I * pi / 3 + 1).is_real is False
    assert tanh(x).is_real is True
    assert tanh(I * pi * x / 2).is_real is None
Example #51
0
def test_issue_7450():
    ans = integrate(exp(-(1 + I) * x), (x, 0, oo))
    assert re(ans) == S.Half and im(ans) == -S.Half
Example #52
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(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 )}"
Example #53
0
 def getPhase(self):
     self.H = self.solution[self.Vo]/self.solution[self.Vi]
     self.H = simplify(self.H)
     self.mod = simplify(sqrt(re(self.H)**2+im(self.H)**2))
     self.phase = simplify(tan(im(self.H)/re(self.H))*180/3.14195)
     return self.phase
Example #54
0
    def _eval_nseries(self, x, n, logx, cdir=0):
        # NOTE Please see the comment at the beginning of this file, labelled
        #      IMPORTANT.
        from sympy import im, cancel, I, Order, logcombine
        from itertools import product
        if not logx:
            logx = log(x)
        if self.args[0] == x:
            return logx
        arg = self.args[0]
        k, l = Wild("k"), Wild("l")
        r = arg.match(k*x**l)
        if r is not None:
            k, l = r[k], r[l]
            if l != 0 and not l.has(x) and not k.has(x):
                r = log(k) + l*logx  # XXX true regardless of assumptions?
                return r

        def coeff_exp(term, x):
            coeff, exp = S.One, S.Zero
            for factor in Mul.make_args(term):
                if factor.has(x):
                    base, exp = factor.as_base_exp()
                    if base != x:
                        try:
                            return term.leadterm(x)
                        except ValueError:
                            return term, S.Zero
                else:
                    coeff *= factor
            return coeff, exp

        # TODO new and probably slow
        try:
            a, b = arg.leadterm(x)
            s = arg.nseries(x, n=n+b, logx=logx)
        except (ValueError, NotImplementedError, PoleError):
            s = arg.nseries(x, n=n, logx=logx)
            while s.is_Order:
                n += 1
                s = arg.nseries(x, n=n, logx=logx)
        a, b = s.removeO().leadterm(x)
        p = cancel(s/(a*x**b) - 1).expand().powsimp()
        if p.has(exp):
            p = logcombine(p)
        if isinstance(p, Order):
            n = p.getn()
        _, d = coeff_exp(p, x)
        if not d.is_positive:
            return log(a) + b*logx + Order(x**n, x)

        def mul(d1, d2):
            res = {}
            for e1, e2 in product(d1, d2):
                ex = e1 + e2
                if ex < n:
                    res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
            return res

        pterms = {}

        for term in Add.make_args(p):
            co1, e1 = coeff_exp(term, x)
            pterms[e1] = pterms.get(e1, S.Zero) + co1.removeO()

        k = S.One
        terms = {}
        pk = pterms

        while k*d < n:
            coeff = -(-1)**k/k
            for ex in pk:
                terms[ex] = terms.get(ex, S.Zero) + coeff*pk[ex]
            pk = mul(pk, pterms)
            k += S.One

        res = log(a) + b*logx
        for ex in terms:
            res += terms[ex]*x**(ex)

        if cdir != 0:
            cdir = self.args[0].dir(x, cdir)
        if a.is_real and a.is_negative and im(cdir) < 0:
            res -= 2*I*S.Pi
        return res + Order(x**n, x)
Example #55
0
    def ratfun(self, expr, s, t, **kwargs):

        if kwargs.pop('pdb', False):
            import pdb
            pdb.set_trace()

        sexpr = Ratfun(expr, s)

        if kwargs.get('damped_sin', False):
            if sexpr.degree == 2:
                return self.do_damped_sin(sexpr, s, t)
            # if False and sexpr.degree == 3 and Ratfun(expr * s).degree == 2:
            #    return self.do_damped_sin3(sexpr, s, t)

        self.debug('Finding QRPO representation')

        damping = kwargs.get('damping', None)
        Q, R, P, O, delay, undef = sexpr.as_QRPO(damping)

        if delay != 0:
            # This will be caught and trigger expansion of the expression.
            self.error('Unhandled delay %s' % delay)

        cresult = Zero

        if Q:
            Qpoly = sym.Poly(Q, s)
            C = Qpoly.all_coeffs()
            for n, c in enumerate(C):
                cresult += c * sym.diff(sym.DiracDelta(t), t, len(C) - n - 1)

        if R == []:
            return cresult, 0

        uresult = 0
        for m, (p, n, A) in enumerate(zip(P, O, R)):

            # This is zero for the conjugate pole.
            if R[m] == 0:
                continue

            # Search and remove conjugate pair.
            has_conjpair = False
            if p.is_complex and kwargs.get('pairs', True):
                pc = p.conjugate()
                Ac = A.conjugate()
                for m2, p2 in enumerate(P[m + 1:]):
                    m2 += m + 1
                    if n == O[m2] and p2 == pc and R[m2] == Ac:
                        R[m2] = 0
                        has_conjpair = True
                        break

            if has_conjpair:
                # Combine conjugate pairs.
                p = p.expand(complex=True)
                A = A.expand(complex=True)
                p_re = sym.re(p)
                p_im = sym.im(p)
                A_re = sym.re(A)
                A_im = sym.im(A)
                et = sym.exp(p_re * t)
                result = 2 * A_re * et * sym.cos(p_im * t)
                result -= 2 * A_im * et * sym.sin(p_im * t)
            else:
                result = A * sym.exp(p * t)

            if n > 1:
                result *= t**(n - 1) / sym.factorial(n - 1)
            uresult += result

        # cresult is a sum of Dirac deltas and its derivatives so is known
        # to be causal.

        return cresult, uresult
Example #56
0
def test_issue_1985():
    x = Symbol('x')
    assert ((x + x*I)/(1 + I)).as_real_imag() == (re((x + I*x)/(1 + I)), im((x + I*x)/(1 + I)))
Example #57
0
def test_expand_function():
    assert expand(x + y) == x + y
    assert expand(x + y, complex=True) == I * im(x) + I * im(y) + re(x) + re(y)
Example #58
0
def test_reduce_inequalities_boolean():
    assert reduce_inequalities([Eq(x**2, 0),
                                True]) == And(Eq(re(x), 0), Eq(im(x), 0))
    assert reduce_inequalities([Eq(x**2, 0), False]) is False
Example #59
0
def test_re():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert unchanged(re, x)
    assert re(x * I) == -im(x)
    assert re(r * I) == 0
    assert re(r) == r
    assert re(i * I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x) + re(y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y * I) == re(x) - im(y)
    assert re(x + r * I) == re(x)

    assert re(log(2 * I)) == log(2)

    assert re((2 + I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i * r * x).diff(r) == re(i * x)
    assert re(i * r * x).diff(i) == I * r * im(x)

    assert re(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * cos(atan2(b, a) / 2)
    assert re(a * (2 + b * I)) == 2 * a

    assert re((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2)

    assert re(x).rewrite(im) == x - S.ImaginaryUnit * im(x)
    assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit * im(y)

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False

    assert re(S.ComplexInfinity) == S.NaN

    n, m, l = symbols('n m l')
    A = MatrixSymbol('A', n, m)
    assert re(A) == (S(1) / 2) * (A + conjugate(A))

    A = Matrix([[1 + 4 * I, 2], [0, -3 * I]])
    assert re(A) == Matrix([[1, 2], [0, 0]])

    A = ImmutableMatrix([[1 + 3 * I, 3 - 2 * I], [0, 2 * I]])
    assert re(A) == ImmutableMatrix([[1, 3], [0, 0]])

    X = SparseMatrix([[2 * j + i * I for i in range(5)] for j in range(5)])
    assert re(X) - Matrix([[0, 0, 0, 0, 0], [2, 2, 2, 2, 2], [4, 4, 4, 4, 4],
                           [6, 6, 6, 6, 6], [8, 8, 8, 8, 8]
                           ]) == Matrix.zeros(5)

    assert im(X) - Matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4],
                           [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]
                           ]) == Matrix.zeros(5)

    X = FunctionMatrix(3, 3, Lambda((n, m), n + m * I))
    assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
Example #60
0
    def PlotDensityMatrix(self, imaginary=False, decimal=False):
        size_p = self.getNumberOfQubits()  # número de qubits
        mRho = [[0] * 2**size_p for i in range(2**size_p)]
        rho = self.DensityMatrix().get()
        for id1 in range(2**size_p):
            for id2 in range(2**size_p):
                if self.getCuda():
                    value = rho[id1][id2]
                    if (not imaginary):
                        value = value.item().real
                    else:
                        value = value.item().imag
                else:
                    value = rho[id1, id2]
                    if (not imaginary):
                        value = sp.re(value)
                    else:
                        value = sp.im(value)
                mRho[id1][id2] = value

        result = np.array(mRho, dtype=np.float)
        fig = plt.figure(figsize=(5, 5), dpi=150)
        ax1 = fig.add_subplot(111, projection='3d')

        size = 2**size_p
        if (not decimal):
            labels = [
                "|" + "{0:b}".format(i).zfill(size_p) + ">"
                for i in range(size)
            ]
        else:
            labels = [i for i in range(size)]
        xlabels = np.array(labels)
        xpos = np.arange(xlabels.shape[0])
        ylabels = np.array(labels)
        ypos = np.arange(ylabels.shape[0])

        xpos_mesh, ypos_mesh = np.meshgrid(xpos, ypos, copy=False)

        zpos = result
        zpos = zpos.ravel()

        dx = 0.5
        dy = 0.5
        dz = zpos

        ax1.w_xaxis.set_ticks(xpos + dx / 2.)
        ax1.w_xaxis.set_ticklabels(xlabels)
        ax1.w_yaxis.set_ticks(ypos + dy / 2.)
        ax1.w_yaxis.set_ticklabels(ylabels)

        values = np.linspace(0.2, 1., xpos_mesh.ravel().shape[0])
        colors = cm.rainbow(values)
        ax1.bar3d(xpos_mesh.ravel(),
                  ypos_mesh.ravel(),
                  dz * 0,
                  dx,
                  dy,
                  dz,
                  color=colors)
        plt.show()