Example #1
0
    def integrate(self, x=None, **kwargs):
        """Integrate Formal Power Series.

        Examples
        ========

        >>> from sympy import fps, sin, integrate
        >>> from sympy.abc import x
        >>> f = fps(sin(x))
        >>> f.integrate(x).truncate()
        -1 + x**2/2 - x**4/24 + O(x**6)
        >>> integrate(f, (x, 0, 1))
        -cos(1) + 1
        """
        from sympy.integrals import integrate

        if x is None:
            x = self.x
        elif iterable(x):
            return integrate(self.function, x)

        f = integrate(self.function, x)
        ind = integrate(self.ind, x)
        ind += (f - ind).limit(x, 0)  # constant of integration

        pow_xk = self._get_pow_x(self.xk.formula)
        ak = self.ak
        k = ak.variables[0]
        if ak.formula.has(x):
            form = []
            for e, c in ak.formula.args:
                temp = S.Zero
                for t in Add.make_args(e):
                    pow_x = self._get_pow_x(t)
                    temp += t / (pow_xk + pow_x + 1)
                form.append((temp, c))
            form = Piecewise(*form)
            ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
        else:
            ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
                          (k, ak.start + 1, ak.stop))

        return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
Example #2
0
    def _eval_derivative(self, x):
        f = self.function.diff(x)
        ind = self.ind.diff(x)

        pow_xk = self._get_pow_x(self.xk.formula)
        ak = self.ak
        k = ak.variables[0]
        if ak.formula.has(x):
            form = []
            for e, c in ak.formula.args:
                temp = S.Zero
                for t in Add.make_args(e):
                    pow_x = self._get_pow_x(t)
                    temp += t * (pow_xk + pow_x)
                form.append((temp, c))
            form = Piecewise(*form)
            ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
        else:
            ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
                          (k, ak.start - 1, ak.stop))

        return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
Example #3
0
def rsolve_hypergeometric(f, x, P, Q, k, m):
    """Solves RE of hypergeometric type.

    Attempts to solve RE of the form

    Q(k)*a(k + m) - P(k)*a(k)

    Transformations that preserve Hypergeometric type:

        a. x**n*f(x): b(k + m) = R(k - n)*b(k)
        b. f(A*x): b(k + m) = A**m*R(k)*b(k)
        c. f(x**n): b(k + n*m) = R(k/n)*b(k)
        d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k)
        e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k)

    Some of these transformations have been used to solve the RE.

    Returns
    =======

    formula : Expr
    ind : Expr
        Independent terms.
    order : int

    Examples
    ========

    >>> from sympy import exp, ln, S
    >>> from sympy.series.formal import rsolve_hypergeometric as rh
    >>> from sympy.abc import x, k

    >>> rh(exp(x), x, -S.One, (k + 1), k, 1)
    (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)

    >>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1)
    (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
     Eq(Mod(k, 1), 0)), (0, True)), x, 2)

    References
    ==========

    .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
    .. [2] Power Series in Computer Algebra - Wolfram Koepf
    """
    result = _rsolve_hypergeometric(f, x, P, Q, k, m)

    if result is None:
        return None

    sol_list, ind, mp = result

    sol_dict = defaultdict(lambda: S.Zero)
    for res, cond in sol_list:
        j, mk = cond.as_coeff_Add()
        c = mk.coeff(k)

        if j.is_integer is False:
            res *= x**frac(j)
            j = floor(j)

        res = res.subs(k, (k - j) / c)
        cond = Eq(k % c, j % c)
        sol_dict[cond] += res  # Group together formula for same conditions

    sol = []
    for cond, res in sol_dict.items():
        sol.append((res, cond))
    sol.append((S.Zero, True))
    sol = Piecewise(*sol)

    if mp is -oo:
        s = S.Zero
    elif mp.is_integer is False:
        s = ceiling(mp)
    else:
        s = mp + 1

    #  save all the terms of
    #  form 1/x**k in ind
    if s < 0:
        ind += sum(sequence(sol * x**k, (k, s, -1)))
        s = S.Zero

    return (sol, ind, s)
Example #4
0
 def _eval_rewrite_as_Piecewise(self, arg):
     if arg.is_real:
         return Piecewise((arg, arg >= 0), (-arg, True))
Example #5
0
 def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
     if arg.is_extended_real:
         return Piecewise((arg, arg >= 0), (-arg, True))
