当前位置: 首页>>代码示例>>Python>>正文


Python Basic.sympify方法代码示例

本文整理汇总了Python中sympy.core.Basic.sympify方法的典型用法代码示例。如果您正苦于以下问题:Python Basic.sympify方法的具体用法?Python Basic.sympify怎么用?Python Basic.sympify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sympy.core.Basic的用法示例。


在下文中一共展示了Basic.sympify方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _eval_apply

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
    def _eval_apply(cls, arg):
        arg = Basic.sympify(arg)

        if isinstance(arg, Basic.Number):
            if isinstance(arg, Basic.NaN):
                return S.NaN
            elif isinstance(arg, Basic.Infinity):
                return S.Infinity
            elif isinstance(arg, Basic.Integer):
                if arg.is_positive:
                    return Basic.Factorial(arg-1)
                else:
                    return S.ComplexInfinity
            elif isinstance(arg, Basic.Rational):
                if arg.q == 2:
                    n = abs(arg.p) / arg.q

                    if arg.is_positive:
                        k, coeff = n, S.One
                    else:
                        n = k = n + 1

                        if n & 1 == 0:
                            coeff = S.One
                        else:
                            coeff = S.NegativeOne

                    for i in range(3, 2*k, 2):
                        coeff *= i

                    if arg.is_positive:
                        return coeff*Basic.sqrt(S.Pi) / 2**n
                    else:
                        return 2**n*Basic.sqrt(S.Pi) / coeff
开发者ID:certik,项目名称:sympy-oldcore,代码行数:36,代码来源:gamma_functions.py

示例2: __new__

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
    def __new__(cls, f, z, **assumptions):
        f = Basic.sympify(f)

        if not f.is_polynomial(z):
            return f

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (f.as_polynomial(z), z)

        return obj
开发者ID:certik,项目名称:sympy-oldcore,代码行数:12,代码来源:rewrite.py

示例3: separate

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def separate(expr, deep=False):
    """Rewrite or separate a power of product to a product of powers
       but without any expanding, ie. rewriting products to summations.

       >>> from sympy import *
       >>> x, y, z = symbols('x', 'y', 'z')

       >>> separate((x*y)**2)
       x**2*y**2

       >>> separate((x*(y*z)**3)**2)
       x**2*y**6*z**6

       >>> separate((x*sin(x))**y + (x*cos(x))**y)
       x**y*cos(x)**y + x**y*sin(x)**y

       #>>> separate((exp(x)*exp(y))**x)
       #exp(x*y)*exp(x**2)

       Notice that summations are left un touched. If this is not the
       requested behaviour, apply 'expand' to input expression before:

       >>> separate(((x+y)*z)**2)
       z**2*(x + y)**2

       >>> separate((x*y)**(1+z))
       x**(1 + z)*y**(1 + z)

    """
    expr = Basic.sympify(expr)

    if isinstance(expr, Basic.Pow):
        terms, expo = [], separate(expr.exp, deep)
        #print expr, terms, expo, expr.base

        if isinstance(expr.base, Mul):
            t = [ separate(Basic.Pow(t,expo), deep) for t in expr.base ]
            return Basic.Mul(*t)
        elif isinstance(expr.base, Basic.exp):
            if deep == True:
                return Basic.exp(separate(expr.base[0], deep)*expo)
            else:
                return Basic.exp(expr.base[0]*expo)
        else:
            return Basic.Pow(separate(expr.base, deep), expo)
    elif isinstance(expr, (Basic.Add, Basic.Mul)):
        return type(expr)(*[ separate(t, deep) for t in expr ])
    elif isinstance(expr, Basic.Function) and deep:
        return expr.func(*[ separate(t) for t in expr])
    else:
        return expr
开发者ID:certik,项目名称:sympy-oldcore,代码行数:53,代码来源:simplify.py

示例4: __new__

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
    def __new__(cls, f, *symbols, **assumptions):
        f = Basic.sympify(f)

        if isinstance(f, Basic.Number):
            if isinstance(f, Basic.NaN):
                return S.NaN
            elif isinstance(f, Basic.Zero):
                return S.Zero

        if not symbols:
            limits = f.atoms(Symbol)

            if not limits:
                return f
        else:
            limits = []

            for V in symbols:
                if isinstance(V, Symbol):
                    limits.append(V)
                    continue
                elif isinstance(V, Equality):
                    if isinstance(V.lhs, Symbol):
                        if isinstance(V.rhs, Interval):
                            limits.append((V.lhs, V.rhs.start, V.rhs.end))
                        else:
                            limits.append((V.lhs, V.rhs))

                        continue
                elif isinstance(V, (tuple, list)):
                    if len(V) == 1:
                        if isinstance(V[0], Symbol):
                            limits.append(V[0])
                            continue
                    elif len(V) in (2, 3):
                        if isinstance(V[0], Symbol):
                            limits.append(tuple(V))
                            continue

                raise ValueError("Invalid summation variable or limits")

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (f, tuple(limits))

        return obj
