Exemplo n.º 1
0
    def eval(cls, nu, z):
        if z.is_zero:
            if nu.is_zero:
                return S.One
            elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
                return S.Zero
            elif re(nu).is_negative and not (nu.is_integer is True):
                return S.ComplexInfinity
            elif nu.is_imaginary:
                return S.NaN
        if z is S.Infinity or (z is S.NegativeInfinity):
            return S.Zero

        if z.could_extract_minus_sign():
            return (z)**nu*(-z)**(-nu)*besselj(nu, -z)
        if nu.is_integer:
            if nu.could_extract_minus_sign():
                return S(-1)**(-nu)*besselj(-nu, z)
            newz = z.extract_multiplicatively(I)
            if newz:  # NOTE we don't want to change the function if z==0
                return I**(nu)*besseli(nu, newz)

        # branch handling:
        from sympy import unpolarify, exp
        if nu.is_integer:
            newz = unpolarify(z)
            if newz != z:
                return besselj(nu, newz)
        else:
            newz, n = z.extract_branch_factor()
            if n != 0:
                return exp(2*n*pi*nu*I)*besselj(nu, newz)
        nnu = unpolarify(nu)
        if nu != nnu:
            return besselj(nnu, z)
Exemplo n.º 2
0
    def eval(cls, nu, z):
        if z.is_zero:
            if nu.is_zero:
                return S.NegativeInfinity
            elif re(nu).is_zero is False:
                return S.ComplexInfinity
            elif re(nu).is_zero:
                return S.NaN
        if z is S.Infinity or z is S.NegativeInfinity:
            return S.Zero

        if nu.is_integer:
            if nu.could_extract_minus_sign():
                return S(-1) ** (-nu) * bessely(-nu, z)
Exemplo n.º 3
0
    def eval(cls, nu, z):
        if z.is_zero:
            if nu.is_zero:
                return S.Infinity
            elif re(nu).is_zero is False:
                return S.ComplexInfinity
            elif re(nu).is_zero:
                return S.NaN
        if z.is_imaginary:
            if im(z) is S.Infinity or im(z) is S.NegativeInfinity:
                return S.Zero

        if nu.is_integer:
            if nu.could_extract_minus_sign():
                return besselk(-nu, z)