Example #6
0
def test_Piecewise():
    assert refine(Piecewise((1, x < 0), (3, True)), Q.is_true(x < 0)) == 1
    assert refine(Piecewise((1, x < 0), (3, True)), ~Q.is_true(x < 0)) == 3
    assert refine(Piecewise((1, x < 0), (3, True)),
                  Q.is_true(y < 0)) == Piecewise((1, x < 0), (3, True))
    assert refine(Piecewise((1, x > 0), (3, True)), Q.is_true(x > 0)) == 1
    assert refine(Piecewise((1, x > 0), (3, True)), ~Q.is_true(x > 0)) == 3
    assert refine(Piecewise((1, x > 0), (3, True)),
                  Q.is_true(y > 0)) == Piecewise((1, x > 0), (3, True))
    assert refine(Piecewise((1, x <= 0), (3, True)), Q.is_true(x <= 0)) == 1
    assert refine(Piecewise((1, x <= 0), (3, True)), ~Q.is_true(x <= 0)) == 3
    assert refine(Piecewise((1, x <= 0), (3, True)),
                  Q.is_true(y <= 0)) == Piecewise((1, x <= 0), (3, True))
    assert refine(Piecewise((1, x >= 0), (3, True)), Q.is_true(x >= 0)) == 1
    assert refine(Piecewise((1, x >= 0), (3, True)), ~Q.is_true(x >= 0)) == 3
    assert refine(Piecewise((1, x >= 0), (3, True)),
                  Q.is_true(y >= 0)) == Piecewise((1, x >= 0), (3, True))
    assert refine(Piecewise((1, Eq(x, 0)), (3, True)), Q.is_true(Eq(x,
                                                                    0))) == 1
    assert refine(Piecewise((1, Eq(x, 0)), (3, True)), Q.is_true(Eq(0,
                                                                    x))) == 1
    assert refine(Piecewise((1, Eq(x, 0)), (3, True)),
                  ~Q.is_true(Eq(x, 0))) == 3
    assert refine(Piecewise((1, Eq(x, 0)), (3, True)),
                  ~Q.is_true(Eq(0, x))) == 3
    assert refine(Piecewise((1, Eq(x, 0)), (3, True)),
                  Q.is_true(Eq(y, 0))) == Piecewise((1, Eq(x, 0)), (3, True))
    assert refine(Piecewise((1, Ne(x, 0)), (3, True)), Q.is_true(Ne(x,
                                                                    0))) == 1
    assert refine(Piecewise((1, Ne(x, 0)), (3, True)),
                  ~Q.is_true(Ne(x, 0))) == 3
    assert refine(Piecewise((1, Ne(x, 0)), (3, True)),
                  Q.is_true(Ne(y, 0))) == Piecewise((1, Ne(x, 0)), (3, True))
Example #7
0
def test_integrate_Piecewise_rational_over_reals():
    f = Piecewise((0, t - 478.515625 * pi < 0),
                  (13.2075145209219 * pi /
                   (0.000871222 * t + 0.995)**2, t - 478.515625 * pi >= 0))

    assert abs((integrate(f, (t, 0, oo)) - 15235.9375 * pi).evalf()) <= 1e-7
Example #8
0
def test_issue_12251():
    assert manualintegrate(x**y, x) == Piecewise(
        (x**(y + 1) / (y + 1), Ne(y, -1)), (log(x), True))
Example #9
0
 def pmf(self, x):
     if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol):
         return Piecewise((self.p, x == self.succ),
                          (1 - self.p, x == self.fail), (S.Zero, True))
     return Piecewise((self.p, Eq(x, self.succ)),
                      (1 - self.p, Eq(x, self.fail)), (S.Zero, True))
Example #10
0
def eval_sum_symbolic(f, limits):
    (i, a, b) = limits
    if not f.has(i):
        return f * (b - a + 1)

    # Linearity
    if f.is_Mul:
        L, R = f.as_two_terms()

        if not L.has(i):
            sR = eval_sum_symbolic(R, (i, a, b))
            if sR:
                return L * sR

        if not R.has(i):
            sL = eval_sum_symbolic(L, (i, a, b))
            if sL:
                return R * sL

        try:
            f = apart(f, i)  # see if it becomes an Add
        except PolynomialError:
            pass

    if f.is_Add:
        L, R = f.as_two_terms()
        lrsum = telescopic(L, R, (i, a, b))

        if lrsum:
            return lrsum

        lsum = eval_sum_symbolic(L, (i, a, b))
        rsum = eval_sum_symbolic(R, (i, a, b))

        if None not in (lsum, rsum):
            return lsum + rsum

    # Polynomial terms with Faulhaber's formula
    n = Wild('n')
    result = f.match(i**n)

    if result is not None:
        n = result[n]

        if n.is_Integer:
            if n >= 0:
                if (b is S.Infinity and not a is S.NegativeInfinity) or \
                   (a is S.NegativeInfinity and not b is S.Infinity):
                    return S.Infinity
                return ((C.bernoulli(n + 1, b + 1) - C.bernoulli(n + 1, a)) /
                        (n + 1)).expand()
            elif a.is_Integer and a >= 1:
                if n == -1:
                    return C.harmonic(b) - C.harmonic(a - 1)
                else:
                    return C.harmonic(b, abs(n)) - C.harmonic(a - 1, abs(n))

    if not (a.has(S.Infinity, S.NegativeInfinity)
            or b.has(S.Infinity, S.NegativeInfinity)):
        # Geometric terms
        c1 = C.Wild('c1', exclude=[i])
        c2 = C.Wild('c2', exclude=[i])
        c3 = C.Wild('c3', exclude=[i])

        e = f.match(c1**(c2 * i + c3))

        if e is not None:
            p = (c1**c3).subs(e)
            q = (c1**c2).subs(e)

            r = p * (q**a - q**(b + 1)) / (1 - q)
            l = p * (b - a + 1)

            return Piecewise((l, Eq(q, S.One)), (r, True))

        r = gosper_sum(f, (i, a, b))

        if not r in (None, S.NaN):
            return r

    return eval_sum_hyper(f, (i, a, b))
