• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utilities.any函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.utilities.any函数的典型用法代码示例。如果您正苦于以下问题:Python any函数的具体用法?Python any怎么用?Python any使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: _rootof_data

def _rootof_data(poly, indices):
    """Construct ``RootOf`` data from a polynomial and indices. """
    (_, factors) = poly.factor_list()

    reals = _rootof_get_reals(factors)
    real_count = sum([ k for _, _, k in reals ])

    if indices is None:
        reals = _rootof_reals_sorted(reals)

        for index in xrange(0, real_count):
            yield _rootof_reals_index(reals, index)
    else:
        if any(index < real_count for index in indices):
            reals = _rootof_reals_sorted(reals)

            for index in indices:
                if index < real_count:
                    yield _rootof_reals_index(reals, index)

        if any(index >= real_count for index in indices):
            complexes = _rootof_get_complexes(factors)
            complexes = _rootof_complexes_sorted(complexes)

            for index in indices:
                if index >= real_count:
                    yield _rootof_complexes_index(complexes, index-real_count)
开发者ID:haz,项目名称:sympy,代码行数:27,代码来源:rootoftools.py


示例2: update

    def update(G, CP, h):
        """update G using the set of critical pairs CP and h = (expv,pi)
        see [BW] page 230
        """
        hexpv, hp = f[h]
        # print 'DB10',hp
        # filter new pairs (h,g), g in G
        C = G.copy()
        D = set()

        while C:
            # select a pair (h,g) by popping an element from C
            g = C.pop()
            gexpv = f[g][0]
            LCMhg = lcm_expv(hexpv, gexpv)

            def lcm_divides(p):
                expv = lcm_expv(hexpv, f[p][0])
                # LCM(LM(h), LM(p)) divides LCM(LM(h),LM(g))
                return monomial_div(LCMhg, expv)

            # HT(h) and HT(g) disjoint: hexpv + gexpv == LCMhg
            if monomial_mul(hexpv, gexpv) == LCMhg or (
                not any(lcm_divides(f) for f in C) and not any(lcm_divides(pr[1]) for pr in D)
            ):
                D.add((h, g))

        E = set()
        while D:
            # select h,g from D
            h, g = D.pop()
            gexpv = f[g][0]
            LCMhg = lcm_expv(hexpv, gexpv)
            if not monomial_mul(hexpv, gexpv) == LCMhg:
                E.add((h, g))

        # filter old pairs
        B_new = set()

        while CP:
            # select g1,g2 from CP
            g1, g2 = CP.pop()
            g1expv = f[g1][0]
            g2expv = f[g2][0]
            LCM12 = lcm_expv(g1expv, g2expv)
            # if HT(h) does not divide lcm(HT(g1),HT(g2))
            if not monomial_div(LCM12, hexpv) or lcm_expv(g1expv, hexpv) == LCM12 or lcm_expv(g2expv, hexpv) == LCM12:
                B_new.add((g1, g2))

        B_new |= E

        # filter polynomials
        G_new = set()
        while G:
            g = G.pop()
            if not monomial_div(f[g][0], hexpv):
                G_new.add(g)
        G_new.add(h)

        return G_new, B_new
开发者ID:pernici,项目名称:sympy,代码行数:60,代码来源:lgroebner.py


示例3: is_univariate

    def is_univariate(f):
        """Returns True if 'f' is univariate in its last variable. """
        for monom in f.monoms():
            if any(m > 0 for m in monom[:-1]):
                return False

        return True
开发者ID:Aang,项目名称:sympy,代码行数:7,代码来源:polysys.py


示例4: solve_undetermined_coeffs

