Exemple #1
0
def test_literal_evalf_is_number_is_zero_is_comparable():
    from sympy.integrals.integrals import Integral
    from sympy.core.symbol import symbols
    from sympy.core.function import Function
    from sympy.functions.elementary.trigonometric import cos, sin
    x = symbols('x')
    f = Function('f')

    # issue 5033
    assert f.is_number is False
    # issue 6646
    assert f(1).is_number is False
    i = Integral(0, (x, x, x))
    # expressions that are symbolically 0 can be difficult to prove
    # so in case there is some easy way to know if something is 0
    # it should appear in the is_zero property for that object;
    # if is_zero is true evalf should always be able to compute that
    # zero
    assert i.n() == 0
    assert i.is_zero
    assert i.is_number is False
    assert i.evalf(2, strict=False) == 0

    # issue 10268
    n = sin(1)**2 + cos(1)**2 - 1
    assert n.is_comparable is False
    assert n.n(2).is_comparable is False
    assert n.n(2).n(2).is_comparable
Exemple #2
0
def test_literal_evalf_is_number_is_zero_is_comparable():
    from sympy.integrals.integrals import Integral
    from sympy.core.symbol import symbols
    from sympy.core.function import Function
    from sympy.functions.elementary.trigonometric import cos, sin
    x = symbols('x')
    f = Function('f')

    # the following should not be changed without a lot of dicussion
    # `foo.is_number` should be equivalent to `not foo.free_symbols`
    # it should not attempt anything fancy; see is_zero, is_constant
    # and equals for more rigorous tests.
    assert f(1).is_number is True
    i = Integral(0, (x, x, x))
    # expressions that are symbolically 0 can be difficult to prove
    # so in case there is some easy way to know if something is 0
    # it should appear in the is_zero property for that object;
    # if is_zero is true evalf should always be able to compute that
    # zero
    assert i.n() == 0
    assert i.is_zero
    assert i.is_number is False
    assert i.evalf(2, strict=False) == 0

    # issue 10268
    n = sin(1)**2 + cos(1)**2 - 1
    assert n.is_comparable is False
    assert n.n(2).is_comparable is False
    assert n.n(2).n(2).is_comparable
Exemple #3
0
def test_evalf_integral():
    # test that workprec has to increase in order to get a result other than 0
    eps = Rational(1, 1000000)
    assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
Exemple #4
0
 def _eval_rewrite_as_Integral(self, *args):
     from sympy.integrals.integrals import Integral
     z, m = (pi / 2, self.args[0]) if len(self.args) == 1 else self.args
     t = Dummy('t')
     return Integral(sqrt(1 - m * sin(t)**2), (t, 0, z))
Exemple #5
0
def apply():
    x = Symbol.x(real=True)
    return Equality(1 / sqrt(2 * pi) * Integral(exp(-x * x / 2), (x, -oo, oo)),
                    1,
                    evaluate=False)
Exemple #6
0
def test_double_integral():
    # example from http://mpmath.org/doc/current/calculus/integration.html
    i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
    l = lambdify([z], i)
    d = l(1)
    assert 1.23370055 < d < 1.233700551
Exemple #7
0
def test_factor_terms():
    A = Symbol('A', commutative=False)
    assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
        9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
    assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
        _keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
    assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
        9*3**(2*x)*(a + 1)
    assert factor_terms(x + x*A) == \
        x*(1 + A)
    assert factor_terms(sin(x + x*A)) == \
        sin(x*(1 + A))
    assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
        _keep_coeff(S(3), x + 1)**_keep_coeff(Rational(2, 3), x + 1)
    assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
        x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
    assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
        x*(a + 2*b)*(y + 1)
    i = Integral(x, (x, 0, oo))
    assert factor_terms(i) == i

    assert factor_terms(x / 2 + y) == x / 2 + y
    # fraction doesn't apply to integer denominators
    assert factor_terms(x / 2 + y, fraction=True) == x / 2 + y
    # clear *does* apply to the integer denominators
    assert factor_terms(x / 2 + y, clear=True) == Mul(S.Half,
                                                      x + 2 * y,
                                                      evaluate=False)

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

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

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

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

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

    # if not True, then "special" processesing in factor_terms is not necessary
    assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
    e = exp(-x - 2) + x
    assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
    assert factor_terms(e, sign=False) == e
    assert factor_terms(exp(-4 * x - 2) -
                        x) == -x + exp(Mul(-2, 2 * x + 1, evaluate=False))

    # sum/integral tests
    for F in (Sum, Integral):
        assert factor_terms(F(x, (y, 1, 10))) == x * F(1, (y, 1, 10))
        assert factor_terms(F(x, (y, 1, 10)) + x) == x * (1 + F(1, (y, 1, 10)))
        assert factor_terms(F(x * y + x * y**2,
                              (y, 1, 10))) == x * F(y * (y + 1), (y, 1, 10))