开发者ID:certik,项目名称:sympy-oldcore,代码行数:47,代码来源:summations.py

示例5: __new__

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
    def __new__(cls, function, *symbols, **assumptions):
        function = Basic.sympify(function)

        if isinstance(function, Basic.Number):
            if isinstance(function, Basic.NaN):
                return S.NaN
            elif isinstance(function, Basic.Infinity):
                return S.Infinity
            elif isinstance(function, Basic.NegativeInfinity):
                return S.NegativeInfinity

        if symbols:
            limits = []

            for V in symbols:
                if isinstance(V, Symbol):
                    limits.append((V,None))
                    continue
                elif isinstance(V, (tuple, list)):
                    if len(V) == 3:
                        limits.append( (V[0],tuple(V[1:])) )
                        continue
                    elif len(V) == 1:
                        if isinstance(V[0], Symbol):
                            limits.append((V[0],None))
                            continue

                raise ValueError("Invalid integration variable or limits")
        else:
            limits = func.atoms(Symbol)

            if not limits:
                return function

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (function, tuple(limits))

        return obj
开发者ID:certik,项目名称:sympy-oldcore,代码行数:40,代码来源:integrals.py

示例6: __new__

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
    def __new__(cls, term, *symbols, **assumptions):
        term = Basic.sympify(term)

        if isinstance(term, Basic.Number):
            if isinstance(term, Basic.NaN):
                return S.NaN
            elif isinstance(term, Basic.Infinity):
                return S.NaN
            elif isinstance(term, Basic.NegativeInfinity):
                return S.NaN
            elif isinstance(term, Basic.Zero):
                return S.Zero
            elif isinstance(term, Basic.One):
                return S.One

        if len(symbols) == 1:
            symbol = symbols[0]

            if isinstance(symbol, Basic.Equality):
                k = symbol.lhs
                a = symbol.rhs.start
                n = symbol.rhs.end
            elif isinstance(symbol, (tuple, list)):
                k, a, n = symbol
            else:
                raise ValueError("Invalid arguments")

            k, a, n = map(Basic.sympify, (k, a, n))

            if isinstance(a, Basic.Number) and isinstance(n, Basic.Number):
                return Mul(*[term.subs(k, i) for i in xrange(int(a), int(n) + 1)])
        else:
            raise NotImplementedError

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (term, k, a, n)

        return obj
开发者ID:certik,项目名称:sympy-oldcore,代码行数:40,代码来源:products.py

示例7: hypersimp

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def hypersimp(term, n, consecutive=True, simplify=True):
    """Given combinatorial term a(n) simplify its consecutive term
       ratio ie. a(n+1)/a(n). The term can be composed of functions
       and integer sequences which have equivalent represenation
       in terms of gamma special function. Currently ths includes
       factorials (falling, rising), binomials and gamma it self.

       The algorithm performs three basic steps:

           (1) Rewrite all functions in terms of gamma, if possible.

           (2) Rewrite all occurences of gamma in terms of produtcs
               of gamma and rising factorial with integer, absolute
               constant exponent.

           (3) Perform simplification of nested fractions, powers
               and if the resulting expression is a quotient of
               polynomials, reduce their total degree.

       If the term given is hypergeometric then the result of this
       procudure is a quotient of polynomials of minimal degree.
       Sequence is hypergeometric if it is anihilated by linear,
       homogeneous recurrence operator of first order, so in
       other words when a(n+1)/a(n) is a rational function.

       When the status of being hypergeometric or not, is required
       then you can avoid additional simplification by unsetting
       'simplify' flag.

       This algorithm, due to Wolfram Koepf, is very simple but
       powerful, however its full potential will be visible when
       simplification in general will improve.

       For more information on the implemented algorithm refer to:

       [1] W. Koepf, Algorithms for m-fold Hypergeometric Summation,
           Journal of Symbolic Computation (1995) 20, 399-417
    """
    term = Basic.sympify(term)

    if consecutive == True:
        term = term.subs(n, n+1)/term

    expr = term.rewrite(gamma).expand(func=True, basic=False)

    p, q = together(expr).as_numer_denom()

    if p.is_polynomial(n) and q.is_polynomial(n):
        if simplify == True:
            from sympy.polynomials import gcd, quo

            G = gcd(p, q, n)

            if not isinstance(G, Basic.One):
                p = quo(p, G, n)
                q = quo(q, G, n)

                p = p.as_polynomial(n)
                q = q.as_polynomial(n)

                a, p = p.as_integer()
                b, q = q.as_integer()

                p = p.as_basic()
                q = q.as_basic()

                return (b/a) * (p/q)

        return p/q
    else:
        return None