Example #11
0
def test_rewrite():
    x, y = Symbol('x', real=True), Symbol('y')
    assert Heaviside(x).rewrite(Piecewise) == (Piecewise(
        (0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0)))
    assert Heaviside(y).rewrite(Piecewise) == (Piecewise(
        (0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0)))
    assert Heaviside(x, y).rewrite(Piecewise) == (Piecewise(
        (0, x < 0), (y, Eq(x, 0)), (1, x > 0)))
    assert Heaviside(x, 0).rewrite(Piecewise) == (Piecewise((0, x <= 0),
                                                            (1, x > 0)))
    assert Heaviside(x, 1).rewrite(Piecewise) == (Piecewise((0, x < 0),
                                                            (1, x >= 0)))
    assert Heaviside(x, nan).rewrite(Piecewise) == (Piecewise(
        (0, x < 0), (nan, Eq(x, 0)), (1, x > 0)))

    assert Heaviside(x).rewrite(sign) == \
        Heaviside(x, H0=Heaviside(0)).rewrite(sign) == \
        Piecewise(
            (sign(x)/2 + S(1)/2, Eq(Heaviside(0), S(1)/2)),
            (Piecewise(
                (sign(x)/2 + S(1)/2, Ne(x, 0)), (Heaviside(0), True)), True)
        )

    assert Heaviside(y).rewrite(sign) == Heaviside(y)
    assert Heaviside(x, S.Half).rewrite(sign) == (sign(x) + 1) / 2
    assert Heaviside(x, y).rewrite(sign) == \
        Piecewise(
            (sign(x)/2 + S(1)/2, Eq(y, S(1)/2)),
            (Piecewise(
                (sign(x)/2 + S(1)/2, Ne(x, 0)), (y, True)), True)
        )

    assert DiracDelta(y).rewrite(Piecewise) == Piecewise(
        (DiracDelta(0), Eq(y, 0)), (0, True))
    assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1)
    assert DiracDelta(x - 5).rewrite(Piecewise) == (Piecewise(
        (DiracDelta(0), Eq(x - 5, 0)), (0, True)))

    assert (x * DiracDelta(x - 10)).rewrite(
        SingularityFunction) == x * SingularityFunction(x, 10, -1)
    assert 5 * x * y * DiracDelta(
        y, 1).rewrite(SingularityFunction) == 5 * x * y * SingularityFunction(
            y, 0, -2)
    assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(
        0, 0, -1)
    assert DiracDelta(0,
                      1).rewrite(SingularityFunction) == SingularityFunction(
                          0, 0, -2)

    assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(
        x, 0, 0)
    assert 5 * x * y * Heaviside(y + 1).rewrite(
        SingularityFunction) == 5 * x * y * SingularityFunction(y, -1, 0)
    assert ((x - 3)**3 * Heaviside(x - 3)).rewrite(
        SingularityFunction) == (x - 3)**3 * SingularityFunction(x, 3, 0)
    assert Heaviside(0).rewrite(SingularityFunction) == S.Half