Exemple #8
0
def test_count_ops_visual():
    ADD, MUL, POW, SIN, COS, EXP, AND, D, G, M = symbols(
        'Add Mul Pow sin cos exp And Derivative Integral Sum'.upper())
    DIV, SUB, NEG = symbols('DIV SUB NEG')
    LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE')
    NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols(
        'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper())

    def count(val):
        return count_ops(val, visual=True)

    assert count(7) is S.Zero
    assert count(S(7)) is S.Zero
    assert count(-1) == NEG
    assert count(-2) == NEG
    assert count(S(2) / 3) == DIV
    assert count(Rational(2, 3)) == DIV
    assert count(pi / 3) == DIV
    assert count(-pi / 3) == DIV + NEG
    assert count(I - 1) == SUB
    assert count(1 - I) == SUB
    assert count(1 - 2 * I) == SUB + MUL

    assert count(x) is S.Zero
    assert count(-x) == NEG
    assert count(-2 * x / 3) == NEG + DIV + MUL
    assert count(Rational(-2, 3) * x) == NEG + DIV + MUL
    assert count(1 / x) == DIV
    assert count(1 / (x * y)) == DIV + MUL
    assert count(-1 / x) == NEG + DIV
    assert count(-2 / x) == NEG + DIV
    assert count(x / y) == DIV
    assert count(-x / y) == NEG + DIV

    assert count(x**2) == POW
    assert count(-x**2) == POW + NEG
    assert count(-2 * x**2) == POW + MUL + NEG

    assert count(x + pi / 3) == ADD + DIV
    assert count(x + S.One / 3) == ADD + DIV
    assert count(x + Rational(1, 3)) == ADD + DIV
    assert count(x + y) == ADD
    assert count(x - y) == SUB
    assert count(y - x) == SUB
    assert count(-1 / (x - y)) == DIV + NEG + SUB
    assert count(-1 / (y - x)) == DIV + NEG + SUB
    assert count(1 + x**y) == ADD + POW
    assert count(1 + x + y) == 2 * ADD
    assert count(1 + x + y + z) == 3 * ADD
    assert count(1 + x**y + 2 * x * y + y**2) == 3 * ADD + 2 * POW + 2 * MUL
    assert count(2 * z + y + x + 1) == 3 * ADD + MUL
    assert count(2 * z + y**17 + x + 1) == 3 * ADD + MUL + POW
    assert count(2 * z + y**17 + x + sin(x)) == 3 * ADD + POW + MUL + SIN
    assert count(2 * z + y**17 + x +
                 sin(x**2)) == 3 * ADD + MUL + 2 * POW + SIN
    assert count(2 * z + y**17 + x + sin(x**2) +
                 exp(cos(x))) == 4 * ADD + MUL + 2 * POW + EXP + COS + SIN

    assert count(Derivative(x, x)) == D
    assert count(Integral(x, x) + 2 * x / (1 + x)) == G + DIV + MUL + 2 * ADD
    assert count(Sum(x, (x, 1, x + 1)) + 2 * x /
                 (1 + x)) == M + DIV + MUL + 3 * ADD
    assert count(Basic()) is S.Zero

    assert count({x + 1: sin(x)}) == ADD + SIN
    assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD
    assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2 * ADD
    assert count({}) is S.Zero
    assert count([x + 1, sin(x) * y, None]) == SIN + ADD + MUL
    assert count([]) is S.Zero

    assert count(Basic()) == 0
    assert count(Basic(Basic(), Basic(x, x + y))) == ADD + 2 * BASIC
    assert count(Basic(x, x + y)) == ADD + BASIC
    assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split()
            ] == [LT, LE, GT, GE, EQ, NE, NE]
    assert count(Or(x, y)) == OR
    assert count(And(x, y)) == AND
    assert count(Or(x, Or(y, And(z, a)))) == AND + OR
    assert count(Nor(x, y)) == NOT + OR
    assert count(Nand(x, y)) == NOT + AND
    assert count(Xor(x, y)) == XOR
    assert count(Implies(x, y)) == IMPLIES
    assert count(Equivalent(x, y)) == EQUIVALENT
    assert count(ITE(x, y, z)) == _ITE
    assert count([Or(x, y), And(x, y), Basic(x + y)]) == ADD + AND + BASIC + OR

    assert count(Basic(Tuple(x))) == BASIC + TUPLE
    #It checks that TUPLE is counted as an operation.

    assert count(Eq(x + y, S(2))) == ADD + EQ