Exemplo n.º 4
0
def test_solve_sqrt_3():
    R = Symbol("R")
    eq = sqrt(2) * R * sqrt(1 / (R + 1)) + (R + 1) * (sqrt(2) * sqrt(1 / (R + 1)) - 1)
    sol = solveset_complex(eq, R)

    assert sol == FiniteSet(
        *[
            S(5) / 3 + 4 * sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3,
            -sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
            + 40 * re(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            + sqrt(30) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
            + S(5) / 3
            + I
            * (
                -sqrt(30) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
                - sqrt(10) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
                + 40 * im(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            ),
        ]
    )

    # the number of real roots will depend on the value of m: for m=1 there are 4
    # and for m=-1 there are none.
    eq = -sqrt((m - q) ** 2 + (-m / (2 * q) + S(1) / 2) ** 2) + sqrt(
        (-m ** 2 / 2 - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
        + (m ** 2 / 2 - m - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
    )
    raises(NotImplementedError, lambda: solveset_real(eq, q))
Exemplo n.º 5
0
    def as_real_imag(self):
        """Returns a tuple of the real part of the input Matrix
           and it's imaginary part.

           >>> from sympy import Matrix, I
           >>> A = Matrix([[1+2*I, 3], [4+7*I, 5]])
           >>> A.as_real_imag()
           (Matrix([
           [1, 3],
           [4, 5]]), Matrix([
           [2, 0],
           [7, 0]]))
           >>> from sympy.abc import x, y, z, w
           >>> B = Matrix([[x, y + x * I], [z + w * I, z]])
           >>> B.as_real_imag()
           (Matrix([
           [        re(x), re(y) - im(x)],
           [re(z) - im(w),         re(z)]]), Matrix([
           [        im(x), re(x) + im(y)],
           [re(w) + im(z),         im(z)]]))

        """
        from sympy.functions.elementary.complexes import re, im
        real_mat = self._new(self.rows, self.cols, lambda i, j: re(self[i, j]))
        im_mat = self._new(self.rows, self.cols, lambda i, j: im(self[i, j]))

        return (real_mat, im_mat)
Exemplo n.º 6
0
 def _eval_rewrite_as_besseli(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = Pow(z, Rational(3, 2))
     if re(z).is_positive:
         return ot * sqrt(z) * (besseli(-ot, tt * a) - besseli(ot, tt * a))
     else:
         return ot * (Pow(a, ot) * besseli(-ot, tt * a) - z * Pow(a, -ot) * besseli(ot, tt * a))
Exemplo n.º 7
0
    def as_real_imag(self):
        real_matrices = [re(matrix) for matrix in self.blocks]
        real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)

        im_matrices = [im(matrix) for matrix in self.blocks]
        im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)

        return (real_matrices, im_matrices)
Exemplo n.º 8
0
 def _eval_rewrite_as_besseli(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = Pow(z, Rational(3, 2))
     if re(z).is_positive:
         return sqrt(z) / sqrt(3) * (besseli(-ot, tt * a) + besseli(ot, tt * a))
     else:
         b = Pow(a, ot)
         c = Pow(a, -ot)
         return sqrt(ot) * (b * besseli(-ot, tt * a) + z * c * besseli(ot, tt * a))
Exemplo n.º 9
0
 def _eval_rewrite_as_besseli(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = tt * Pow(z, Rational(3, 2))
     if re(z).is_positive:
         return z / 3 * (besseli(tt, a) - besseli(-tt, a))
     else:
         a = Pow(z, Rational(3, 2))
         b = Pow(a, tt)
         c = Pow(a, -tt)
         return ot * (z ** 2 * c * besseli(tt, tt * a) - b * besseli(-ot, tt * a))
Exemplo n.º 10
0
 def _eval_rewrite_as_besseli(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = tt * Pow(z, Rational(3, 2))
     if re(z).is_positive:
         return z / sqrt(3) * (besseli(-tt, a) + besseli(tt, a))
     else:
         a = Pow(z, Rational(3, 2))
         b = Pow(a, tt)
         c = Pow(a, -tt)
         return sqrt(ot) * (b * besseli(-tt, tt * a) + z ** 2 * c * besseli(tt, tt * a))
Exemplo n.º 11
0
    def as_real_imag(self):
        """Returns tuple containing (real , imaginary) part of sparse matrix"""
        from sympy.functions.elementary.complexes import re, im
        real_smat = self.copy()
        im_smat = self.copy()

        for key, value in self._smat.items():
            real_smat._smat[key] = re(value)
            im_smat._smat[key] = im(value)

        return (real_smat, im_smat)
Exemplo n.º 12
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])
     try:
         bad = (i <= -pi or i > pi)
     except TypeError:
         bad = True
     if bad:
         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
Exemplo n.º 13
0
def test_solve_sqrt_3():
    R = Symbol("R")
    eq = sqrt(2) * R * sqrt(1 / (R + 1)) + (R + 1) * (sqrt(2) * sqrt(1 / (R + 1)) - 1)
    sol = solveset_complex(eq, R)

    assert sol == FiniteSet(
        *[
            S(5) / 3 + 4 * sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3,
            -sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
            + 40 * re(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            + sqrt(30) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
            + S(5) / 3
            + I
            * (
                -sqrt(30) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
                - sqrt(10) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
                + 40 * im(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            ),
        ]
    )

    # the number of real roots will depend on the value of m: for m=1 there are 4
    # and for m=-1 there are none.
    eq = -sqrt((m - q) ** 2 + (-m / (2 * q) + S(1) / 2) ** 2) + sqrt(
        (-m ** 2 / 2 - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
        + (m ** 2 / 2 - m - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
    )
    unsolved_object = ConditionSet(
        q,
        Eq(
            (
                -2 * sqrt(4 * q ** 2 * (m - q) ** 2 + (-m + q) ** 2)
                + sqrt(
                    (-2 * m ** 2 - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) - 1) ** 2
                    + (2 * m ** 2 - 4 * m - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) - 1) ** 2
                )
                * Abs(q)
            )
            / Abs(q),
            0,
        ),
        S.Reals,
    )
    assert solveset_real(eq, q) == unsolved_object
Exemplo n.º 14
0
    def eval(cls, n, a, x):
        # For negative n the polynomials vanish
        # See http://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/
        if n.is_negative:
            return S.Zero

        # Some special values for fixed a
        if a == S.Half:
            return legendre(n, x)
        elif a == S.One:
            return chebyshevu(n, x)
        elif a == S.NegativeOne:
            return S.Zero

        if not n.is_Number:
            # Handle this before the general sign extraction rule
            if x == S.NegativeOne:
                if (re(a) > S.Half) == True:
                    return S.ComplexInfinity
                else:
                    # No sec function available yet
                    #return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) /
                    #            (gamma(2*a) * gamma(n+1)))
                    return None

            # Symbolic result C^a_n(x)
            # C^a_n(-x)  --->  (-1)**n * C^a_n(x)
            if x.could_extract_minus_sign():
                return S.NegativeOne**n * gegenbauer(n, a, -x)
            # We can evaluate for some special values of x
            if x == S.Zero:
                return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) /
                        (gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) )
            if x == S.One:
                return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1))
            elif x == S.Infinity:
                if n.is_positive:
                    return RisingFactorial(a, n) * S.Infinity
        else:
            # n is a given fixed integer, evaluate into polynomial
            return gegenbauer_poly(n, a, x)
Exemplo n.º 15
0
def test_fresnel():
    assert fresnels(0) is S.Zero
    assert fresnels(oo) is 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) is S.Zero
    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.core.random 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
Exemplo n.º 16
0
def test_issue_5084():
    x = Symbol('x')
    assert ((x + x * I) / (1 + I)).as_real_imag() == (re(
        (x + I * x) / (1 + I)), im((x + I * x) / (1 + I)))
 def _check(self, value):
     from sympy.functions import re, im
     super(ComplexType, self)._check(re(value))
     super(ComplexType, self)._check(im(value))
Exemplo n.º 18
0
def test_periodicity():
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z', real=True)

    assert periodicity(sin(2*x), x) == pi
    assert periodicity((-2)*tan(4*x), x) == pi/4
    assert periodicity(sin(x)**2, x) == 2*pi
    assert periodicity(3**tan(3*x), x) == pi/3
    assert periodicity(tan(x)*cos(x), x) == 2*pi
    assert periodicity(sin(x)**(tan(x)), x) == 2*pi
    assert periodicity(tan(x)*sec(x), x) == 2*pi
    assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
    assert periodicity(tan(x) + cot(x), x) == pi
    assert periodicity(sin(x) - cos(2*x), x) == 2*pi
    assert periodicity(sin(x) - 1, x) == 2*pi
    assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
    assert periodicity(exp(sin(x)), x) == 2*pi
    assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
    assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
    assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
    assert periodicity(tan(sin(2*x)), x) == pi
    assert periodicity(2*tan(x)**2, x) == pi
    assert periodicity(sin(x%4), x) == 4
    assert periodicity(sin(x)%4, x) == 2*pi
    assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
    assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
    assert periodicity((x**2+1) % x, x) is None
    assert periodicity(sin(re(x)), x) == 2*pi
    assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
    assert periodicity(tan(x), y) is S.Zero
    assert periodicity(sin(x) + I*cos(x), x) == 2*pi
    assert periodicity(x - sin(2*y), y) == pi

    assert periodicity(exp(x), x) is None
    assert periodicity(exp(I*x), x) == 2*pi
    assert periodicity(exp(I*z), z) == 2*pi
    assert periodicity(exp(z), z) is None
    assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
    assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
    assert periodicity(exp(sin(z)), z) == 2*pi
    assert periodicity(exp(2*I*z), z) == pi
    assert periodicity(exp(z + I*sin(z)), z) is None
    assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
    assert periodicity(log(x), x) is None
    assert periodicity(exp(x)**sin(x), x) is None
    assert periodicity(sin(x)**y, y) is None

    assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
    assert all(periodicity(Abs(f(x)), x) == pi for f in (
        cos, sin, sec, csc, tan, cot))
    assert periodicity(Abs(sin(tan(x))), x) == pi
    assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
    assert periodicity(sin(x) > S.Half, x) == 2*pi

    assert periodicity(x > 2, x) is None
    assert periodicity(x**3 - x**2 + 1, x) is None
    assert periodicity(Abs(x), x) is None
    assert periodicity(Abs(x**2 - 1), x) is None

    assert periodicity((x**2 + 4)%2, x) is None
    assert periodicity((E**x)%3, x) is None

    assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
    # returning `None` for any Piecewise
    p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
    assert periodicity(p, x) is None

    m = MatrixSymbol('m', 3, 3)
    raises(NotImplementedError, lambda: periodicity(sin(m), m))
    raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m))
    raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0]))
    raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0]))