Example #12
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]))
Example #13
0
def test_BernoulliProcess():

    B = BernoulliProcess("B", p=0.6, success=1, failure=0)
    assert B.state_space == FiniteSet(0, 1)
    assert B.index_set == S.Naturals0
    assert B.success == 1
    assert B.failure == 0

    X = BernoulliProcess("X", p=Rational(1, 3), success='H', failure='T')
    assert X.state_space == FiniteSet('H', 'T')
    H, T = symbols("H,T")
    assert E(X[1] + X[2] * X[3]
             ) == H**2 / 9 + 4 * H * T / 9 + H / 3 + 4 * T**2 / 9 + 2 * T / 3

    t, x = symbols('t, x', positive=True, integer=True)
    assert isinstance(B[t], RandomIndexedSymbol)

    raises(ValueError,
           lambda: BernoulliProcess("X", p=1.1, success=1, failure=0))
    raises(NotImplementedError, lambda: B(t))

    raises(IndexError, lambda: B[-3])
    assert B.joint_distribution(B[3], B[9]) == JointDistributionHandmade(
        Lambda(
            (B[3], B[9]),
            Piecewise((0.6, Eq(B[3], 1)), (0.4, Eq(B[3], 0)),
                      (0, True)) * Piecewise((0.6, Eq(B[9], 1)),
                                             (0.4, Eq(B[9], 0)), (0, True))))

    assert B.joint_distribution(2, B[4]) == JointDistributionHandmade(
        Lambda(
            (B[2], B[4]),
            Piecewise((0.6, Eq(B[2], 1)), (0.4, Eq(B[2], 0)),
                      (0, True)) * Piecewise((0.6, Eq(B[4], 1)),
                                             (0.4, Eq(B[4], 0)), (0, True))))

    # Test for the sum distribution of Bernoulli Process RVs
    Y = B[1] + B[2] + B[3]
    assert P(Eq(Y, 0)).round(2) == Float(0.06, 1)
    assert P(Eq(Y, 2)).round(2) == Float(0.43, 2)
    assert P(Eq(Y, 4)).round(2) == 0
    assert P(Gt(Y, 1)).round(2) == Float(0.65, 2)
    # Test for independency of each Random Indexed variable
    assert P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0)
             & Eq(B[4], 1)).round(2) == Float(0.06, 1)

    assert E(2 * B[1] + B[2]).round(2) == Float(1.80, 3)
    assert E(2 * B[1] + B[2] + 5).round(2) == Float(6.80, 3)
    assert E(B[2] * B[4] + B[10]).round(2) == Float(0.96, 2)
    assert E(B[2] > 0, Eq(B[1], 1) & Eq(B[2], 1)).round(2) == Float(0.60, 2)
    assert E(B[1]) == 0.6
    assert P(B[1] > 0).round(2) == Float(0.60, 2)
    assert P(B[1] < 1).round(2) == Float(0.40, 2)
    assert P(B[1] > 0, B[2] <= 1).round(2) == Float(0.60, 2)
    assert P(B[12] * B[5] > 0).round(2) == Float(0.36, 2)
    assert P(B[12] * B[5] > 0, B[4] < 1).round(2) == Float(0.36, 2)
    assert P(Eq(B[2], 1), B[2] > 0) == 1
    assert P(Eq(B[5], 3)) == 0
    assert P(Eq(B[1], 1), B[1] < 0) == 0
    assert P(B[2] > 0, Eq(B[2], 1)) == 1
    assert P(B[2] < 0, Eq(B[2], 1)) == 0
    assert P(B[2] > 0, B[2] == 7) == 0
    assert P(B[5] > 0, B[5]) == BernoulliDistribution(0.6, 0, 1)
    raises(ValueError, lambda: P(3))
    raises(ValueError, lambda: P(B[3] > 0, 3))

    # test issue 19456
    expr = Sum(B[t], (t, 0, 4))
    expr2 = Sum(B[t], (t, 1, 3))
    expr3 = Sum(B[t]**2, (t, 1, 3))
    assert expr.doit() == B[0] + B[1] + B[2] + B[3] + B[4]
    assert expr2.doit() == Y
    assert expr3.doit() == B[1]**2 + B[2]**2 + B[3]**2
    assert B[2 * t].free_symbols == {B[2 * t], t}
    assert B[4].free_symbols == {B[4]}
    assert B[x * t].free_symbols == {B[x * t], x, t}

    #test issue 20078
    assert (2 * B[t] + 3 * B[t]).simplify() == 5 * B[t]
    assert (2 * B[t] - 3 * B[t]).simplify() == -B[t]
    assert (2 * (0.25 * B[t])).simplify() == 0.5 * B[t]
    assert (2 * B[t] * 0.25 * B[t]).simplify() == 0.5 * B[t]**2
    assert (B[t]**2 + B[t]**3).simplify() == (B[t] + 1) * B[t]**2
Example #14
0
 def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
     from sympy.functions.elementary.piecewise import Piecewise
     i, j = args
     return Piecewise((0, Ne(i, j)), (1, True))