开发者ID:certik,项目名称:sympy-oldcore,代码行数:73,代码来源:simplify.py

示例8: fraction

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def fraction(expr, exact=False):
    """Returns a pair with expression's numerator and denominator.
       If the given expression is not a fraction then this function
       will assume that the denominator is equal to one.

       This function will not make any attempt to simplify nested
       fractions or to do any term rewriting at all.

       If only one of the numerator/denominator pair is needed then
       use numer(expr) or denom(expr) functions respectively.

       >>> from sympy import *
       >>> x, y = symbols('x', 'y')

       >>> fraction(x/y)
       (x, y)
       >>> fraction(x)
       (x, 1)

       >>> fraction(1/y**2)
       (1, y**2)

       >>> fraction(x*y/2)
       (x*y, 2)
       >>> fraction(Rational(1, 2))
       (1, 2)

       This function will also work fine with assumptions:

       >>> k = Symbol('k', negative=True)
       >>> fraction(x * y**k)
       (x, y**(-k))

       If we know nothing about sign of some exponent and 'exact'
       flag is unset, then structure this exponent's structure will
       be analyzed and pretty fraction will be returned:

       >>> fraction(2*x**(-y))
       (2, x**y)

       #>>> fraction(exp(-x))
       #(1, exp(x))

       >>> fraction(exp(-x), exact=True)
       (exp(-x), 1)

    """
    expr = Basic.sympify(expr)

    #XXX this only works sometimes (caching bug?)
    if expr == exp(-Symbol("x")) and exact:
        return (expr, 1)

    numer, denom = [], []

    for term in make_list(expr, Mul):
        if isinstance(term, Pow):
            if term.exp.is_negative:
                if term.exp == Integer(-1):
                    denom.append(term.base)
                else:
                    denom.append(Pow(term.base, -term.exp))
            elif not exact and isinstance(term.exp, Mul):
                coeff, tail = term.exp[0], Mul(*term.exp[1:])#term.exp.getab()

                if isinstance(coeff, Rational) and coeff.is_negative:
                    denom.append(Pow(term.base, -term.exp))
                else:
                    numer.append(term)
            else:
                numer.append(term)
        elif isinstance(term, Basic.exp):
            if term[0].is_negative:
                denom.append(Basic.exp(-term[0]))
            elif not exact and isinstance(term[0], Mul):
                coeff, tail = term[0], Mul(*term[1:])#term.args.getab()

                if isinstance(coeff, Rational) and coeff.is_negative:
                    denom.append(Basic.exp(-term[0]))
                else:
                    numer.append(term)
            else:
                numer.append(term)
        elif isinstance(term, Rational):
            if term.is_integer:
                numer.append(term)
            else:
                numer.append(Rational(term.p))
                denom.append(Rational(term.q))
        else:
            numer.append(term)

    return Mul(*numer), Mul(*denom)
开发者ID:certik,项目名称:sympy-oldcore,代码行数:95,代码来源:simplify.py

示例9: collect

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]