Exemplo n.º 19
0
 def _eval_Abs(self):   # Abs is never a polar number
     return exp(re(self.args[0]))
Exemplo n.º 20
0
 def as_real_imag(self):
     return (re(Matrix(self)), im(Matrix(self)))
 def _cast_nocheck(self, value):
     from sympy.functions import re, im
     return (super(ComplexType, self)._cast_nocheck(re(value)) +
             super(ComplexType, self)._cast_nocheck(im(value)) * 1j)
Exemplo n.º 22
0
    def _generic_mul(q1, q2):
        """Generic multiplication.

        Parameters
        ==========

        q1 : Quaternion or symbol
        q2 : Quaternion or symbol

        It's important to note that if neither q1 nor q2 is a Quaternion,
        this function simply returns q1 * q2.

        Returns
        =======

        Quaternion
            The resultant quaternion after multiplying q1 and q2

        Examples
        ========

        >>> from sympy import Quaternion
        >>> from sympy import Symbol
        >>> q1 = Quaternion(1, 2, 3, 4)
        >>> q2 = Quaternion(5, 6, 7, 8)
        >>> Quaternion._generic_mul(q1, q2)
        (-60) + 12*i + 30*j + 24*k
        >>> Quaternion._generic_mul(q1, 2)
        2 + 4*i + 6*j + 8*k
        >>> x = Symbol('x', real = True)
        >>> Quaternion._generic_mul(q1, x)
        x + 2*x*i + 3*x*j + 4*x*k

        Quaternions over complex fields :

        >>> from sympy import Quaternion
        >>> from sympy import I
        >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
        >>> Quaternion._generic_mul(q3, 2 + 3*I)
        (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k

        """
        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 and q1.is_complex:
                return Quaternion(re(q1), im(q1), 0, 0) * q2
            elif q1.is_commutative:
                return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)
            else:
                raise ValueError(
                    "Only commutative expressions can be multiplied with a Quaternion."
                )

        # If q2 is a number or a SymPy expression instead of a quaternion
        if not isinstance(q2, Quaternion):
            if q1.real_field and q2.is_complex:
                return q1 * Quaternion(re(q2), im(q2), 0, 0)
            elif q2.is_commutative:
                return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)
            else:
                raise ValueError(
                    "Only commutative expressions can be multiplied with a Quaternion."
                )

        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)