Exemple #9
0
def linodesolve(A, t, b=None, B=None, type="auto", doit=False):
    r"""
    System of n equations linear first-order differential equations

    Explanation
    ===========

    This solver solves the system of ODEs of the follwing form:

    .. math::
        X'(t) = A(t) X(t) +  b(t)

    Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
    $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$

    Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
    differently.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
    the solution is:

    .. math::
        X(t) = \exp(A t) C

    Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
    the solution is:

    .. math::
        X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)

    When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
    $b(t)$ is a zero vector i.e. system is homogeneous, the solution is:

    .. math::
        X(t) = \exp(B(t)) C

    When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
    non-homogeneous, the solution is:

    .. math::
        X(t) =  e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)

    The final solution is the general solution for all the four equations since a constant coefficient
    matrix is always commutative with its antidervative.

    Parameters
    ==========

    A : Matrix
        Coefficient matrix of the system of linear first order ODEs.
    t : Symbol
        Independent variable in the system of ODEs.
    b : Matrix or None
        Non-homogeneous term in the system of ODEs. If None is passed,
        a homogeneous system of ODEs is assumed.
    B : Matrix or None
        Antiderivative of the coefficient matrix. If the antiderivative
        is not passed and the solution requires the term, then the solver
        would compute it internally.
    type : String
        Type of the system of ODEs passed. Depending on the type, the
        solution is evaluated. The type values allowed and the corresponding
        system it solves are: "type1" for constant coefficient homogeneous
        "type2" for constant coefficient non-homogeneous, "type3" for non-constant
        coefficient homogeneous and "type4" for non-constant coefficient non-homogeneous.
        The default value is "auto" which will let the solver decide the correct type of
        the system passed.
    doit : Boolean
        Evaluate the solution if True, default value is False

    Examples
    ========

    To solve the system of ODEs using this function directly, several things must be
    done in the right order. Wrong inputs to the function will lead to incorrect results.

    >>> from sympy import symbols, Function, Eq
    >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
    >>> from sympy.solvers.ode.subscheck import checkodesol
    >>> f, g = symbols("f, g", cls=Function)
    >>> x, a = symbols("x, a")
    >>> funcs = [f(x), g(x)]
    >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]

    Here, it is important to note that before we derive the coefficient matrix, it is
    important to get the system of ODEs into the desired form. For that we will use
    :obj:`sympy.solvers.ode.systems.canonical_odes()`.

    >>> eqs = canonical_odes(eqs, funcs, x)
    >>> eqs
    [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]

    Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
    non-homogeneous term if it is there.

    >>> eqs = eqs[0]
    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = A0

    We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
    :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
    to finally pass it to the solver.

    >>> system_info = linodesolve_type(A, x, b=b)
    >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type'])

    Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checkodesol(eqs, sol)
    (True, [0, 0])

    We can also use the doit method to evaluate the solutions passed by the function.

    >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)

    Now, we will look at a system of ODEs which is non-constant.

    >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]

    The system defined above is already in the desired form, so we don't have to convert it.

    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = A0

    A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
    Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
    with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
    If it does have a commutative antiderivative, then the function just returns the information about the system.

    >>> system_info = linodesolve_type(A, x, b=b)

    Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
    passed, then the solver will compute the required arguments internally.

    >>> sol_vector = linodesolve(A, x, b=b)

    Once again, we can verify the solution obtained.

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checkodesol(eqs, sol)
    (True, [0, 0])

    Returns
    =======

    List

    Raises
    ======

    ValueError
        This error is raised when the coefficient matrix, non-homogeneous term
        or the antiderivative, if passed, aren't a matrix or
        don't have correct dimensions
    NonSquareMatrixError
        When the coefficient matrix or its antiderivative, if passed isn't a square
        matrix
    NotImplementedError
        If the coefficient matrix doesn't have a commutative antiderivative

    See Also
    ========

    linear_ode_to_matrix: Coefficient matrix computation function
    canonical_odes: System of ODEs representation change
    linodesolve_type: Getting information about systems of ODEs to pass in this solver

    """

    if not isinstance(A, MatrixBase):
        raise ValueError(
            filldedent('''\
            The coefficients of the system of ODEs should be of type Matrix
        '''))

    if not A.is_square:
        raise NonSquareMatrixError(
            filldedent('''\
            The coefficient matrix must be a square
        '''))

    if b is not None:
        if not isinstance(b, MatrixBase):
            raise ValueError(
                filldedent('''\
                The non-homogeneous terms of the system of ODEs should be of type Matrix
            '''))

        if A.rows != b.rows:
            raise ValueError(
                filldedent('''\
                The system of ODEs should have the same number of non-homogeneous terms and the number of
                equations
            '''))

    if B is not None:
        if not isinstance(B, MatrixBase):
            raise ValueError(
                filldedent('''\
                The antiderivative of coefficients of the system of ODEs should be of type Matrix
            '''))

        if not B.is_square:
            raise NonSquareMatrixError(
                filldedent('''\
                The antiderivative of the coefficient matrix must be a square
            '''))

        if A.rows != B.rows:
            raise ValueError(
                filldedent('''\
                        The coefficient matrix and its antiderivative should have same dimensions
                    '''))

    if not any(type == "type{}".format(i)
               for i in range(1, 5)) and not type == "auto":
        raise ValueError(
            filldedent('''\
                    The input type should be a valid one
                '''))

    n = A.rows

    # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
    Cvect = Matrix(list(Dummy() for _ in range(n)))

    if (type == "type2" or type == "type4") and b is None:
        b = zeros(n, 1)

    if type == "auto":
        system_info = linodesolve_type(A, t, b=b)
        type = system_info["type"]
        B = system_info["antiderivative"]

    if type == "type1" or type == "type2":
        P, J = matrix_exp_jordan_form(A, t)
        P = simplify(P)

        if type == "type1":
            sol_vector = P * (J * Cvect)
        else:
            sol_vector = P * J * (
                (J.inv() * P.inv() * b).applyfunc(lambda x: Integral(x, t)) +
                Cvect)

    else:
        if B is None:
            B, _ = _is_commutative_anti_derivative(A, t)

        if type == "type3":
            sol_vector = B.exp() * Cvect
        else:
            sol_vector = B.exp() * ((
                (-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)

    gens = sol_vector.atoms(exp)

    if type != "type1":
        sol_vector = [expand_mul(s) for s in sol_vector]

    sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]

    if doit:
        sol_vector = [s.doit() for s in sol_vector]

    return sol_vector
Exemple #10
0
def piecewise_linear():
    from sympy.integrals.rubi.constraints import cons1092, cons19, cons1093, cons89, cons90, cons1094, cons91, cons25, cons74, cons68, cons4, cons1095, cons216, cons685, cons102, cons103, cons1096, cons1097, cons33, cons96, cons358, cons1098, cons21, cons1099, cons2, cons3


    pattern1885 = Pattern(Integral(u_**WC('m', S(1)), x_), cons19, cons1092)
    rule1885 = ReplacementRule(pattern1885, With1885)

    pattern1886 = Pattern(Integral(v_/u_, x_), cons1093, CustomConstraint(With1886))
    rule1886 = ReplacementRule(pattern1886, replacement1886)

    pattern1887 = Pattern(Integral(v_**n_/u_, x_), cons1093, cons89, cons90, cons1094, CustomConstraint(With1887))
    rule1887 = ReplacementRule(pattern1887, replacement1887)

    pattern1888 = Pattern(Integral(S(1)/(u_*v_), x_), cons1093, CustomConstraint(With1888))
    rule1888 = ReplacementRule(pattern1888, replacement1888)

    pattern1889 = Pattern(Integral(S(1)/(u_*sqrt(v_)), x_), cons1093, CustomConstraint(With1889))
    rule1889 = ReplacementRule(pattern1889, replacement1889)

    pattern1890 = Pattern(Integral(S(1)/(u_*sqrt(v_)), x_), cons1093, CustomConstraint(With1890))
    rule1890 = ReplacementRule(pattern1890, replacement1890)

    pattern1891 = Pattern(Integral(v_**n_/u_, x_), cons1093, cons89, cons91, CustomConstraint(With1891))
    rule1891 = ReplacementRule(pattern1891, replacement1891)

    pattern1892 = Pattern(Integral(v_**n_/u_, x_), cons1093, cons25, CustomConstraint(With1892))
    rule1892 = ReplacementRule(pattern1892, replacement1892)

    pattern1893 = Pattern(Integral(S(1)/(sqrt(u_)*sqrt(v_)), x_), cons1093, CustomConstraint(With1893))
    rule1893 = ReplacementRule(pattern1893, replacement1893)

    pattern1894 = Pattern(Integral(S(1)/(sqrt(u_)*sqrt(v_)), x_), cons1093, CustomConstraint(With1894))
    rule1894 = ReplacementRule(pattern1894, replacement1894)

    pattern1895 = Pattern(Integral(u_**m_*v_**n_, x_), cons19, cons4, cons1093, cons74, cons68, CustomConstraint(With1895))
    rule1895 = ReplacementRule(pattern1895, replacement1895)

    pattern1896 = Pattern(Integral(u_**m_*v_**WC('n', S(1)), x_), cons19, cons4, cons1093, cons68, cons1095, CustomConstraint(With1896))
    rule1896 = ReplacementRule(pattern1896, replacement1896)

    pattern1897 = Pattern(Integral(u_**m_*v_**WC('n', S(1)), x_), cons1093, cons216, cons89, cons90, cons685, cons102, cons103, CustomConstraint(With1897))
    rule1897 = ReplacementRule(pattern1897, replacement1897)

    pattern1898 = Pattern(Integral(u_**m_*v_**n_, x_), cons1093, cons685, cons1096, cons1097, CustomConstraint(With1898))
    rule1898 = ReplacementRule(pattern1898, replacement1898)

    pattern1899 = Pattern(Integral(u_**m_*v_**n_, x_), cons1093, cons216, cons33, cons96, CustomConstraint(With1899))
    rule1899 = ReplacementRule(pattern1899, replacement1899)

    pattern1900 = Pattern(Integral(u_**m_*v_**n_, x_), cons1093, cons358, cons1098, CustomConstraint(With1900))
    rule1900 = ReplacementRule(pattern1900, replacement1900)

    pattern1901 = Pattern(Integral(u_**m_*v_**n_, x_), cons1093, cons21, cons25, CustomConstraint(With1901))
    rule1901 = ReplacementRule(pattern1901, replacement1901)

    pattern1902 = Pattern(Integral(u_**WC('n', S(1))*log(x_*WC('b', S(1)) + WC('a', S(0))), x_), cons2, cons3, cons1092, cons1099, cons89, cons90)
    rule1902 = ReplacementRule(pattern1902, With1902)

    pattern1903 = Pattern(Integral(u_**WC('n', S(1))*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*log(x_*WC('b', S(1)) + WC('a', S(0))), x_), cons2, cons3, cons19, cons1092, cons1099, cons89, cons90, cons68)
    rule1903 = ReplacementRule(pattern1903, With1903)
    return [rule1885, rule1886, rule1887, rule1888, rule1889, rule1890, rule1891, rule1892, rule1893, rule1894, rule1895, rule1896, rule1897, rule1898, rule1899, rule1900, rule1901, rule1902, rule1903, ]
Exemple #11
0
def test_constant_independent_of_symbol():
    assert manualintegrate(Integral(y, (x, 1, 2)), x) == \
        x*Integral(y, (x, 1, 2))
Exemple #12
0
def test_issue_12899():
    assert manualintegrate(f(x, y).diff(x),
                           y) == Integral(Derivative(f(x, y), x), y)
    assert manualintegrate(f(x, y).diff(y).diff(x),
                           y) == Derivative(f(x, y), x)
Exemple #13
0
def test_manualintegrate_trivial_substitution():
    assert manualintegrate((exp(x) - exp(-x)) / x, x) == -Ei(-x) + Ei(x)
    f = Function('f')
    assert manualintegrate((f(x) - f(-x))/x, x) == \
        -Integral(f(-x)/x, x) + Integral(f(x)/x, x)
Exemple #14
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(ra*x**2 + 1), x) == \
        Piecewise((asin(x*sqrt(-ra))/sqrt(-ra), ra < 0), (asinh(sqrt(ra)*x)/sqrt(ra), ra > 0))
    assert manualintegrate(1/sqrt(ra + x**2), x) == \
        Piecewise((asinh(x*sqrt(1/ra)), ra > 0), (acosh(x*sqrt(-1/ra)), ra < 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(ra*x**2 - 4), x) == \
        Piecewise((acosh(sqrt(ra)*x/2)/sqrt(ra), ra > 0))
    assert manualintegrate(1/sqrt(-ra + 4*x**2), x) == \
        Piecewise((asinh(2*x*sqrt(-1/ra))/2, -ra > 0), (acosh(2*x*sqrt(1/ra))/2, -ra < 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(ra-rb*x**2), x) == \
        Piecewise((asin(x*sqrt(rb/ra))/sqrt(rb), And(-rb < 0, ra > 0)),
                  (asinh(x*sqrt(-rb/ra))/sqrt(-rb), And(-rb > 0, ra > 0)),
                  (acosh(x*sqrt(rb/ra))/sqrt(-rb), And(-rb > 0, ra < 0)))
    assert manualintegrate(1/sqrt(ra + rb*x**2), x) == \
        Piecewise((asin(x*sqrt(-rb/ra))/sqrt(-rb), And(ra > 0, rb < 0)),
                  (asinh(x*sqrt(rb/ra))/sqrt(rb), And(ra > 0, rb > 0)),
                  (acosh(x*sqrt(-rb/ra))/sqrt(rb), And(ra < 0, rb > 0)))
def test_issue_15920():
    r = rootof(x**5 - x + 1, 0)
    p = Integral(x, (x, 1, y))
    assert unchanged(Eq, r, p)
def test_requires_partial():
    x, y, z, t, nu = symbols('x y z t nu')
    n = symbols('n', integer=True)

    f = x * y
    assert requires_partial(Derivative(f, x)) is True
    assert requires_partial(Derivative(f, y)) is True

    ## integrating out one of the variables
    assert requires_partial(
        Derivative(Integral(exp(-x * y),
                            (x, 0, oo)), y, evaluate=False)) is False

    ## bessel function with smooth parameter
    f = besselj(nu, x)
    assert requires_partial(Derivative(f, x)) is True
    assert requires_partial(Derivative(f, nu)) is True

    ## bessel function with integer parameter
    f = besselj(n, x)
    assert requires_partial(Derivative(f, x)) is False
    # this is not really valid (differentiating with respect to an integer)
    # but there's no reason to use the partial derivative symbol there. make
    # sure we don't throw an exception here, though
    assert requires_partial(Derivative(f, n)) is False

    ## bell polynomial
    f = bell(n, x)
    assert requires_partial(Derivative(f, x)) is False
    # again, invalid
    assert requires_partial(Derivative(f, n)) is False

    ## legendre polynomial
    f = legendre(0, x)
    assert requires_partial(Derivative(f, x)) is False

    f = legendre(n, x)
    assert requires_partial(Derivative(f, x)) is False
    # again, invalid
    assert requires_partial(Derivative(f, n)) is False

    f = x**n
    assert requires_partial(Derivative(f, x)) is False

    assert requires_partial(
        Derivative(
            Integral((x * y)**n * exp(-x * y),
                     (x, 0, oo)), y, evaluate=False)) is False

    # parametric equation
    f = (exp(t), cos(t))
    g = sum(f)
    assert requires_partial(Derivative(g, t)) is False

    f = symbols('f', cls=Function)
    assert requires_partial(Derivative(f(x), x)) is False
    assert requires_partial(Derivative(f(x), y)) is False
    assert requires_partial(Derivative(f(x, y), x)) is True
    assert requires_partial(Derivative(f(x, y), y)) is True
    assert requires_partial(Derivative(f(x, y), z)) is True
    assert requires_partial(Derivative(f(x, y), x, y)) is True
Exemple #17
0
def test_issue_4021():
    e = Integral(x, x) + 1
    assert str(e) == 'Integral(x, x) + 1'
Exemple #18
0
def test_Integral():
    assert precedence(Integral(x,y)) == PRECEDENCE["Atom"]
Exemple #19
0
def test_ellipse_geom():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    t = Symbol('t', real=True)
    y1 = Symbol('y1', real=True)
    half = Rational(1, 2)
    p1 = Point(0, 0)
    p2 = Point(1, 1)
    p4 = Point(0, 1)

    e1 = Ellipse(p1, 1, 1)
    e2 = Ellipse(p2, half, 1)
    e3 = Ellipse(p1, y1, y1)
    c1 = Circle(p1, 1)
    c2 = Circle(p2, 1)
    c3 = Circle(Point(sqrt(2), sqrt(2)), 1)
    l1 = Line(p1, p2)

    # Test creation with three points
    cen, rad = Point(3 * half, 2), 5 * half
    assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad)
    raises(GeometryError,
           lambda: Circle(Point(0, 0), Point(1, 1), Point(2, 2)))

    raises(ValueError, lambda: Ellipse(None, None, None, 1))
    raises(GeometryError, lambda: Circle(Point(0, 0)))

    # Basic Stuff
    assert Ellipse(None, 1, 1).center == Point(0, 0)
    assert e1 == c1
    assert e1 != e2
    assert e1 != l1
    assert p4 in e1
    assert p2 not in e2
    assert e1.area == pi
    assert e2.area == pi / 2
    assert e3.area == pi * y1 * abs(y1)
    assert c1.area == e1.area
    assert c1.circumference == e1.circumference
    assert e3.circumference == 2 * pi * y1
    assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi]
    assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi]
    assert Ellipse(None, 1, None, 1).circumference == 2 * pi
    assert c1.minor == 1
    assert c1.major == 1
    assert c1.hradius == 1
    assert c1.vradius == 1

    # Private Functions
    assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1)))
    assert c1 in e1
    assert (Line(p1, p2) in e1) is False
    assert e1.__cmp__(e1) == 0
    assert e1.__cmp__(Point(0, 0)) > 0

    # Encloses
    assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True
    assert e1.encloses(Line(p1, p2)) is False
    assert e1.encloses(Ray(p1, p2)) is False
    assert e1.encloses(e1) is False
    assert e1.encloses(
        Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True
    assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True
    assert e1.encloses(RegularPolygon(p1, 5, 3)) is False
    assert e1.encloses(RegularPolygon(p2, 5, 3)) is False

    # with generic symbols, the hradius is assumed to contain the major radius
    M = Symbol('M')
    m = Symbol('m')
    c = Ellipse(p1, M, m).circumference
    _x = c.atoms(Dummy).pop()
    assert c == 4 * M * Integral(
        sqrt((1 - _x**2 * (M**2 - m**2) / M**2) / (1 - _x**2)), (_x, 0, 1))

    assert e2.arbitrary_point() in e2

    # Foci
    f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0)
    ef = Ellipse(Point(0, 0), 4, 2)
    assert ef.foci in [(f1, f2), (f2, f1)]

    # Tangents
    v = sqrt(2) / 2
    p1_1 = Point(v, v)
    p1_2 = p2 + Point(half, 0)
    p1_3 = p2 + Point(0, 1)
    assert e1.tangent_lines(p4) == c1.tangent_lines(p4)
    assert e2.tangent_lines(p1_2) == [
        Line(Point(3 / 2, 1), Point(3 / 2, 1 / 2))
    ]
    assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(5 / 4, 2))]
    assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))]
    assert c1.tangent_lines(p1) == []
    assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1)))
    assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1)))
    assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2))))
    assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False
    assert c1.is_tangent(e1) is False
    assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True
    assert c1.is_tangent(Polygon(Point(1, 1), Point(1, -1), Point(2,
                                                                  0))) is True
    assert c1.is_tangent(Polygon(Point(1, 1), Point(1, 0), Point(2,
                                                                 0))) is False
    assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False

    assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \
        [Line(Point(0, 0), Point(77/25, 132/25)),
     Line(Point(0, 0), Point(33/5, 22/5))]
    assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \
        [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))]
    assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \
        [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))]
    assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \
        [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))),
     Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ]

    # for numerical calculations, we shouldn't demand exact equality,
    # so only test up to the desired precision
    def lines_close(l1, l2, prec):
        """ tests whether l1 and 12 are within 10**(-prec)
        of each other """
        return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 -
                                                        l2.p2) < 10**(-prec)

    def line_list_close(ll1, ll2, prec):
        return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2))

    e = Ellipse(Point(0, 0), 2, 1)
    assert e.normal_lines(Point(0, 0)) == \
        [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))]
    assert e.normal_lines(Point(1, 0)) == \
        [Line(Point(0, 0), Point(1, 0))]
    assert e.normal_lines((0, 1)) == \
        [Line(Point(0, 0), Point(0, 1))]
    assert line_list_close(e.normal_lines(Point(1, 1), 2), [
        Line(Point(-51 / 26, -1 / 5), Point(-25 / 26, 17 / 83)),
        Line(Point(28 / 29, -7 / 8), Point(57 / 29, -9 / 2))
    ], 2)
    # test the failure of Poly.intervals and checks a point on the boundary
    p = Point(sqrt(3), S.Half)
    assert p in e
    assert line_list_close(e.normal_lines(p, 2), [
        Line(Point(-341 / 171, -1 / 13), Point(-170 / 171, 5 / 64)),
        Line(Point(26 / 15, -1 / 2), Point(41 / 15, -43 / 26))
    ], 2)
    # be sure to use the slope that isn't undefined on boundary
    e = Ellipse((0, 0), 2, 2 * sqrt(3) / 3)
    assert line_list_close(e.normal_lines((1, 1), 2), [
        Line(Point(-64 / 33, -20 / 71), Point(-31 / 33, 2 / 13)),
        Line(Point(1, -1), Point(2, -4))
    ], 2)
    # general ellipse fails except under certain conditions
    e = Ellipse((0, 0), x, 1)
    assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))]
    raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1)))

    # Properties
    major = 3
    minor = 1
    e4 = Ellipse(p2, minor, major)
    assert e4.focus_distance == sqrt(major**2 - minor**2)
    ecc = e4.focus_distance / major
    assert e4.eccentricity == ecc
    assert e4.periapsis == major * (1 - ecc)
    assert e4.apoapsis == major * (1 + ecc)
    # independent of orientation
    e4 = Ellipse(p2, major, minor)
    assert e4.focus_distance == sqrt(major**2 - minor**2)
    ecc = e4.focus_distance / major
    assert e4.eccentricity == ecc
    assert e4.periapsis == major * (1 - ecc)
    assert e4.apoapsis == major * (1 + ecc)

    # Intersection
    l1 = Line(Point(1, -5), Point(1, 5))
    l2 = Line(Point(-5, -1), Point(5, -1))
    l3 = Line(Point(-1, -1), Point(1, 1))
    l4 = Line(Point(-10, 0), Point(0, 10))
    pts_c1_l3 = [
        Point(sqrt(2) / 2,
              sqrt(2) / 2),
        Point(-sqrt(2) / 2, -sqrt(2) / 2)
    ]

    assert intersection(e2, l4) == []
    assert intersection(c1, Point(1, 0)) == [Point(1, 0)]
    assert intersection(c1, l1) == [Point(1, 0)]
    assert intersection(c1, l2) == [Point(0, -1)]
    assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]]
    assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)]
    assert intersection(c1, c3) == [Point(sqrt(2) / 2, sqrt(2) / 2)]
    assert e1.intersection(l1) == [Point(1, 0)]
    assert e2.intersection(l4) == []
    assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)]
    assert e1.intersection(Circle(Point(5, 0), 1)) == []
    assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)]
    assert e1.intersection(Ellipse(
        Point(5, 0),
        1,
        1,
    )) == []
    assert e1.intersection(Point(2, 0)) == []
    assert e1.intersection(e1) == e1
    assert intersection(Ellipse(Point(0, 0), 2, 1),
                        Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)]
    assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0),
                                                       1)) == [Point(2, 0)]
    assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == []
    assert intersection(Ellipse(Point(0, 0), 5, 17),
                        Ellipse(Point(4, 0), 1, 0.2)) == [Point(5, 0)]
    assert intersection(Ellipse(Point(0, 0), 5, 17),
                        Ellipse(Point(4, 0), 0.999, 0.2)) == []
    raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1))))
    raises(TypeError, lambda: intersection(e2, Rational(12)))
    # some special case intersections
    csmall = Circle(p1, 3)
    cbig = Circle(p1, 5)
    cout = Circle(Point(5, 5), 1)
    # one circle inside of another
    assert csmall.intersection(cbig) == []
    # separate circles
    assert csmall.intersection(cout) == []
    # coincident circles
    assert csmall.intersection(csmall) == csmall

    v = sqrt(2)
    t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0))
    points = intersection(t1, c1)
    assert len(points) == 4
    assert Point(0, 1) in points
    assert Point(0, -1) in points
    assert Point(v / 2, v / 2) in points
    assert Point(v / 2, -v / 2) in points

    circ = Circle(Point(0, 0), 5)
    elip = Ellipse(Point(0, 0), 5, 20)
    assert intersection(circ, elip) in \
        [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]]
    assert elip.tangent_lines(Point(0, 0)) == []
    elip = Ellipse(Point(0, 0), 3, 2)
    assert elip.tangent_lines(Point(3, 0)) == \
        [Line(Point(3, 0), Point(3, -12))]

    e1 = Ellipse(Point(0, 0), 5, 10)
    e2 = Ellipse(Point(2, 1), 4, 8)
    a = 53 / 17
    c = 2 * sqrt(3991) / 17
    ans = [Point(a - c / 8, a / 2 + c), Point(a + c / 8, a / 2 - c)]
    assert e1.intersection(e2) == ans
    e2 = Ellipse(Point(x, y), 4, 8)
    c = sqrt(3991)
    ans = [
        Point(-c / 68 + a, 2 * c / 17 + a / 2),
        Point(c / 68 + a, -2 * c / 17 + a / 2)
    ]
    assert [p.subs({x: 2, y: 1}) for p in e1.intersection(e2)] == ans

    # Combinations of above
    assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0])

    e = Ellipse((1, 2), 3, 2)
    assert e.tangent_lines(Point(10, 0)) == \
        [Line(Point(10, 0), Point(1, 0)),
        Line(Point(10, 0), Point(14/5, 18/5))]

    # encloses_point
    e = Ellipse((0, 0), 1, 2)
    assert e.encloses_point(e.center)
    assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
    assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
    assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
    assert e.encloses_point(e.center +
                            Point(e.hradius + Rational(1, 10), 0)) is False
    e = Ellipse((0, 0), 2, 1)
    assert e.encloses_point(e.center)
    assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
    assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
    assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
    assert e.encloses_point(e.center +
                            Point(e.hradius + Rational(1, 10), 0)) is False
    assert c1.encloses_point(Point(1, 0)) is False
    assert c1.encloses_point(Point(0.3, 0.4)) is True

    assert e.scale(2, 3) == Ellipse((0, 0), 4, 3)
    assert e.scale(3, 6) == Ellipse((0, 0), 6, 6)
    assert e.rotate(pi) == e
    assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1)
    raises(NotImplementedError, lambda: e.rotate(pi / 3))

    # Circle rotation tests (Issue #11743)
    # Link - https://github.com/sympy/sympy/issues/11743
    cir = Circle(Point(1, 0), 1)
    assert cir.rotate(pi / 2) == Circle(Point(0, 1), 1)
    assert cir.rotate(pi / 3) == Circle(Point(1 / 2, sqrt(3) / 2), 1)
    assert cir.rotate(pi / 3, Point(1, 0)) == Circle(Point(1, 0), 1)
    assert cir.rotate(pi / 3, Point(0, 1)) == Circle(
        Point(1 / 2 + sqrt(3) / 2, 1 / 2 + sqrt(3) / 2), 1)