#.........这里部分代码省略.........
            pattern = [ parse_term(elem) for elem in pattern ]

            elems, common_expo, has_deriv = [], Rational(1), False

            for elem, e_rat, e_sym, e_ord in pattern:
                if e_ord is not None:
                    # there is derivative in the pattern so
                    # there will by small performance penalty
                    has_deriv = True

                for j in range(len(terms)):
                    term, t_rat, t_sym, t_ord = terms[j]

                    if elem == term and e_sym == t_sym:
                        if exact == False:
                            # we don't have to exact so find common exponent
                            # for both expression's term and pattern's element
                            expo = t_rat / e_rat

                            if isinstance(common_expo, Basic.One):
                                common_expo = expo
                            else:
                                # common exponent was negotiated before so
                                # teher is no chance for pattern match unless
                                # common and current exponents are equal
                                if common_expo != expo:
                                    return None
                        else:
                            # we ought to be exact so all fields of
                            # interest must match in very details
                            if e_rat != t_rat or e_ord != t_ord:
                                continue

                        # found common term so remove it from the expression
                        # and try to match next element in the pattern
                        elems.append(terms[j])
                        del terms[j]

                        break
                else:
                    # pattern element not found
                    return None

            return terms, elems, common_expo, has_deriv

    if evaluate:
        if isinstance(expr, Basic.Mul):
            ret = 1
            for term in expr:
                ret *= collect(term, syms, True, exact)
            return ret
        elif isinstance(expr, Basic.Pow):
            b = collect(expr.base, syms, True, exact)
            return Basic.Pow(b, expr.exp)

    summa = [ separate(i) for i in make_list(Basic.sympify(expr), Add) ]

    if isinstance(syms, list):
        syms = [ separate(s) for s in syms ]
    else:
        syms = [ separate(syms) ]

    collected, disliked = {}, Rational(0)

    for product in summa:
        terms = [ parse_term(i) for i in make_list(product, Mul) ]

        for symbol in syms:
            result = parse_expression(terms, symbol)

            if result is not None:
                terms, elems, common_expo, has_deriv = result

                # when there was derivative in current pattern we
                # will need to rebuild its expression from scratch
                if not has_deriv:
                    index = Pow(symbol, common_expo)
                else:
                    index = make_expression(elems)

                terms = separate(make_expression(terms))
                index = separate(index)

                if index in collected:
                    collected[index] += terms
                else:
                    collected[index] = terms

                break
        else:
            # none of the patterns matched
            disliked += product

    if disliked != Rational(0):
        collected[Rational(1)] = disliked

    if evaluate:
        return Add(*[ a*b for a, b in collected.iteritems() ])
    else:
        return collected
开发者ID:certik,项目名称:sympy-oldcore,代码行数:104,代码来源:simplify.py

示例10: risch_norman

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def risch_norman(f, x, rewrite=False):
    """Computes indefinite integral using extended Risch-Norman algorithm,
       also known as parallel Risch. This is a simplified version of full
       recursive Risch algorithm. It is designed for integrating various
       classes of functions including transcendental elementary or special
       functions like Airy, Bessel, Whittaker and Lambert.

       The main difference between this algorithm and the recursive one
       is that rather than computing a tower of differential extensions
       in a recursive way, it handles all cases in one shot. That's why
       it is called parallel Risch algorithm. This makes it much faster
       than the original approach.

       Another benefit is that it doesn't require to rewrite expressions
       in terms of complex exponentials. Rather it uses tangents and so
       antiderivatives are being found in a more familliar form.

       Risch-Norman algorithm can also handle special functions very
       easily without any additional effort. Just differentiation
       method must be known for a given function.

       Note that this algorithm is not a decision procedure. If it
       computes an antiderivative for a given integral then it's a
       proof that such function exists. However when it fails then
       there still may exist an antiderivative and a fallback to
       recurrsive Risch algorithm would be necessary.

       The question if this algorithm can be made a full featured
       decision procedure still remains open.

       For more information on the implemented algorithm refer to:

       [1] K. Geddes, L.Stefanus, On the Risch-Norman Integration
           Method and its Implementation in Maple, Proceedings of
           ISSAC'89, ACM Press, 212-217.

       [2] J. H. Davenport, On the Parallel Risch Algorithm (I),
           Proceedings of EUROCAM'82, LNCS 144, Springer, 144-157.

       [3] J. H. Davenport, On the Parallel Risch Algorithm (III):
           Use of Tangents, SIGSAM Bulletin 16 (1982), 3-6.

       [4] J. H. Davenport, B. M. Trager, On the Parallel Risch
           Algorithm (II), ACM Transactions on Mathematical
           Software 11 (1985), 356-362.

    """
    f = Basic.sympify(f)

    if not f.has(x):
        return f * x

    rewritables = {
        (sin, cos, cot)     : tan,
        (sinh, cosh, coth)  : tanh,
    }

    if rewrite:
        for candidates, rule in rewritables.iteritems():
            f = f.rewrite(candidates, rule)
    else:
        for candidates in rewritables.iterkeys():
            if f.has(*candidates):
                break
        else:
            rewrite = True

    terms = components(f)

    for g in set(terms):
        h = g.diff(x)

        if not isinstance(h, Basic.Zero):
            terms |= components(h)

    terms = [ g for g in terms if g.has(x) ]

    V, in_terms, out_terms = [], [], {}

    for i, term in enumerate(terms):
        V += [ Symbol('x%s' % i) ]

        N = term.count_ops(symbolic=False)
        in_terms += [ (N, term, V[-1]) ]

        out_terms[V[-1]] = term

    in_terms.sort(lambda u, v: int(v[0] - u[0]))

    def substitute(expr):
        for _, g, symbol in in_terms:
            expr = expr.subs(g, symbol)

        return expr

    diffs = [ substitute(g.diff(x)) for g in terms ]

    denoms = [ g.as_numer_denom()[1] for g in diffs ]
    denom = reduce(lambda p, q: lcm(p, q, V), denoms)