def solve_undetermined_coeffs(equ, coeffs, sym, **flags):
    """Solve equation of a type p(x; a_1, ..., a_k) == q(x) where both
       p, q are univariate polynomials and f depends on k parameters.
       The result of this functions is a dictionary with symbolic
       values of those parameters with respect to coefficiens in q.

       This functions accepts both Equations class instances and ordinary
       SymPy expressions. Specification of parameters and variable is
       obligatory for efficiency and simplicity reason.

       >>> from sympy import *
       >>> a, b, c, x = symbols('a', 'b', 'c', 'x')

       >>> solve_undetermined_coeffs(Eq(2*a*x + a+b, x), [a, b], x)
       {a: 1/2, b: -1/2}

       >>> solve_undetermined_coeffs(Eq(a*c*x + a+b, x), [a, b], x)
       {a: 1/c, b: -1/c}

    """
    if isinstance(equ, Equality):
        # got equation, so move all the
        # terms to the left hand side
        equ = equ.lhs - equ.rhs

    system = collect(equ.expand(), sym, evaluate=False).values()

    if not any([ equ.has(sym) for equ in system ]):
        # consecutive powers in the input expressions have
        # been successfully collected, so solve remaining
        # system using Gaussian ellimination algorithm
        return solve(system, *coeffs, **flags)
    else:
        return None # no solutions
开发者ID:cran,项目名称:rSymPy,代码行数:34,代码来源:solvers.py


示例5: gf_Qbasis

def gf_Qbasis(Q, p, K):
    """
    Compute a basis of the kernel of ``Q``.

    **Examples**

    >>> from sympy.polys.domains import ZZ
    >>> from sympy.polys.galoistools import gf_Qmatrix, gf_Qbasis

    >>> gf_Qbasis(gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ), 5, ZZ)
    [[1, 0, 0, 0], [0, 0, 1, 0]]

    >>> gf_Qbasis(gf_Qmatrix([3, 2, 4], 5, ZZ), 5, ZZ)
    [[1, 0]]

    """
    Q, n = [ list(q) for q in Q ], len(Q)

    for k in xrange(0, n):
        Q[k][k] = (Q[k][k] - K.one) % p

    for k in xrange(0, n):
        for i in xrange(k, n):
            if Q[k][i]:
                break
        else:
            continue

        inv = K.invert(Q[k][i], p)

        for j in xrange(0, n):
            Q[j][i] = (Q[j][i]*inv) % p

        for j in xrange(0, n):
            t = Q[j][k]
            Q[j][k] = Q[j][i]
            Q[j][i] = t

        for i in xrange(0, n):
            if i != k:
                q = Q[k][i]

                for j in xrange(0, n):
                    Q[j][i] = (Q[j][i] - Q[j][k]*q) % p

    for i in xrange(0, n):
        for j in xrange(0, n):
            if i == j:
                Q[i][j] = (K.one - Q[i][j]) % p
            else:
                Q[i][j] = (-Q[i][j]) % p

    basis = []

    for q in Q:
        if any(q):
            basis.append(q)

    return basis
开发者ID:addisonc,项目名称:sympy,代码行数:59,代码来源:galoistools.py


示例6: denester