Exemplo n.º 23
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
    assert cosh(5 * I * S.Pi / 2, evaluate=False).is_zero is True
    assert cosh(x).is_zero is False
Exemplo n.º 24
0
 def _eval_Abs(self):   # Abs is never a polar number
     from sympy.functions.elementary.complexes import re
     return exp(re(self.args[0]))
Exemplo n.º 25
0
 def as_real_imag(self, deep=True, **hints):
     if hints.get('ignore') == self:
         return None
     else:
         from sympy.functions.elementary.complexes import im, re
         return (re(self), im(self))
Exemplo n.º 26
0
 def _eval_rewrite_as_besselj(self, z, **kwargs):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a))
Exemplo n.º 27
0
    def eval(cls, a, z):
        from sympy import unpolarify, I, expint

        if z.is_Number:
            if z is S.NaN:
                return S.NaN
            elif z is S.Infinity:
                return S.Zero
            elif z.is_zero:
                if re(a).is_positive:
                    return gamma(a)

        # We extract branching information here. C/f lowergamma.
        nx, n = z.extract_branch_factor()
        if a.is_integer and a.is_positive:
            nx = unpolarify(z)
            if z != nx:
                return uppergamma(a, nx)
        elif a.is_integer and a.is_nonpositive:
            if n != 0:
                return -2 * pi * I * n * (-1) ** (-a) / factorial(-a) + uppergamma(
                    a, nx
                )
        elif n != 0:
            return gamma(a) * (1 - exp(2 * pi * I * n * a)) + exp(
                2 * pi * I * n * a
            ) * uppergamma(a, nx)

        # Special values.
        if a.is_Number:
            if a is S.Zero and z.is_positive:
                return -Ei(-z)
            elif a is S.One:
                return exp(-z)
            elif a is S.Half:
                return sqrt(pi) * erfc(sqrt(z))
            elif a.is_Integer or (2 * a).is_Integer:
                b = a - 1
                if b.is_positive:
                    if a.is_integer:
                        return (
                            exp(-z)
                            * factorial(b)
                            * Add(*[z ** k / factorial(k) for k in range(a)])
                        )
                    else:
                        return gamma(a) * erfc(sqrt(z)) + (-1) ** (a - S(3) / 2) * exp(
                            -z
                        ) * sqrt(z) * Add(
                            *[
                                gamma(-S.Half - k) * (-z) ** k / gamma(1 - a)
                                for k in range(a - S.Half)
                            ]
                        )
                elif b.is_Integer:
                    return expint(-b, z) * unpolarify(z) ** (b + 1)

                if not a.is_Integer:
                    return (-1) ** (S.Half - a) * pi * erfc(sqrt(z)) / gamma(
                        1 - a
                    ) - z ** a * exp(-z) * Add(
                        *[
                            z ** k * gamma(a) / gamma(a + k + 1)
                            for k in range(S.Half - a)
                        ]
                    )

        if a.is_zero and z.is_positive:
            return -Ei(-z)

        if z.is_zero and re(a).is_positive:
            return gamma(a)