Exemple #20
0
    def _eval_expand_commutator(self, **hints):
        A = self.args[0]
        B = self.args[1]

        if isinstance(A, Add):
            # [A + B, C]  ->  [A, C] + [B, C]
            sargs = []
            for term in A.args:
                comm = Commutator(term, B)
                if isinstance(comm, Commutator):
                    comm = comm._eval_expand_commutator()
                sargs.append(comm)
            return Add(*sargs)
        elif isinstance(B, Add):
            # [A, B + C]  ->  [A, B] + [A, C]
            sargs = []
            for term in B.args:
                comm = Commutator(A, term)
                if isinstance(comm, Commutator):
                    comm = comm._eval_expand_commutator()
                sargs.append(comm)
            return Add(*sargs)
        elif isinstance(A, Mul):
            # [A*B, C] -> A*[B, C] + [A, C]*B
            a = A.args[0]
            b = Mul(*A.args[1:])
            c = B
            comm1 = Commutator(b, c)
            comm2 = Commutator(a, c)
            if isinstance(comm1, Commutator):
                comm1 = comm1._eval_expand_commutator()
            if isinstance(comm2, Commutator):
                comm2 = comm2._eval_expand_commutator()
            first = Mul(a, comm1)
            second = Mul(comm2, b)
            return Add(first, second)
        elif isinstance(B, Mul):
            # [A, B*C] -> [A, B]*C + B*[A, C]
            a = A
            b = B.args[0]
            c = Mul(*B.args[1:])
            comm1 = Commutator(a, b)
            comm2 = Commutator(a, c)
            if isinstance(comm1, Commutator):
                comm1 = comm1._eval_expand_commutator()
            if isinstance(comm2, Commutator):
                comm2 = comm2._eval_expand_commutator()
            first = Mul(comm1, c)
            second = Mul(b, comm2)
            return Add(first, second)
        elif isinstance(A, Integral):
            # [∫adx, B] ->  ∫[a, B]dx
            func, lims = A.function, A.limits
            new_args = [Commutator(func, B)]
            for lim in lims:
                new_args.append(lim)
            return Integral(*new_args)
        elif isinstance(B, Integral):
            # [A, ∫bdx] ->  ∫[A, b]dx
            func, lims = B.function, B.limits
            new_args = [Commutator(A, func)]
            for lim in lims:
                new_args.append(lim)
            return Integral(*new_args)
        # No changes, so return self
        return self