def denester(nested):
    """
    Denests a list of expressions that contain nested square roots.
    This method should not be called directly - use 'denest' instead.
    This algorithm is based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>.

    It is assumed that all of the elements of 'nested' share the same
    bottom-level radicand. (This is stated in the paper, on page 177, in
    the paragraph immediately preceding the algorithm.)

    When evaluating all of the arguments in parallel, the bottom-level
    radicand only needs to be denested once. This means that calling
    denester with x arguments results in a recursive invocation with x+1
    arguments; hence denester has polynomial complexity.

    However, if the arguments were evaluated separately, each call would
    result in two recursive invocations, and the algorithm would have
    exponential complexity.

    This is discussed in the paper in the middle paragraph of page 179.
    """
    if all((n ** 2).is_Number for n in nested):  # If none of the arguments are nested
        for f in subsets(len(nested)):  # Test subset 'f' of nested
            p = prod(nested[i] ** 2 for i in range(len(f)) if f[i]).expand()
            if 1 in f and f.count(1) > 1 and f[-1]:
                p = -p
            if sqrt(p).is_Number:
                return sqrt(p), f  # If we got a perfect square, return its square root.
        return nested[-1], [0] * len(nested)  # Otherwise, return the radicand from the previous invocation.
    else:
        a, b, r, R = Wild("a"), Wild("b"), Wild("r"), None
        values = [expr.match(sqrt(a + b * sqrt(r))) for expr in nested]
        for v in values:
            if r in v:  # Since if b=0, r is not defined
                if R is not None:
                    assert R == v[r]  # All the 'r's should be the same.
                else:
                    R = v[r]
        d, f = denester([sqrt((v[a] ** 2).expand() - (R * v[b] ** 2).expand()) for v in values] + [sqrt(R)])
        if not any([f[i] for i in range(len(nested))]):  # If f[i]=0 for all i < len(nested)
            v = values[-1]
            return sqrt(v[a] + v[b] * d), f
        else:
            v = prod(nested[i] ** 2 for i in range(len(nested)) if f[i]).expand().match(a + b * sqrt(r))
            if 1 in f and f.index(1) < len(nested) - 1 and f[len(nested) - 1]:
                v[a] = -1 * v[a]
                v[b] = -1 * v[b]
            if not f[len(nested)]:  # Solution denests with square roots
                return (
                    (
                        sqrt((v[a] + d).expand() / 2) + sign(v[b]) * sqrt((v[b] ** 2 * R / (2 * (v[a] + d))).expand())
                    ).expand(),
                    f,
                )
            else:  # Solution requires a fourth root
                FR, s = (R.expand() ** Rational(1, 4)), sqrt((v[b] * R).expand() + d)
                return (s / (sqrt(2) * FR) + v[a] * FR / (sqrt(2) * s)).expand(), f
开发者ID:unix0000,项目名称:sympy-polys,代码行数:57,代码来源:sqrtdenest.py


示例7: _eval_nseries

    def _eval_nseries(self, x, n):
        """
        This function does compute series for multivariate functions,
        but the expansion is always in terms of *one* variable.
        Examples:

        >>> from sympy import atan2, O
        >>> from sympy.abc import x, y
        >>> atan2(x, y).series(x, n=2)
        atan2(0, y) + x/y + O(x**2)
        >>> atan2(x, y).series(y, n=2)
        atan2(x, 0) - y/x + O(y**2)
        """
        if self.func.nargs is None:
            raise NotImplementedError('series for user-defined \
functions are not supported.')
        args = self.args
        args0 = [t.limit(x, 0) for t in args]
        if any([t is S.NaN or t.is_bounded is False for t in args0]):
            raise PoleError("Cannot expand %s around 0" % (args))
        if (self.func.nargs == 1 and args0[0]) or self.func.nargs > 1:
            e = self
            e1 = e.expand()
            if e == e1:
                #for example when e = sin(x+1) or e = sin(cos(x))
                #let's try the general algorithm
                term = e.subs(x, S.Zero)
                if term.is_bounded is False or term is S.NaN:
                    raise PoleError("Cannot expand %s around 0" % (self))
                series = term
                fact = S.One
                for i in range(n-1):
                    i += 1
                    fact *= Rational(i)
                    e = e.diff(x)
                    subs = e.subs(x, S.Zero)
                    if subs is S.NaN:
                        # try to evaluate a limit if we have to
                        subs = e.limit(x, S.Zero)
                    if subs.is_bounded is False:
                        raise PoleError("Cannot expand %s around 0" % (self))
                    term = subs*(x**i)/fact
                    term = term.expand()
                    series += term
                return series + C.Order(x**n, x)
            return e1.nseries(x, n=n)
        arg = self.args[0]
        l = []
        g = None
        for i in xrange(n+2):
            g = self.taylor_term(i, arg, g)
            g = g.nseries(x, n=n)
            l.append(g)
        return Add(*l) + C.Order(x**n, x)
开发者ID:haz,项目名称:sympy,代码行数:54,代码来源:function.py


示例8: dmp_zz_wang_lead_coeffs