Example #15
0
def test_isolve_Sets():
    n = Dummy('n')
    assert isolve(Abs(x) <= n, x, relational=False) == \
        Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True))
Example #16
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(0, evaluate=False).doit() == 0
    assert sign(oo, evaluate=False).doit() == 1
    assert sign(nan) is 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')
    f = Function('f')
    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, H0=S(1) / 2) - 1
    assert sign(y).rewrite(Heaviside) == sign(y)
    assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y / Abs(y), True))
    assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)),
                                                (f(y) / Abs(f(y)), True))

    # 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 #17
0
def test_manualintegrate_rational():
    assert manualintegrate(1 / (4 - x**2), x) == Piecewise(
        (acoth(x / 2) / 2, x**2 > 4), (atanh(x / 2) / 2, x**2 < 4))
    assert manualintegrate(1 / (-1 + x**2), x) == Piecewise(
        (-acoth(x), x**2 > 1), (-atanh(x), x**2 < 1))
Example #18
0
 def high(self):
     return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True))
Example #19
0
def heurisch_wrapper(f, x, rewrite=False, hints=None, mappings=None, retries=3,
                     degree_offset=0, unnecessary_permutations=None):
    """
    A wrapper around the heurisch integration algorithm.

    This method takes the result from heurisch and checks for poles in the
    denominator. For each of these poles, the integral is reevaluated, and
    the final integration result is given in terms of a Piecewise.

    Examples
    ========

    >>> from sympy.core import symbols
    >>> from sympy.functions import cos
    >>> from sympy.integrals.heurisch import heurisch, heurisch_wrapper
    >>> n, x = symbols('n x')
    >>> heurisch(cos(n*x), x)
    sin(n*x)/n
    >>> heurisch_wrapper(cos(n*x), x)
    Piecewise((x, Eq(n, 0)), (sin(n*x)/n, True))

    See Also
    ========

    heurisch
    """
    from sympy.solvers.solvers import solve, denoms
    f = sympify(f)
    if x not in f.free_symbols:
        return f*x

    res = heurisch(f, x, rewrite, hints, mappings, retries, degree_offset,
                   unnecessary_permutations)
    if not isinstance(res, Basic):
        return res
    # We consider each denominator in the expression, and try to find
    # cases where one or more symbolic denominator might be zero. The
    # conditions for these cases are stored in the list slns.
    slns = []
    for d in denoms(res):
        try:
            slns += solve(d, dict=True, exclude=(x,))
        except NotImplementedError:
            pass
    if not slns:
        return res
    slns = list(uniq(slns))
    # Remove the solutions corresponding to poles in the original expression.
    slns0 = []
    for d in denoms(f):
        try:
            slns0 += solve(d, dict=True, exclude=(x,))
        except NotImplementedError:
            pass
    slns = [s for s in slns if s not in slns0]
    if not slns:
        return res
    if len(slns) > 1:
        eqs = []
        for sub_dict in slns:
            eqs.extend([Eq(key, value) for key, value in sub_dict.items()])
        slns = solve(eqs, dict=True, exclude=(x,)) + slns
    # For each case listed in the list slns, we reevaluate the integral.
    pairs = []
    for sub_dict in slns:
        expr = heurisch(f.subs(sub_dict), x, rewrite, hints, mappings, retries,
                        degree_offset, unnecessary_permutations)
        cond = And(*[Eq(key, value) for key, value in sub_dict.items()])
        pairs.append((expr, cond))
    pairs.append((heurisch(f, x, rewrite, hints, mappings, retries,
                           degree_offset, unnecessary_permutations), True))
    return Piecewise(*pairs)
Example #20
0
 def low(self):
     return Piecewise((0, Gt(0, self.n + self.m - self.N) != False),
                      (self.n + self.m - self.N, True))
Example #21
0
 def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
     i, j = args
     return Piecewise((0, Ne(i, j)), (1, True))
Example #22
0
 def pmf(self):
     k = Dummy('k')
     return Lambda(
         k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True)))
Example #23
0
 def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
     if arg.is_extended_real:
         return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
Example #24
0
 def pmf(self, x):
     x = Symbol('x')
     return Lambda(
         x,
         Piecewise(*([(v, Eq(k, x))
                      for k, v in self.dict.items()] + [(S.Zero, True)])))
Example #25
0
 def _eval_rewrite_as_Piecewise(self, arg):
     if arg.is_real:
         return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