Exemple #21
0
def test_integral():
    f = Lambda(x, exp(-x**2))
    l = lambdify(y, Integral(f(x), (x, y, oo)))
    d = l(-oo)
    assert 1.77245385 < d < 1.772453851
Exemple #22
0
# Some of the pretty forms shown denote how the expressions just
# above them should look with pretty printing.
N = CoordSys3D('N')
C = N.orient_new_axis('C', a, N.k)  # type: ignore
v = []
d = []
v.append(Vector.zero)
v.append(N.i)  # type: ignore
v.append(-N.i)  # type: ignore
v.append(N.i + N.j)  # type: ignore
v.append(a * N.i)  # type: ignore
v.append(a * N.i - b * N.j)  # type: ignore
v.append((a**2 + N.x) * N.i + N.k)  # type: ignore
v.append((a**2 + b) * N.i + 3 * (C.y - c) * N.k)  # type: ignore
f = Function('f')
v.append(N.j - (Integral(f(b)) - C.x**2) * N.k)  # type: ignore
upretty_v_8 = """\
      ⎛   2   ⌠        ⎞    \n\
j_N + ⎜x_C  - ⎮ f(b) db⎟ k_N\n\
      ⎝       ⌡        ⎠    \
"""
pretty_v_8 = """\
j_N + /         /       \\\n\
      |   2    |        |\n\
      |x_C  -  | f(b) db|\n\
      |        |        |\n\
      \\       /         / \
"""