def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K):
    """Wang/EEZ: Compute correct leading coefficients. """
    C, J, v = [], [0]*len(E), u-1

    for h in H:
        c = dmp_one(v, K)
        d = dup_LC(h, K)*cs

        for i in reversed(xrange(len(E))):
            k, e, (t, _) = 0, E[i], T[i]

            while not (d % e):
                d, k = d//e, k+1

            if k != 0:
                c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1

        C.append(c)

    if any([ not j for j in J ]):
        raise ExtraneousFactors # pragma: no cover

    CC, HH = [], []

    for c, h in zip(C, H):
        d = dmp_eval_tail(c, A, v, K)
        lc = dup_LC(h, K)

        if K.is_one(cs):
            cc = lc//d
        else:
            g = K.gcd(lc, d)
            d, cc = d//g, lc//g
            h, cs = dup_mul_ground(h, d, K), cs//d

        c = dmp_mul_ground(c, cc, v, K)

        CC.append(c)
        HH.append(h)

    if K.is_one(cs):
        return f, HH, CC

    CCC, HHH = [], []

    for c, h in zip(CC, HH):
        CCC.append(dmp_mul_ground(c, cs, v, K))
        HHH.append(dmp_mul_ground(h, cs, 0, K))

    f = dmp_mul_ground(f, cs**(len(H)-1), u, K)

    return f, HHH, CCC
开发者ID:haz,项目名称:sympy,代码行数:52,代码来源:factortools.py


示例9: is_zero

    def is_zero(self):
        """Since Integral doesn't autosimplify it it useful to see if
        it would simplify to zero or not in a trivial manner, i.e. when
        the function is 0 or two limits of a definite integral are the same.

        This is a very naive and quick test, not intended to check for special
        patterns like Integral(sin(m*x)*cos(n*x), (x, 0, 2*pi)) == 0.
        """
        if self.function.is_zero or any(len(xab) == 3 and xab[1] == xab[2] for xab in self.limits):
            return True
        if not self.free_symbols and self.function.is_number:
            # the integrand is a number and the limits are numerical
            return False
开发者ID:robotment,项目名称:sympy,代码行数:13,代码来源:integrals.py


示例10: preprocess

    def preprocess(cls, gens):
        if isinstance(gens, Basic):
            gens = (gens,)
        elif len(gens) == 1 and hasattr(gens[0], '__iter__'):
            gens = gens[0]

        if gens == (None,):
            gens = ()
        elif len(set(gens)) != len(gens):
            raise GeneratorsError("duplicated generators: %s" % str(gens))
        elif any(gen.is_commutative is False for gen in gens):
            raise GeneratorsError("non-commutative generators: %s" % str(gens))

        return tuple(gens)
开发者ID:addisonc,项目名称:sympy,代码行数:14,代码来源:polyoptions.py


示例11: _parallel_dict_from_expr

def _parallel_dict_from_expr(exprs, opt):
    """Transform expressions into a multinomial form. """
    if opt.expand is not False:
        exprs = [ expr.expand() for expr in exprs ]

    if any(expr.is_commutative is False for expr in exprs):
        raise PolynomialError('non-commutative expressions are not supported')

    if opt.gens:
        reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt)
    else:
        reps, gens = _parallel_dict_from_expr_no_gens(exprs, opt)

    return reps, opt.clone({'gens': gens})
开发者ID:fxkr,项目名称:sympy,代码行数:14,代码来源:polyutils.py


示例12: __new__

    def __new__(cls, *args, **options):
        # Handle calls like Function('f')
        if cls is Function:
            return UndefinedFunction(*args)

        args = map(sympify, args)
        evaluate = options.pop('evaluate', True)
        if evaluate:
            evaluated = cls.eval(*args)
            if evaluated is not None:
                return evaluated
        result = super(Application, cls).__new__(cls, *args, **options)
        if evaluate and any([cls._should_evalf(a) for a in args]):
            return result.evalf()
        return result
开发者ID:addisonc,项目名称:sympy,代码行数:15,代码来源:function.py