Exemplo n.º 28
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))
Exemplo n.º 29
0
 def _cast_nocheck(self, value):
     from sympy.functions import re, im
     return (
         super(ComplexType, self)._cast_nocheck(re(value)) +
         super(ComplexType, self)._cast_nocheck(im(value))*1j
     )
Exemplo n.º 30
0
 def _eval_rewrite_as_besselj(self, z, **kwargs):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return sqrt(-z / 3) * (besselj(-ot, tt * a) - besselj(ot, tt * a))
Exemplo n.º 31
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.
    """
    from sympy.functions.elementary.complexes import re, im
    # 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.core.add import Add
        nint = int(to_int(nexpr, rnd))
        n, c, p, b = nexpr
        is_int = (p == 0)
        if not is_int:
            # if there are subs and they all contain integer re/im parts
            # then we can (hopefully) safely substitute them into the
            # expression
            s = options.get('subs', False)
            if s:
                doit = True
                from sympy.core.compatibility import as_int
                for v in s.values():
                    try:
                        as_int(v)
                    except ValueError:
                        try:
                            [as_int(i) for i in v.as_real_imag()]
                            continue
                        except (ValueError, AttributeError):
                            doit = False
                            break
                if doit:
                    expr = expr.subs(s)

            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(re(expr, evaluate=False), ire)
    if iim:
        im_, im_acc = calc_part(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
Exemplo n.º 32
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
    p = Symbol('p', positive=True)
    assert sinh(p).is_zero is False
    assert sinh(0, evaluate=False).is_zero is True
    assert sinh(2 * pi * I, evaluate=False).is_zero is True
Exemplo n.º 33
0
def periodicity(f, symbol, check=False):
    """
    Tests the given function for periodicity in the given symbol.

    Parameters
    ==========

    f : :py:class:`~.Expr`.
        The concerned function.
    symbol : :py:class:`~.Symbol`
        The variable for which the period is to be determined.
    check : bool, optional
        The flag to verify whether the value being returned is a period or not.

    Returns
    =======

    period
        The period of the function is returned.
        ``None`` is returned when the function is aperiodic or has a complex period.
        The value of $0$ is returned as the period of a constant function.

    Raises
    ======

    NotImplementedError
        The value of the period computed cannot be verified.


    Notes
    =====

    Currently, we do not support functions with a complex period.
    The period of functions having complex periodic values such
    as ``exp``, ``sinh`` is evaluated to ``None``.

    The value returned might not be the "fundamental" period of the given
    function i.e. it may not be the smallest periodic value of the function.

    The verification of the period through the ``check`` flag is not reliable
    due to internal simplification of the given expression. Hence, it is set
    to ``False`` by default.

    Examples
    ========
    >>> from sympy import periodicity, Symbol, sin, cos, tan, exp
    >>> x = Symbol('x')
    >>> f = sin(x) + sin(2*x) + sin(3*x)
    >>> periodicity(f, x)
    2*pi
    >>> periodicity(sin(x)*cos(x), x)
    pi
    >>> periodicity(exp(tan(2*x) - 1), x)
    pi/2
    >>> periodicity(sin(4*x)**cos(2*x), x)
    pi
    >>> periodicity(exp(x), x)
    """
    if symbol.kind is not NumberKind:
        raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
    temp = Dummy('x', real=True)
    f = f.subs(symbol, temp)
    symbol = temp

    def _check(orig_f, period):
        '''Return the checked period or raise an error.'''
        new_f = orig_f.subs(symbol, symbol + period)
        if new_f.equals(orig_f):
            return period
        else:
            raise NotImplementedError(
                filldedent('''
                The period of the given function cannot be verified.
                When `%s` was replaced with `%s + %s` in `%s`, the result
                was `%s` which was not recognized as being the same as
                the original function.
                So either the period was wrong or the two forms were
                not recognized as being equal.
                Set check=False to obtain the value.''' %
                           (symbol, symbol, period, orig_f, new_f)))

    orig_f = f
    period = None

    if isinstance(f, Relational):
        f = f.lhs - f.rhs

    f = f.simplify()

    if symbol not in f.free_symbols:
        return S.Zero

    if isinstance(f, TrigonometricFunction):
        try:
            period = f.period(symbol)
        except NotImplementedError:
            pass

    if isinstance(f, Abs):
        arg = f.args[0]
        if isinstance(arg, (sec, csc, cos)):
            # all but tan and cot might have a
            # a period that is half as large
            # so recast as sin
            arg = sin(arg.args[0])
        period = periodicity(arg, symbol)
        if period is not None and isinstance(arg, sin):
            # the argument of Abs was a trigonometric other than
            # cot or tan; test to see if the half-period
            # is valid. Abs(arg) has behaviour equivalent to
            # orig_f, so use that for test:
            orig_f = Abs(arg)
            try:
                return _check(orig_f, period / 2)
            except NotImplementedError as err:
                if check:
                    raise NotImplementedError(err)
            # else let new orig_f and period be
            # checked below

    if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
        f = Pow(S.Exp1, expand_mul(f.exp))
        if im(f) != 0:
            period_real = periodicity(re(f), symbol)
            period_imag = periodicity(im(f), symbol)
            if period_real is not None and period_imag is not None:
                period = lcim([period_real, period_imag])

    if f.is_Pow and f.base != S.Exp1:
        base, expo = f.args
        base_has_sym = base.has(symbol)
        expo_has_sym = expo.has(symbol)

        if base_has_sym and not expo_has_sym:
            period = periodicity(base, symbol)

        elif expo_has_sym and not base_has_sym:
            period = periodicity(expo, symbol)

        else:
            period = _periodicity(f.args, symbol)

    elif f.is_Mul:
        coeff, g = f.as_independent(symbol, as_Add=False)
        if isinstance(g, TrigonometricFunction) or coeff is not S.One:
            period = periodicity(g, symbol)

        else:
            period = _periodicity(g.args, symbol)

    elif f.is_Add:
        k, g = f.as_independent(symbol)
        if k is not S.Zero:
            return periodicity(g, symbol)

        period = _periodicity(g.args, symbol)

    elif isinstance(f, Mod):
        a, n = f.args

        if a == symbol:
            period = n
        elif isinstance(a, TrigonometricFunction):
            period = periodicity(a, symbol)
        #check if 'f' is linear in 'symbol'
        elif (a.is_polynomial(symbol) and degree(a, symbol) == 1
              and symbol not in n.free_symbols):
            period = Abs(n / a.diff(symbol))

    elif isinstance(f, Piecewise):
        pass  # not handling Piecewise yet as the return type is not favorable

    elif period is None:
        from sympy.solvers.decompogen import compogen, decompogen
        g_s = decompogen(f, symbol)
        num_of_gs = len(g_s)
        if num_of_gs > 1:
            for index, g in enumerate(reversed(g_s)):
                start_index = num_of_gs - 1 - index
                g = compogen(g_s[start_index:], symbol)
                if g not in (orig_f, f):  # Fix for issue 12620
                    period = periodicity(g, symbol)
                    if period is not None:
                        break

    if period is not None:
        if check:
            return _check(orig_f, period)
        return period

    return None
Exemplo n.º 34
0
 def _eval_rewrite_as_besselj(self, z):
     tt = Rational(2, 3)
     a = tt * Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return -z / sqrt(3) * (besselj(-tt, a) + besselj(tt, a))
Exemplo n.º 35
0
 def _eval_rewrite_as_besselj(self, z, **kwargs):
     tt = Rational(2, 3)
     a = tt * Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return -z / sqrt(3) * (besselj(-tt, a) + besselj(tt, a))
Exemplo n.º 36
0
                etaa, etad = frac_in(dcoeff, DE.t)
                A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
                if A is not None:
                    Q, m, z = A
                    if Q == 1:
                        n = min(n, m)

        elif case == 'tan':
            dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
            with DecrementLevel(DE):  # We are guaranteed to not have problems,
                # because case != 'base'.
                alphaa, alphad = frac_in(
                    im(-ba.eval(sqrt(-1)) / bd.eval(sqrt(-1)) /
                       a.eval(sqrt(-1))), DE.t)
                betaa, betad = frac_in(
                    re(-ba.eval(sqrt(-1)) / bd.eval(sqrt(-1)) /
                       a.eval(sqrt(-1))), DE.t)
                etaa, etad = frac_in(dcoeff, DE.t)

                if recognize_log_derivative(Poly(2, DE.t) * betaa, betad, DE):
                    A = parametric_log_deriv(
                        alphaa * Poly(sqrt(-1), DE.t) * betad + alphad * betaa,
                        alphad * betad, etaa, etad, DE)
                    if A is not None:
                        Q, m, z = A
                        if Q == 1:
                            n = min(n, m)
    N = max(0, -nb, n - nc)
    pN = p**N
    pn = p**-n

    A = a * pN
Exemplo n.º 37
0
def test_polygamma():
    assert polygamma(n, nan) is nan

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

    assert polygamma(0, -9) is zoo

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

    assert polygamma(0, 0) is 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

    assert polygamma(1, S.Half) == pi**2 / 2
    assert polygamma(2, S.Half) == -14*zeta(3)
    assert polygamma(11, S.Half) == 176896*pi**12

    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:
    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 True
    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 True
    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
Exemplo n.º 38
0
 def _eval_rewrite_as_besselj(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return ot * sqrt(-z) * (besselj(-ot, tt * a) + besselj(ot, tt * a))
Exemplo n.º 39
0
def test_print_re_im():
    x = Symbol('x')
    assert mpp.doprint(re(x)) == '<mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow>'
    assert mpp.doprint(im(x)) == '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>'
    assert mpp.doprint(re(x + 1)) == '<mrow><mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow><mo>+</mo><mn>1</mn></mrow>'
    assert mpp.doprint(im(x + 1)) == '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>'
Exemplo n.º 40
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
Exemplo n.º 41
0
def test_issue_21756():
    term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5))
    assert term.limit(z, 0) == 5
    assert re(term).limit(z, 0) == 5
Exemplo n.º 42
0
def test_erf():
    assert erf(nan) is nan

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

    assert erf(0) is S.Zero

    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, evaluate=False).is_real
    assert erf(0, evaluate=False).is_zero

    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
Exemplo n.º 43
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.
    """
    from sympy.functions.elementary.complexes import re, im
    # 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.core.add import Add
        nint = int(to_int(nexpr, rnd))
        n, c, p, b = nexpr
        is_int = (p == 0)
        if not is_int:
            # if there are subs and they all contain integer re/im parts
            # then we can (hopefully) safely substitute them into the
            # expression
            s = options.get('subs', False)
            if s:
                doit = True
                from sympy.core.compatibility import as_int
                for v in s.values():
                    try:
                        as_int(v)
                    except ValueError:
                        try:
                            [as_int(i) for i in v.as_real_imag()]
                            continue
                        except (ValueError, AttributeError):
                            doit = False
                            break
                if doit:
                    expr = expr.subs(s)

            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(re(expr, evaluate=False), ire)
    if iim:
        im_, im_acc = calc_part(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
Exemplo n.º 44
0
 def _eval_Abs(self):   # Abs is never a polar number
     from sympy.functions.elementary.complexes import re
     return exp(re(self.args[0]))
Exemplo n.º 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
Exemplo n.º 46
0
 def _check(self, value):
     from sympy.functions import re, im
     super(ComplexType, self)._check(re(value))
     super(ComplexType, self)._check(im(value))
Exemplo n.º 47
0
 def _eval_rewrite_as_besselj(self, z):
     ot = Rational(1, 3)
     tt = Rational(2, 3)
     a = C.Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return ot * sqrt(-z) * (besselj(-ot, tt * a) + besselj(ot, tt * a))
Exemplo n.º 48
0
 def _eval_rewrite_as_besselj(self, z, **kwargs):
     tt = Rational(2, 3)
     a = Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return z / 3 * (besselj(-tt, tt * a) - besselj(tt, tt * a))
Exemplo n.º 49
0
 def _eval_rewrite_as_besselj(self, z):
     tt = Rational(2, 3)
     a = Pow(-z, Rational(3, 2))
     if re(z).is_negative:
         return z / 3 * (besselj(-tt, tt * a) - besselj(tt, tt * a))
Exemplo n.º 50
0
 def _handle_UnevaluatedExpr(self, expr):
     return expr.replace(
         re, lambda arg: arg if isinstance(arg, UnevaluatedExpr) and arg.
         args[0].is_real else re(arg))
Exemplo n.º 51
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
Exemplo n.º 52
0
 def as_real_imag(self):
     return (re(Matrix(self)), im(Matrix(self)))
Exemplo n.º 53
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