v.append(N.i + C.k)  # type: ignore
v.append(express(N.i, C))  # type: ignore
Exemple #23
0
def test_sym_integral():
    f = Lambda(x, exp(-x**2))
    l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
    assert l(y) == Integral(exp(-y**2), (y, -oo, oo))
    assert l(y).doit() == sqrt(pi)
Exemple #24
0
def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
    r"""
    Solves a first order linear partial differential equation
    with constant coefficients.

    The general form of this partial differential equation is

    .. math:: a \frac{\partial f(x,y)}{\partial x}
              + b \frac{\partial f(x,y)}{\partial y}
              + c f(x,y) = G(x,y)

    where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
    function in `x` and `y`.

    The general solution of the PDE is:

    .. math::
        f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2}
        \int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2},
        \frac{- a \eta + b \xi}{a^2 + b^2} \right)
        e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right]
        e^{- \frac{c \xi}{a^2 + b^2}}
        \right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, ,

    where `F(\eta)` is an arbitrary single-valued function. The solution
    can be found in SymPy with ``pdsolve``::

        >>> from sympy.solvers import pdsolve
        >>> from sympy.abc import x, y, a, b, c
        >>> from sympy import Function, pprint
        >>> f = Function('f')
        >>> G = Function('G')
        >>> u = f(x,y)
        >>> ux = u.diff(x)
        >>> uy = u.diff(y)
        >>> genform = a*ux + b*uy + c*u - G(x,y)
        >>> pprint(genform)
          d               d
        a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y)
          dx              dy
        >>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
                  //          a*x + b*y                                             \
                  ||              /                                                 |
                  ||             |                                                  |
                  ||             |                                       c*xi       |
                  ||             |                                     -------      |
                  ||             |                                      2    2      |
                  ||             |      /a*xi + b*eta  -a*eta + b*xi\  a  + b       |
                  ||             |     G|------------, -------------|*e        d(xi)|
                  ||             |      |   2    2         2    2   |               |
                  ||             |      \  a  + b         a  + b    /               |
                  ||             |                                                  |
                  ||            /                                                   |
                  ||                                                                |
        f(x, y) = ||F(eta) + -------------------------------------------------------|*
                  ||                                  2    2                        |
                  \\                                 a  + b                         /
        <BLANKLINE>
                \|
                ||
                ||
                ||
                ||
                ||
                ||
                ||
                ||
          -c*xi ||
         -------||
          2    2||
         a  + b ||
        e       ||
                ||
                /|eta=-a*y + b*x, xi=a*x + b*y


    Examples
    ========

    >>> from sympy.solvers.pde import pdsolve
    >>> from sympy import Function, diff, pprint, exp
    >>> from sympy.abc import x,y
    >>> f = Function('f')
    >>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
    >>> pdsolve(eq)
    Eq(f(x, y), (F(4*x + 2*y) + exp(x/2 + 4*y)/15)*exp(x/2 - y))

    References
    ==========

    - Viktor Grigoryan, "Partial Differential Equations"
      Math 124A - Fall 2010, pp.7

    """

    # TODO : For now homogeneous first order linear PDE's having
    # two variables are implemented. Once there is support for
    # solving systems of ODE's, this can be extended to n variables.
    xi, eta = symbols("xi eta")
    f = func.func
    x = func.args[0]
    y = func.args[1]
    b = match[match['b']]
    c = match[match['c']]
    d = match[match['d']]
    e = -match[match['e']]
    expterm = exp(-S(d)/(b**2 + c**2)*xi)
    functerm = solvefun(eta)
    solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y)
    # Integral should remain as it is in terms of xi,
    # doit() should be done in _handle_Integral.
    genterm = (1/S(b**2 + c**2))*Integral(
        (1/expterm*e).subs(solvedict), (xi, b*x + c*y))
    return Eq(f(x,y), Subs(expterm*(functerm + genterm),
        (eta, xi), (c*x - b*y, b*x + c*y)))