示例13: _find

    def _find(self, tests, obj, name, module, source_lines, globs, seen):
        """
        Find tests for the given object and any contained objects, and
        add them to `tests`.
        """
        if self._verbose:
            print 'Finding tests in %s' % name

        # If we've already processed this object, then ignore it.
        if id(obj) in seen:
            return
        seen[id(obj)] = 1

        # Make sure we don't run doctests for classes outside of sympy, such
        # as in numpy or scipy.
        if inspect.isclass(obj):
            if obj.__module__.split('.')[0] != 'sympy':
                return

        # Find a test for this object, and add it to the list of tests.
        test = self._get_test(obj, name, module, globs, source_lines)
        if test is not None:
            tests.append(test)

        # Look for tests in a module's contained objects.
        if inspect.ismodule(obj) and self._recurse:
            for rawname, val in obj.__dict__.items():
                # Recurse to functions & classes.
                if inspect.isfunction(val) or inspect.isclass(val):
                    in_module = self._from_module(module, val)
                    if not in_module:
                        # double check in case this function is decorated
                        # and just appears to come from a different module.
                        pat = r'\s*(def|class)\s+%s\s*\(' % rawname
                        PAT = pre.compile(pat)
                        in_module = any(PAT.match(line) for line in source_lines)
                    if in_module:
                        try:
                            valname = '%s.%s' % (name, rawname)
                            self._find(tests, val, valname, module, source_lines, globs, seen)
                        except ValueError, msg:
                            if "invalid option" in msg.args[0]:
                                # +SKIP raises ValueError in Python 2.4
                                pass
                            else:
                                raise
                        except:
                            pass
开发者ID:qsnake,项目名称:sympy,代码行数:48,代码来源:runtests.py


示例14: gf_Qbasis

def gf_Qbasis(Q, p, K):
    """Compute a basis of the kernel of `Q`. """
    Q, n = [ list(q) for q in Q ], len(Q)

    for k in xrange(0, n):
        Q[k][k] = (Q[k][k] - K.one) % p

    for k in xrange(0, n):
        for i in xrange(k, n):
            if Q[k][i]:
                break
        else:
            continue

        inv = K.invert(Q[k][i], p)

        for j in xrange(0, n):
            Q[j][i] = (Q[j][i]*inv) % p

        for j in xrange(0, n):
            t = Q[j][k]
            Q[j][k] = Q[j][i]
            Q[j][i] = t

        for i in xrange(0, n):
            if i != k:
                q = Q[k][i]

                for j in xrange(0, n):
                    Q[j][i] = (Q[j][i] - Q[j][k]*q) % p

    for i in xrange(0, n):
        for j in xrange(0, n):
            if i == j:
                Q[i][j] = (K.one - Q[i][j]) % p
            else:
                Q[i][j] = (-Q[i][j]) % p

    basis = []

    for q in Q:
        if any(q):
            basis.append(q)

    return basis
开发者ID:Aang,项目名称:sympy,代码行数:45,代码来源:galoistools.py


示例15: test

def test(*args, **kwargs):
    """
    Run all tests containing any of the given strings in their path.

    If sort=False, run them in random order (not default).

    Warning: Tests in *very* deeply nested directories are not found.

    Examples:

    >> import sympy

    Run all tests:
    >> sympy.test()

    Run one file:
    >> sympy.test("sympy/core/tests/test_basic.py")

    Run all tests in sympy/functions/ and some particular file:
    >> sympy.test("sympy/core/tests/test_basic.py", "sympy/functions")

    Run all tests in sympy/core and sympy/utilities:
    >> sympy.test("core", "util")
    """
    from glob import glob
    verbose = kwargs.get("verbose", False)
    tb = kwargs.get("tb", "short")
    kw = kwargs.get("kw", "")
    post_mortem = kwargs.get("pdb", False)
    colors = kwargs.get("colors", True)
    sort = kwargs.get("sort", True)
    r = PyTestReporter(verbose, tb, colors)
    t = SymPyTests(r, kw, post_mortem)
    if len(args) == 0:
        t.add_paths(["sympy"])
    else:
        mypaths = []
        for p in t.get_paths(dir='sympy'):
            mypaths.extend(glob(p))
        mypaths = set(mypaths)
        t.add_paths([p for p in mypaths if any(a in p for a in args)])
    return t.test(sort=sort)
开发者ID:KevinGoodsell,项目名称:sympy,代码行数:42,代码来源:runtests.py


示例16: dup_zz_cyclotomic_factor