Example #26
0
def eval_sum_symbolic(f, limits):
    from sympy.functions import harmonic, bernoulli

    f_orig = f
    (i, a, b) = limits
    if not f.has(i):
        return f * (b - a + 1)

    # Linearity
    if f.is_Mul:
        L, R = f.as_two_terms()

        if not L.has(i):
            sR = eval_sum_symbolic(R, (i, a, b))
            if sR:
                return L * sR

        if not R.has(i):
            sL = eval_sum_symbolic(L, (i, a, b))
            if sL:
                return R * sL

        try:
            f = apart(f, i)  # see if it becomes an Add
        except PolynomialError:
            pass

    if f.is_Add:
        L, R = f.as_two_terms()
        lrsum = telescopic(L, R, (i, a, b))

        if lrsum:
            return lrsum

        lsum = eval_sum_symbolic(L, (i, a, b))
        rsum = eval_sum_symbolic(R, (i, a, b))

        if None not in (lsum, rsum):
            r = lsum + rsum
            if not r is S.NaN:
                return r

    # Polynomial terms with Faulhaber's formula
    n = Wild('n')
    result = f.match(i**n)

    if result is not None:
        n = result[n]

        if n.is_Integer:
            if n >= 0:
                if (b is S.Infinity and not a is S.NegativeInfinity) or \
                   (a is S.NegativeInfinity and not b is S.Infinity):
                    return S.Infinity
                return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a)) /
                        (n + 1)).expand()
            elif a.is_Integer and a >= 1:
                if n == -1:
                    return harmonic(b) - harmonic(a - 1)
                else:
                    return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))

    if not (a.has(S.Infinity, S.NegativeInfinity)
            or b.has(S.Infinity, S.NegativeInfinity)):
        # Geometric terms
        c1 = Wild('c1', exclude=[i])
        c2 = Wild('c2', exclude=[i])
        c3 = Wild('c3', exclude=[i])
        wexp = Wild('wexp')

        # Here we first attempt powsimp on f for easier matching with the
        # exponential pattern, and attempt expansion on the exponent for easier
        # matching with the linear pattern.
        e = f.powsimp().match(c1**wexp)
        if e is not None:
            e_exp = e.pop(wexp).expand().match(c2 * i + c3)
            if e_exp is not None:
                e.update(e_exp)

        if e is not None:
            p = (c1**c3).subs(e)
            q = (c1**c2).subs(e)

            r = p * (q**a - q**(b + 1)) / (1 - q)
            l = p * (b - a + 1)

            return Piecewise((l, Eq(q, S.One)), (r, True))

        r = gosper_sum(f, (i, a, b))

        if isinstance(r, (Mul, Add)):
            from sympy import ordered, Tuple
            non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
            den = denom(together(r))
            den_sym = non_limit & den.free_symbols
            args = []
            for v in ordered(den_sym):
                try:
                    s = solve(den, v)
                    m = Eq(v, s[0]) if s else S.false
                    if m != False:
                        args.append((Sum(f_orig.subs(*m.args),
                                         limits).doit(), m))
                    break
                except NotImplementedError:
                    continue

            args.append((r, True))
            return Piecewise(*args)

        if not r in (None, S.NaN):
            return r

    h = eval_sum_hyper(f_orig, (i, a, b))
    if h is not None:
        return h

    factored = f_orig.factor()
    if factored != f_orig:
        return eval_sum_symbolic(factored, (i, a, b))
Example #27
0
 def pdf(self, *x):
     n, p = self.n, self.p
     term_1 = factorial(n)/Mul.fromiter(factorial(x_k) for x_k in x)
     term_2 = Mul.fromiter(p_k**x_k for p_k, x_k in zip(p, x))
     return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
Example #28
0
 def _eval_rewrite_as_Abs(self, arg, **kwargs):
     return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