Exemple #25
0
def test_issue_6408_integral():
    x, y = symbols('x y')
    assert nsolve(Integral(x * y, (x, 0, 5)), y, 2) == 0.0
Exemple #26
0
def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
    r"""
    Solves a first order linear partial differential equation
    with constant coefficients.

    The general form of this partial differential equation is

    .. math:: a \frac{df(x,y)}{dx} + b \frac{df(x,y)}{dy} + c f(x,y) = G(x,y)

    where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
    function in `x` and `y`.

    The general solution of the PDE is::

        >>> from sympy.solvers import pdsolve
        >>> from sympy.abc import x, y, a, b, c
        >>> from sympy import Function, pprint
        >>> f = Function('f')
        >>> G = Function('G')
        >>> u = f(x,y)
        >>> ux = u.diff(x)
        >>> uy = u.diff(y)
        >>> genform = a*u + b*ux + c*uy - G(x,y)
        >>> pprint(genform)
                  d               d
        a*f(x, y) + b*--(f(x, y)) + c*--(f(x, y)) - G(x, y)
                  dx              dy
        >>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
                  //          b*x + c*y                                             \
                  ||              /                                                 |
                  ||             |                                                  |
                  ||             |                                       a*xi       |
                  ||             |                                     -------      |
                  ||             |                                      2    2      |
                  ||             |      /b*xi + c*eta  -b*eta + c*xi\  b  + c       |
                  ||             |     G|------------, -------------|*e        d(xi)|
                  ||             |      |   2    2         2    2   |               |
                  ||             |      \  b  + c         b  + c    /               |
                  ||             |                                                  |
                  ||            /                                                   |
                  ||                                                                |
        f(x, y) = ||F(eta) + -------------------------------------------------------|*
                  ||                                  2    2                        |
                  \\                                 b  + c                         /
        <BLANKLINE>
                \|
                ||
                ||
                ||
                ||
                ||
                ||
                ||
                ||
          -a*xi ||
         -------||
          2    2||
         b  + c ||
        e       ||
                ||
                /|eta=-b*y + c*x, xi=b*x + c*y


    Examples
    ========

    >>> from sympy.solvers.pde import pdsolve
    >>> from sympy import Function, diff, pprint, exp
    >>> from sympy.abc import x,y
    >>> f = Function('f')
    >>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
    >>> pdsolve(eq)
    Eq(f(x, y), (F(4*x + 2*y) + exp(x/2 + 4*y)/15)*exp(x/2 - y))

    References
    ==========

    - Viktor Grigoryan, "Partial Differential Equations"
      Math 124A - Fall 2010, pp.7

    """

    # TODO : For now homogeneous first order linear PDE's having
    # two variables are implemented. Once there is support for
    # solving systems of ODE's, this can be extended to n variables.
    xi, eta = symbols("xi eta")
    f = func.func
    x = func.args[0]
    y = func.args[1]
    b = match[match['b']]
    c = match[match['c']]
    d = match[match['d']]
    e = -match[match['e']]
    expterm = exp(-S(d) / (b**2 + c**2) * xi)
    functerm = solvefun(eta)
    solvedict = solve((b * x + c * y - xi, c * x - b * y - eta), x, y)
    # Integral should remain as it is in terms of xi,
    # doit() should be done in _handle_Integral.
    genterm = (1 / S(b**2 + c**2)) * Integral(
        (1 / expterm * e).subs(solvedict), (xi, b * x + c * y))
    return Eq(
        f(x, y),
        Subs(expterm * (functerm + genterm), (eta, xi),
             (c * x - b * y, b * x + c * y)))