def dup_zz_cyclotomic_factor(f, K):
    """Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`.

       Given a univariate polynomial `f` in `Z[x]` returns a list of factors
       of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for
       `n >= 1`. Otherwise returns None.

       Factorization is performed using using cyclotomic decomposition of `f`,
       which makes this method much faster that any other direct factorization
       approach (e.g. Zassenhaus's).

       References
       ==========

       .. [Weisstein09] Eric W. Weisstein, Cyclotomic Polynomial, From MathWorld - A
           Wolfram Web Resource, http://mathworld.wolfram.com/CyclotomicPolynomial.html

    """
    lc_f, tc_f = dup_LC(f, K), dup_TC(f, K)

    if dup_degree(f) <= 0:
        return None

    if lc_f != 1 or tc_f not in [-1, 1]:
        return None

    if any([ bool(cf) for cf in f[1:-1] ]):
        return None

    n = dup_degree(f)
    F = _dup_cyclotomic_decompose(n, K)

    if not K.is_one(tc_f):
        return F
    else:
        H = []

        for h in _dup_cyclotomic_decompose(2*n, K):
            if h not in F:
                H.append(h)

        return H
开发者ID:Aang,项目名称:sympy,代码行数:42,代码来源:factortools.py


示例17: __new__

 def __new__(cls, *args, **options):
     args = map(sympify, args)
     # these lines should be refactored
     for opt in ["nargs", "dummy", "comparable", "noncommutative", "commutative"]:
         if opt in options:
             del options[opt]
     # up to here.
     if not options.pop('evaluate', True):
         return super(Application, cls).__new__(cls, *args, **options)
     evaluated = cls.eval(*args)
     if evaluated is not None:
         return evaluated
     # Just undefined functions have nargs == None
     if not cls.nargs and hasattr(cls, 'undefined_Function'):
         r = super(Application, cls).__new__(cls, *args, **options)
         r.nargs = len(args)
         return r
     r = super(Application, cls).__new__(cls, *args, **options)
     if any([cls._should_evalf(a) for a in args]):
         return r.evalf()
     return r
开发者ID:robotment,项目名称:sympy,代码行数:21,代码来源:function.py


示例18: tsolve

def tsolve(eq, sym):
    """
    Solves a transcendental equation with respect to the given
    symbol. Various equations containing mixed linear terms, powers,
    and logarithms, can be solved.

    Only a single solution is returned. This solution is generally
    not unique. In some cases, a complex solution may be returned
    even though a real solution exists.

        >>> from sympy import tsolve, log
        >>> from sympy.abc import x

        >>> tsolve(3**(2*x+5)-4, x)
        [(-5*log(3) + log(4))/(2*log(3))]

        >>> tsolve(log(x) + 2*x, x)
        [LambertW(2)/2]

    """
    if patterns is None:
        _generate_patterns()
    eq = sympify(eq)
    if isinstance(eq, Equality):
        eq = eq.lhs - eq.rhs
    sym = sympify(sym)
    eq2 = eq.subs(sym, x)
    # First see if the equation has a linear factor
    # In that case, the other factor can contain x in any way (as long as it
    # is finite), and we have a direct solution to which we add others that
    # may be found for the remaining portion.
    r = Wild("r")
    m = eq2.match((a * x + b) * r)
    if m and m[a]:
        return [(-b / a).subs(m).subs(x, sym)] + solve(m[r], x)
    for p, sol in patterns:
        m = eq2.match(p)
        if m:
            return [sol.subs(m).subs(x, sym)]

    # let's also try to inverse the equation
    lhs = eq
    rhs = S.Zero

    while True:
        indep, dep = lhs.as_independent(sym)

        # dep + indep == rhs
        if lhs.is_Add:
            # this indicates we have done it all
            if indep is S.Zero:
                break

            lhs = dep
            rhs -= indep

        # dep * indep == rhs
        else:
            # this indicates we have done it all
            if indep is S.One:
                break

            lhs = dep
            rhs /= indep

    #                    -1
    # f(x) = g  ->  x = f  (g)
    if lhs.is_Function and lhs.nargs == 1 and hasattr(lhs, "inverse"):
        rhs = lhs.inverse()(rhs)
        lhs = lhs.args[0]

        sol = solve(lhs - rhs, sym)
        return sol

    elif lhs.is_Add:
        # just a simple case - we do variable substitution for first function,
        # and if it removes all functions - let's call solve.
        #      x    -x                   -1
        # UC: e  + e   = y      ->  t + t   = y
        t = Dummy("t")
        terms = lhs.args

        # find first term which is Function
        for f1 in lhs.args:
            if f1.is_Function:
                break
        else:
            raise NotImplementedError(
                "Unable to solve the equation" + "(tsolve: at least one Function expected at this point"
            )

        # perform the substitution
        lhs_ = lhs.subs(f1, t)

        # if no Functions left, we can proceed with usual solve
        if not (lhs_.is_Function or any(term.is_Function for term in lhs_.args)):
            cv_sols = solve(lhs_ - rhs, t)
            for sol in cv_sols:
                if sol.has(sym):
                    raise NotImplementedError("Unable to solve the equation")