Example #29
0
def test_hyperrep():
    from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh,
        HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
        HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
        HyperRep_cosasin, HyperRep_sinasin)
    # First test the base class works.
    from sympy.functions.elementary.exponential import exp_polar
    from sympy.functions.elementary.piecewise import Piecewise
    a, b, c, d, z = symbols('a b c d z')

    class myrep(HyperRep):
        @classmethod
        def _expr_small(cls, x):
            return a

        @classmethod
        def _expr_small_minus(cls, x):
            return b

        @classmethod
        def _expr_big(cls, x, n):
            return c*n

        @classmethod
        def _expr_big_minus(cls, x, n):
            return d*n
    assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True))
    assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \
        Piecewise((0, abs(z) > 1), (b, True))
    assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \
        Piecewise((c, abs(z) > 1), (a, True))
    assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \
        Piecewise((d, abs(z) > 1), (b, True))
    assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \
        Piecewise((2*c, abs(z) > 1), (a, True))
    assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \
        Piecewise((2*d, abs(z) > 1), (b, True))
    assert myrep(z).rewrite('nonrepsmall') == a
    assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b

    def t(func, hyp, z):
        """ Test that func is a valid representation of hyp. """
        # First test that func agrees with hyp for small z
        if not tn(func.rewrite('nonrepsmall'), hyp, z,
                  a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
            return False
        # Next check that the two small representations agree.
        if not tn(
            func.rewrite('nonrepsmall').subs(
                z, exp_polar(I*pi)*z).replace(exp_polar, exp),
            func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'),
                z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
            return False
        # Next check continuity along exp_polar(I*pi)*t
        expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep')
        if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10:
            return False
        # Finally check continuity of the big reps.

        def dosubs(func, a, b):
            rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep')
            return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp)
        for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]:
            expr1 = dosubs(func, 2*I*pi*n, I*pi/2)
            expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2)
            if not tn(expr1, expr2, z):
                return False
            expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2)
            expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2)
            if not tn(expr1, expr2, z):
                return False
        return True

    # Now test the various representatives.
    a = Rational(1, 3)
    assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z)
    assert t(HyperRep_power1(a, z), hyper([-a], [], z), z)
    assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z)
    assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z)
    assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z)
    assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z)
    assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z)
    assert t(HyperRep_sqrts2(a, z),
             -2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z)
    assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z)
    assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z)
    assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z)
Example #30
0
 def _eval_rewrite_as_Piecewise(self, arg):
     if arg.is_real:
         return Piecewise((1, arg > 0), (S(1) / 2, Eq(arg, 0)), (0, True))