#.........这里部分代码省略.........
开发者ID:certik,项目名称:sympy-oldcore,代码行数:103,代码来源:risch.py

示例11: indexsymbol

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def indexsymbol(a):
    if isinstance(a, Symbol):
        return Symbol(a.name, integer=True)
    else:
        return Basic.sympify(a)
开发者ID:certik,项目名称:sympy-oldcore,代码行数:7,代码来源:sums_products.py

示例12: apart

# 需要导入模块: from sympy.core import Basic [as 别名]
# 或者: from sympy.core.Basic import sympify [as 别名]
def apart(f, z, domain=None, index=None):
    """Computes full partial fraction decomposition of a univariate
       rational function over the algebraic closure of its field of
       definition. Although only gcd operations over the initial
       field are required, the expansion is returned in a formal
       form with linear denominators.

       However it is possible to force expansion of the resulting
       formal summations, and so factorization over a specified
       domain is performed.

       To specify the desired behavior of the algorithm use the
       'domain' keyword. Setting it to None, which is done be
       default, will result in no factorization at all.

       Otherwise it can be assigned with one of Z, Q, R, C domain
       specifiers and the formal partial fraction expansion will
       be rewritten using all possible roots over this domain.

       If the resulting expansion contains formal summations, then
       for all those a single dummy index variable named 'a' will
       be generated. To change this default behavior issue new
       name via 'index' keyword.

       For more information on the implemented algorithm refer to:

       [1] M. Bronstein, B. Salvy, Full partial fraction decomposition
           of rational functions, in: M. Bronstein, ed., Proceedings
           ISSAC '93, ACM Press, Kiev, Ukraine, 1993, pp. 157-160.

    """
    f = Basic.sympify(f)

    if isinstance(f, Basic.Add):
        return Add(*[ apart(g) for g in f ])
    else:
        if f.is_fraction(z):
            f = normal(f, z)
        else:
            return f

        P, Q = f.as_numer_denom()

        if not Q.has(z):
            return f

        u = Function('u')(z)

        if index is None:
            A = Symbol('a', dummy=True)
        else:
            A = Symbol(index)

        partial, r = div(P, Q, z)
        f, q, U = r / Q, Q, []

        for k, d in enumerate(sqf(q, z)):
            n, d = k + 1, d.as_basic()
            U += [ u.diff(z, k) ]

            h = normal(f * d**n, z) / u**n

            H, subs = [h], []

            for j in range(1, n):
                H += [ H[-1].diff(z) / j ]

            for j in range(1, n+1):
                subs += [ (U[j-1], d.diff(z, j) / j) ]

            for j in range(0, n):
                P, Q = together(H[j]).as_numer_denom()

                for i in range(0, j+1):
                    P = P.subs(*subs[j-i])

                Q = Q.subs(*subs[0])

                G = gcd(P, d, z)
                D = quo(d, G, z)

                g, B, _ = ext_gcd(Q, D, z)
                b = rem(P * B / g, D, z)

                term = b.subs(z, A) / (z - A)**(n-j)

                if domain is None:
                    a = D.diff(z)

                    if not a.has(z):
                        partial += term.subs(A, -D.subs(z, 0) / a)
                    else:
                        partial += Basic.Sum(term, (A, Basic.RootOf(D, z)))
                else:
                    raise NotImplementedError

        return partial
开发者ID:certik,项目名称:sympy-oldcore,代码行数:99,代码来源:rewrite.py


注:本文中的sympy.core.Basic.sympify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。