#.........这里部分代码省略.........
开发者ID:mackaka,项目名称:sympy,代码行数:101,代码来源:solvers.py


示例19: solve_linear_system

def solve_linear_system(system, *symbols, **flags):
    """Solve system of N linear equations with M variables, which means
       both Cramer and over defined systems are supported. The possible
       number of solutions is zero, one or infinite. Respectively this
       procedure will return None or dictionary with solutions. In the
       case of over defined system all arbitrary parameters are skipped.
       This may cause situation in with empty dictionary is returned.
       In this case it means all symbols can be assigned arbitrary values.

       Input to this functions is a Nx(M+1) matrix, which means it has
       to be in augmented form. If you are unhappy with such setting
       use 'solve' method instead, where you can input equations
       explicitly. And don't worry about the matrix, this function
       is persistent and will make a local copy of it.

       The algorithm used here is fraction free Gaussian elimination,
       which results, after elimination, in upper-triangular matrix.
       Then solutions are found using back-substitution. This approach
       is more efficient and compact than the Gauss-Jordan method.

       >>> from sympy import Matrix, solve_linear_system
       >>> from sympy.abc import x, y

       Solve the following system:

              x + 4 y ==  2
           -2 x +   y == 14

       >>> system = Matrix(( (1, 4, 2), (-2, 1, 14)))
       >>> solve_linear_system(system, x, y)
       {x: -6, y: 2}

    """
    matrix = system[:, :]
    syms = list(symbols)

    i, m = 0, matrix.cols - 1  # don't count augmentation

    while i < matrix.rows:
        if i == m:
            # an overdetermined system
            if any(matrix[i:, m]):
                return None  # no solutions
            else:
                # remove trailing rows
                matrix = matrix[:i, :]
                break

        if not matrix[i, i]:
            # there is no pivot in current column
            # so try to find one in other columns
            for k in xrange(i + 1, m):
                if matrix[i, k]:
                    break
            else:
                if matrix[i, m]:
                    return None  # no solutions
                else:
                    # zero row or was a linear combination of
                    # other rows so now we can safely skip it
                    matrix.row_del(i)
                    continue

            # we want to change the order of colums so
            # the order of variables must also change
            syms[i], syms[k] = syms[k], syms[i]
            matrix.col_swap(i, k)

        pivot_inv = S.One / matrix[i, i]

        # divide all elements in the current row by the pivot
        matrix.row(i, lambda x, _: x * pivot_inv)

        for k in xrange(i + 1, matrix.rows):
            if matrix[k, i]:
                coeff = matrix[k, i]

                # subtract from the current row the row containing
                # pivot and multiplied by extracted coefficient
                matrix.row(k, lambda x, j: simplify(x - matrix[i, j] * coeff))

        i += 1

    # if there weren't any problems, augmented matrix is now
    # in row-echelon form so we can check how many solutions
    # there are and extract them using back substitution

    simplified = flags.get("simplified", True)

    if len(syms) == matrix.rows:
        # this system is Cramer equivalent so there is
        # exactly one solution to this system of equations
        k, solutions = i - 1, {}

        while k >= 0:
            content = matrix[k, m]

            # run back-substitution for variables
            for j in xrange(k + 1, m):
                content -= matrix[k, j] * solutions[syms[j]]