Example #31
0
def test_manualintegrate_inversetrig():
    # atan
    assert manualintegrate(exp(x) / (1 + exp(2 * x)), x) == atan(exp(x))
    assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x / 2) / 6
    assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16
    assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2
    assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2 * x) / 2
    ra = Symbol('a', real=True)
    rb = Symbol('b', real=True)
    assert manualintegrate(1/(ra + rb*x**2), x) == \
        Piecewise((atan(x/sqrt(ra/rb))/(rb*sqrt(ra/rb)), ra/rb > 0),
                  (-acoth(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 > -ra/rb)),
                  (-atanh(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 < -ra/rb)))
    assert manualintegrate(1/(4 + rb*x**2), x) == \
        Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 4/rb > 0),
                  (-acoth(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 > -4/rb)),
                  (-atanh(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 < -4/rb)))
    assert manualintegrate(1/(ra + 4*x**2), x) == \
        Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra/4 > 0),
                  (-acoth(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 > -ra/4)),
                  (-atanh(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 < -ra/4)))
    assert manualintegrate(1 / (4 + 4 * x**2), x) == atan(x) / 4

    assert manualintegrate(1 / (a + b * x**2),
                           x) == atan(x / sqrt(a / b)) / (b * sqrt(a / b))

    # asin
    assert manualintegrate(1 / sqrt(1 - x**2), x) == asin(x)
    assert manualintegrate(1 / sqrt(4 - 4 * x**2), x) == asin(x) / 2
    assert manualintegrate(3 / sqrt(1 - 9 * x**2), x) == asin(3 * x)
    assert manualintegrate(1 / sqrt(4 - 9 * x**2),
                           x) == asin(x * Rational(3, 2)) / 3

    # asinh
    assert manualintegrate(1/sqrt(x**2 + 1), x) == \
        asinh(x)
    assert manualintegrate(1/sqrt(x**2 + 4), x) == \
        asinh(x/2)
    assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \
        asinh(x)/2
    assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \
        asinh(2*x)/2
    assert manualintegrate(1/sqrt(a*x**2 + 1), x) == \
        Piecewise((sqrt(-1/a)*asin(x*sqrt(-a)), a < 0), (sqrt(1/a)*asinh(sqrt(a)*x), a > 0))
    assert manualintegrate(1/sqrt(a + x**2), x) == \
        Piecewise((asinh(x*sqrt(1/a)), a > 0), (acosh(x*sqrt(-1/a)), a < 0))

    # acosh
    assert manualintegrate(1/sqrt(x**2 - 1), x) == \
        acosh(x)
    assert manualintegrate(1/sqrt(x**2 - 4), x) == \
        acosh(x/2)
    assert manualintegrate(1/sqrt(4*x**2 - 4), x) == \
        acosh(x)/2
    assert manualintegrate(1/sqrt(9*x**2 - 1), x) == \
        acosh(3*x)/3
    assert manualintegrate(1/sqrt(a*x**2 - 4), x) == \
        Piecewise((sqrt(1/a)*acosh(sqrt(a)*x/2), a > 0))
    assert manualintegrate(1/sqrt(-a + 4*x**2), x) == \
        Piecewise((asinh(2*x*sqrt(-1/a))/2, -a > 0), (acosh(2*x*sqrt(1/a))/2, -a < 0))

    # From https://www.wikiwand.com/en/List_of_integrals_of_inverse_trigonometric_functions
    # asin
    assert manualintegrate(asin(x), x) == x * asin(x) + sqrt(1 - x**2)
    assert manualintegrate(asin(a * x), x) == Piecewise(
        ((a * x * asin(a * x) + sqrt(-a**2 * x**2 + 1)) / a, Ne(a, 0)),
        (0, True))
    assert manualintegrate(x * asin(a * x), x) == -a * Integral(
        x**2 / sqrt(-a**2 * x**2 + 1), x) / 2 + x**2 * asin(a * x) / 2
    # acos
    assert manualintegrate(acos(x), x) == x * acos(x) - sqrt(1 - x**2)
    assert manualintegrate(acos(a * x), x) == Piecewise(
        ((a * x * acos(a * x) - sqrt(-a**2 * x**2 + 1)) / a, Ne(a, 0)),
        (pi * x / 2, True))
    assert manualintegrate(x * acos(a * x), x) == a * Integral(
        x**2 / sqrt(-a**2 * x**2 + 1), x) / 2 + x**2 * acos(a * x) / 2
    # atan
    assert manualintegrate(atan(x), x) == x * atan(x) - log(x**2 + 1) / 2
    assert manualintegrate(atan(a * x), x) == Piecewise(
        ((a * x * atan(a * x) - log(a**2 * x**2 + 1) / 2) / a, Ne(a, 0)),
        (0, True))
    assert manualintegrate(
        x * atan(a * x),
        x) == -a * (x / a**2 - atan(x / sqrt(a**(-2))) /
                    (a**4 * sqrt(a**(-2)))) / 2 + x**2 * atan(a * x) / 2
    # acsc
    assert manualintegrate(
        acsc(x), x) == x * acsc(x) + Integral(1 / (x * sqrt(1 - 1 / x**2)), x)
    assert manualintegrate(
        acsc(a * x),
        x) == x * acsc(a * x) + Integral(1 / (x * sqrt(1 - 1 /
                                                       (a**2 * x**2))), x) / a
    assert manualintegrate(x * acsc(a * x),
                           x) == x**2 * acsc(a * x) / 2 + Integral(
                               1 / sqrt(1 - 1 / (a**2 * x**2)), x) / (2 * a)
    # asec
    assert manualintegrate(
        asec(x), x) == x * asec(x) - Integral(1 / (x * sqrt(1 - 1 / x**2)), x)
    assert manualintegrate(
        asec(a * x),
        x) == x * asec(a * x) - Integral(1 / (x * sqrt(1 - 1 /
                                                       (a**2 * x**2))), x) / a
    assert manualintegrate(x * asec(a * x),
                           x) == x**2 * asec(a * x) / 2 - Integral(
                               1 / sqrt(1 - 1 / (a**2 * x**2)), x) / (2 * a)
    # acot
    assert manualintegrate(acot(x), x) == x * acot(x) + log(x**2 + 1) / 2
    assert manualintegrate(acot(a * x), x) == Piecewise(
        ((a * x * acot(a * x) + log(a**2 * x**2 + 1) / 2) / a, Ne(a, 0)),
        (pi * x / 2, True))
    assert manualintegrate(
        x * acot(a * x),
        x) == a * (x / a**2 - atan(x / sqrt(a**(-2))) /
                   (a**4 * sqrt(a**(-2)))) / 2 + x**2 * acot(a * x) / 2

    # piecewise
    assert manualintegrate(1/sqrt(a-b*x**2), x) == \
        Piecewise((sqrt(a/b)*asin(x*sqrt(b/a))/sqrt(a), And(-b < 0, a > 0)),
                  (sqrt(-a/b)*asinh(x*sqrt(-b/a))/sqrt(a), And(-b > 0, a > 0)),
                  (sqrt(a/b)*acosh(x*sqrt(b/a))/sqrt(-a), And(-b > 0, a < 0)))
    assert manualintegrate(1/sqrt(a + b*x**2), x) == \
        Piecewise((sqrt(-a/b)*asin(x*sqrt(-b/a))/sqrt(a), And(a > 0, b < 0)),
                  (sqrt(a/b)*asinh(x*sqrt(b/a))/sqrt(a), And(a > 0, b > 0)),
                  (sqrt(-a/b)*acosh(x*sqrt(-b/a))/sqrt(-a), And(a < 0, b > 0)))
Example #32
0
def test_issue_14238():
    # doesn't cause recursion error
    r = Symbol('r', real=True)
    assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))