Exemple #27
0
 def _eval_rewrite_as_Integral(self, *args):
     from sympy.integrals.integrals import Integral
     t = Dummy('t')
     m = self.args[0]
     return Integral(1 / sqrt(1 - m * sin(t)**2), (t, 0, pi / 2))
Exemple #28
0
 (r"\infty", oo),
 (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)),
 (r"\frac{d}{dx} x", Derivative(x, x)),
 (r"\frac{d}{dt} x", Derivative(x, t)),
 (r"f(x)", f(x)),
 (r"f(x, y)", f(x, y)),
 (r"f(x, y, z)", f(x, y, z)),
 (r"\frac{d f(x)}{dx}", Derivative(f(x), x)),
 (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
 (r"x \neq y", Unequality(x, y)),
 (r"|x|", _Abs(x)),
 (r"||x||", _Abs(Abs(x))),
 (r"|x||y|", _Abs(x) * _Abs(y)),
 (r"||x||y||", _Abs(_Abs(x) * _Abs(y))),
 (r"\pi^{|xy|}", Symbol('pi')**_Abs(x * y)),
 (r"\int x dx", Integral(x, x)),
 (r"\int x d\theta", Integral(x, theta)),
 (r"\int (x^2 - y)dx", Integral(x**2 - y, x)),
 (r"\int x + a dx", Integral(_Add(x, a), x)),
 (r"\int da", Integral(1, a)),
 (r"\int_0^7 dx", Integral(1, (x, 0, 7))),
 (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))),
 (r"\int_a^b x dx", Integral(x, (x, a, b))),
 (r"\int^b_a x dx", Integral(x, (x, a, b))),
 (r"\int_{a}^b x dx", Integral(x, (x, a, b))),
 (r"\int^{b}_a x dx", Integral(x, (x, a, b))),
 (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))),
 (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))),
 (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
 (r"\int (x+a)", Integral(_Add(x, a), x)),
 (r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
Exemple #29
0
def test_integrals():
    x = Symbol("x")
    for c in (Integral, Integral(x)):
        check(c)
Exemple #30
0
def test_issue_15716():
    e = Integral(factorial(x), (x, -oo, oo))
    assert e.as_terms() == ([(e, ((1.0, 0.0), (1, ), ()))], [e])
Exemple #31
0
def test_Integral():
    assert str(Integral(sin(x), y)) == "Integral(sin(x), y)"
    assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))"
Exemple #32
0
def test_dsolve_options():
    eq = x*f(x).diff(x) + f(x)
    a = dsolve(eq, hint='all')
    b = dsolve(eq, hint='all', simplify=False)
    c = dsolve(eq, hint='all_Integral')
    keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
        '1st_homogeneous_coeff_subs_dep_div_indep',
        '1st_homogeneous_coeff_subs_dep_div_indep_Integral',
        '1st_homogeneous_coeff_subs_indep_div_dep',
        '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
        '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral',
        'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
        'default', 'factorable', 'lie_group',
        'nth_linear_euler_eq_homogeneous', 'order',
        'separable', 'separable_Integral']
    Integral_keys = ['1st_exact_Integral',
        '1st_homogeneous_coeff_subs_dep_div_indep_Integral',
        '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral',
        'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default',
        'factorable', 'nth_linear_euler_eq_homogeneous',
        'order', 'separable_Integral']
    assert sorted(a.keys()) == keys
    assert a['order'] == ode_order(eq, f(x))
    assert a['best'] == Eq(f(x), C1/x)
    assert dsolve(eq, hint='best') == Eq(f(x), C1/x)
    assert a['default'] == 'factorable'
    assert a['best_hint'] == 'factorable'
    assert not a['1st_exact'].has(Integral)
    assert not a['separable'].has(Integral)
    assert not a['1st_homogeneous_coeff_best'].has(Integral)
    assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
    assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
    assert not a['1st_linear'].has(Integral)
    assert a['1st_linear_Integral'].has(Integral)
    assert a['1st_exact_Integral'].has(Integral)
    assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
    assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
    assert a['separable_Integral'].has(Integral)
    assert sorted(b.keys()) == keys
    assert b['order'] == ode_order(eq, f(x))
    assert b['best'] == Eq(f(x), C1/x)
    assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x)
    assert b['default'] == 'factorable'
    assert b['best_hint'] == 'factorable'
    assert a['separable'] != b['separable']
    assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
        b['1st_homogeneous_coeff_subs_dep_div_indep']
    assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
        b['1st_homogeneous_coeff_subs_indep_div_dep']
    assert not b['1st_exact'].has(Integral)
    assert not b['separable'].has(Integral)
    assert not b['1st_homogeneous_coeff_best'].has(Integral)
    assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
    assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
    assert not b['1st_linear'].has(Integral)
    assert b['1st_linear_Integral'].has(Integral)
    assert b['1st_exact_Integral'].has(Integral)
    assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
    assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
    assert b['separable_Integral'].has(Integral)
    assert sorted(c.keys()) == Integral_keys
    raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
    raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
    assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
        dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
    assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
                  hint="1st_linear_Integral") == \
        Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
                exp(Integral(1, x)), x))*exp(-Integral(1, x)))