#.........这里部分代码省略.........
开发者ID:mackaka,项目名称:sympy,代码行数:101,代码来源:solvers.py


示例20: solve

def solve(f, *symbols, **flags):
    """Solves equations and systems of equations.

       Currently supported are univariate polynomial, transcendental
       equations, piecewise combinations thereof and systems of linear
       and polynomial equations.  Input is formed as a single expression
       or an equation,  or an iterable container in case of an equation
       system.  The type of output may vary and depends heavily on the
       input. For more details refer to more problem specific functions.

       By default all solutions are simplified to make the output more
       readable. If this is not the expected behavior (e.g., because of
       speed issues) set simplified=False in function arguments.

       To solve equations and systems of equations like recurrence relations
       or differential equations, use rsolve() or dsolve(), respectively.

       >>> from sympy import I, solve
       >>> from sympy.abc import x, y

       Solve a polynomial equation:

       >>> solve(x**4-1, x)
       [1, -1, -I, I]

       Solve a linear system:

       >>> solve((x+5*y-2, -3*x+6*y-15), x, y)
       {x: -3, y: 1}

    """

    def sympit(w):
        return map(sympify, iff(isinstance(w, (list, tuple, set)), w, [w]))

    # make f and symbols into lists of sympified quantities
    # keeping track of how f was passed since if it is a list
    # a dictionary of results will be returned.
    bare_f = not isinstance(f, (list, tuple, set))
    f, symbols = (sympit(w) for w in [f, symbols])

    if any(isinstance(fi, bool) or (fi.is_Relational and not fi.is_Equality) for fi in f):
        return reduce_inequalities(f, assume=flags.get("assume"))

    for i, fi in enumerate(f):
        if fi.is_Equality:
            f[i] = fi.lhs - fi.rhs

    if not symbols:
        # get symbols from equations or supply dummy symbols since
        # solve(3,x) returns []...though it seems that it should raise some sort of error TODO
        symbols = set([])
        for fi in f:
            symbols |= fi.atoms(Symbol) or set([Dummy("x")])
        symbols = list(symbols)

    if bare_f:
        f = f[0]
    if len(symbols) == 1:
        if isinstance(symbols[0], (list, tuple, set)):
            symbols = symbols[0]

    result = list()

    # Begin code handling for Function and Derivative instances
    # Basic idea:  store all the passed symbols in symbols_passed, check to see
    # if any of them are Function or Derivative types, if so, use a dummy
    # symbol in their place, and set symbol_swapped = True so that other parts
    # of the code can be aware of the swap.  Once all swapping is done, the
    # continue on with regular solving as usual, and swap back at the end of
    # the routine, so that whatever was passed in symbols is what is returned.
    symbols_new = []
    symbol_swapped = False

    symbols_passed = list(symbols)

    for i, s in enumerate(symbols):
        if s.is_Symbol:
            s_new = s
        elif s.is_Function:
            symbol_swapped = True
            s_new = Dummy("F%d" % i)
        elif s.is_Derivative:
            symbol_swapped = True
            s_new = Dummy("D%d" % i)
        else:
            raise TypeError("not a Symbol or a Function")
        symbols_new.append(s_new)

        if symbol_swapped:
            swap_back_dict = dict(zip(symbols_new, symbols))
    # End code for handling of Function and Derivative instances

    if not isinstance(f, (tuple, list, set)):

        # Create a swap dictionary for storing the passed symbols to be solved
        # for, so that they may be swapped back.
        if symbol_swapped:
            swap_dict = zip(symbols, symbols_new)
            f = f.subs(swap_dict)
#.........这里部分代码省略.........
开发者ID:mackaka,项目名称:sympy,代码行数:101,代码来源:solvers.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utilities.filldedent函数代码示例发布时间:2022-05-27
下一篇:
Python utilities.all函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap