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


Python sympify.sympify函数代码示例

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


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

示例1: domain_check

def domain_check(f, symbol, p):
    """Returns False if point p is infinite or any subexpression of f
    is infinite or becomes so after replacing symbol with p. If none of
    these conditions is met then True will be returned.

    Examples
    ========

    >>> from sympy import Mul, oo
    >>> from sympy.abc import x
    >>> from sympy.solvers.solveset import domain_check
    >>> g = 1/(1 + (1/(x + 1))**2)
    >>> domain_check(g, x, -1)
    False
    >>> domain_check(x**2, x, 0)
    True
    >>> domain_check(1/x, x, oo)
    False

    * The function relies on the assumption that the original form
      of the equation has not been changed by automatic simplification.

    >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1
    True

    * To deal with automatic evaluations use evaluate=False:

    >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0)
    False
    """
    f, p = sympify(f), sympify(p)
    if p.is_infinite:
        return False
    return _domain_check(f, symbol, p)
开发者ID:A-turing-machine,项目名称:sympy,代码行数:34,代码来源:solveset.py

示例2: __new__

    def __new__(cls, periodical, limits=None):
        x, start, stop = None, None, None
        if limits is None:
            x, start, stop = Dummy("k"), 0, S.Infinity
        if is_sequence(limits, Tuple):
            if len(limits) == 3:
                x, start, stop = limits
            elif len(limits) == 2:
                x = Dummy("k")
                start, stop = limits

        if not isinstance(x, Symbol) or start is None or stop is None:
            raise ValueError("Invalid limits given: %s" % str(limits))

        if start is S.NegativeInfinity and stop is S.Infinity:
            raise ValueError("Both the start and end value" " cannot be unbounded")

        limits = sympify((x, start, stop))

        if is_sequence(periodical, Tuple):
            periodical = sympify(tuple(flatten(periodical)))
        else:
            raise ValueError("invalid period %s should be something " "like e.g (1, 2) " % periodical)

        if Interval(limits[1], limits[2]) is S.EmptySet:
            return S.EmptySequence

        return Basic.__new__(cls, periodical, limits)
开发者ID:LuckyStrikes1090,项目名称:sympy,代码行数:28,代码来源:sequences.py

示例3: _evalf

def _evalf(func, points, derivatives=False, method="RK4"):
    """
    Numerical methods for numerical integration along a given set of
    points in the complex plane.
    """

    ann = func.annihilator
    a = ann.order
    R = ann.parent.base
    K = R.get_field()

    if method == "Euler":
        meth = _euler
    else:
        meth = _rk4

    dmf = []
    for j in ann.listofpoly:
        dmf.append(K.new(j.rep))

    red = [-dmf[i] / dmf[a] for i in range(a)]

    y0 = func.y0
    if len(y0) < a:
        raise TypeError("Not Enough Initial Conditions")
    x0 = func.x0
    sol = [meth(red, x0, points[0], y0, a)]

    for i, j in enumerate(points[1:]):
        sol.append(meth(red, points[i], j, sol[-1], a))

    if not derivatives:
        return [sympify(i[0]) for i in sol]
    else:
        return sympify(sol)
开发者ID:ashutoshsaboo,项目名称:sympy,代码行数:35,代码来源:numerical.py

示例4: gcd

    def gcd(self, other):  # Factors
        """Return Factors of ``gcd(self, other)``. The keys are
        the intersection of factors with the minimum exponent for
        each factor.

        Examples
        ========

        >>> from sympy.core.exprtools import Factors
        >>> from sympy.abc import x, y, z
        >>> a = Factors((x*y**2).as_powers_dict())
        >>> b = Factors((x*y/z).as_powers_dict())
        >>> a.gcd(b)
        Factors({x: 1, y: 1})
        """
        if not isinstance(other, Factors):
            other = Factors(other)
            if other.is_zero:
                return Factors(self.factors)

        factors = {}

        for factor, exp in self.factors.items():
            factor, exp = sympify(factor), sympify(exp)
            if factor in other.factors:
                lt = (exp - other.factors[factor]).is_negative
                if lt == True:
                    factors[factor] = exp
                elif lt == False:
                    factors[factor] = other.factors[factor]

        return Factors(factors)
开发者ID:amitsaha,项目名称:sympy,代码行数:32,代码来源:exprtools.py

示例5: test_sympyify_iterables

def test_sympyify_iterables():
    ans = [Rational(3, 10), Rational(1, 5)]
    assert sympify(['.3', '.2'], rational=True) == ans
    assert sympify(set(['.3', '.2']), rational=True) == set(ans)
    assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
    assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
    assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
开发者ID:SungSingSong,项目名称:sympy,代码行数:7,代码来源:test_sympify.py

示例6: test_issue_10295

def test_issue_10295():
    if not numpy:
        skip("numpy not installed.")

    A = numpy.array([[1, 3, -1],
                     [0, 1, 7]])
    sA = S(A)
    assert sA.shape == (2, 3)
    for (ri, ci), val in numpy.ndenumerate(A):
        assert sA[ri, ci] == val

    B = numpy.array([-7, x, 3*y**2])
    sB = S(B)
    assert B[0] == -7
    assert B[1] == x
    assert B[2] == 3*y**2

    C = numpy.arange(0, 24)
    C.resize(2,3,4)
    sC = S(C)
    assert sC[0, 0, 0].is_integer
    assert sC[0, 0, 0] == 0

    a1 = numpy.array([1, 2, 3])
    a2 = numpy.array([i for i in range(24)])
    a2.resize(2, 4, 3)
    assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3])
    assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3))
开发者ID:baoqchau,项目名称:sympy,代码行数:28,代码来源:test_sympify.py

示例7: __eval_cond

 def __eval_cond(cls, cond):
     """Returns S.One if True, S.Zero if False, or None if undecidable."""
     if type(cond) == bool or cond.is_Number:
         return sympify(bool(cond))
     if cond.args[0].is_Number and cond.args[1].is_Number:
         return sympify(bool(cond))
     return None
开发者ID:gnulinooks,项目名称:sympy,代码行数:7,代码来源:piecewise.py

示例8: __getitem__

 def __getitem__(self, key):
     if not isinstance(key, tuple) and isinstance(key, slice):
         from sympy.matrices.expressions.slice import MatrixSlice
         return MatrixSlice(self, key, (0, None, 1))
     if isinstance(key, tuple) and len(key) == 2:
         i, j = key
         if isinstance(i, slice) or isinstance(j, slice):
             from sympy.matrices.expressions.slice import MatrixSlice
             return MatrixSlice(self, i, j)
         i, j = sympify(i), sympify(j)
         if self.valid_index(i, j) != False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid indices (%s, %s)" % (i, j))
     elif isinstance(key, (SYMPY_INTS, Integer)):
         # row-wise decomposition of matrix
         rows, cols = self.shape
         # allow single indexing if number of columns is known
         if not isinstance(cols, Integer):
             raise IndexError(filldedent('''
                 Single indexing is only supported when the number
                 of columns is known.'''))
         key = sympify(key)
         i = key // cols
         j = key % cols
         if self.valid_index(i, j) != False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid index %s" % key)
     elif isinstance(key, (Symbol, Expr)):
             raise IndexError(filldedent('''
                 Only integers may be used when addressing the matrix
                 with a single index.'''))
     raise IndexError("Invalid index, wanted %s[i,j]" % self)
开发者ID:raoulb,项目名称:sympy,代码行数:34,代码来源:matexpr.py

示例9: inicializar

def inicializar(argumentos):
    if len(argumentos) < 6:
        print("Es necesario introducir 6 argumentos")
        print("Uso: python SuperficieRevolucion.py <f(t)> <g(t)> <número de puntos> <inicio> <fin>")
        sys.exit(-1)

    global vertices, x_t, y_t, z_t
    t = symbols('t')

    x_t         = sympify(argumentos[1])
    y_t         = sympify(argumentos[2])
    z_t         = sympify('0')
    num_puntos  = int(argumentos[3])
    inicio      = float(argumentos[4])
    final       = float(argumentos[5])
    vueltas     = 32

    longitud = final - inicio
    incremento = longitud / (num_puntos - 1)

    curva = Matrix([x_t,y_t,z_t])

    for indice_punto in range(num_puntos):
        t_var = inicio + indice_punto*incremento
        vertices.append([curva[0].subs(t,t_var),curva[1].subs(t,t_var),curva[2].subs(t,t_var)])

    revoluciona(vueltas)

    glEnable(GL_NORMALIZE)
    glEnable(GL_MULTISAMPLE_ARB);
    glClearColor( 1.0, 1.0, 1.0, 1.0 ) ;
    glColor3f(0.0,0.0,0.0)
开发者ID:ranea,项目名称:SuperficiesRevolucion,代码行数:32,代码来源:SuperficiesRevolucion.py

示例10: test_sympify3

def test_sympify3():
    assert sympify("x**3") == x**3
    assert sympify("x^3") == x**3
    assert sympify("1/2") == Integer(1)/2

    raises(SympifyError, "_sympify('x**3')")
    raises(SympifyError, "_sympify('1/2')")
开发者ID:KevinGoodsell,项目名称:sympy,代码行数:7,代码来源:test_sympify.py

示例11: test_lambda

def test_lambda():
    x = Symbol('x')
    assert sympify('lambda : 1') == Lambda(x, 1)
    assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
    assert sympify('lambda x, y: 2*x+y') == Lambda([x, y], 2*x+y)

    raises(SympifyError, "_sympify('lambda : 1')")
开发者ID:KevinGoodsell,项目名称:sympy,代码行数:7,代码来源:test_sympify.py

示例12: test_sympify3

def test_sympify3():
    assert sympify("x**3") == x ** 3
    assert sympify("x^3") == x ** 3
    assert sympify("1/2") == Integer(1) / 2

    raises(SympifyError, lambda: _sympify("x**3"))
    raises(SympifyError, lambda: _sympify("1/2"))
开发者ID:ottersmh,项目名称:sympy,代码行数:7,代码来源:test_sympify.py

示例13: __getitem__

 def __getitem__(self, key):
     if not isinstance(key, tuple) and isinstance(key, slice):
         from sympy.matrices.expressions.slice import MatrixSlice
         return MatrixSlice(self, key, (0, None, 1))
     if isinstance(key, tuple) and len(key) == 2:
         i, j = key
         if isinstance(i, slice) or isinstance(j, slice):
             from sympy.matrices.expressions.slice import MatrixSlice
             return MatrixSlice(self, i, j)
         i, j = sympify(i), sympify(j)
         if self.valid_index(i, j) != False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid indices (%s, %s)" % (i, j))
     elif isinstance(key, (int, Integer)):
         # row-wise decomposition of matrix
         rows, cols = self.shape
         if not (isinstance(rows, Integer) and isinstance(cols, Integer)):
             raise IndexError("Single index only supported for "
                              "non-symbolic matrix shapes.")
         key = sympify(key)
         i = key // cols
         j = key % cols
         if self.valid_index(i, j) != False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid index %s" % key)
     elif isinstance(key, (Symbol, Expr)):
             raise IndexError("Single index only supported for "
                              "non-symbolic indices.")
     raise IndexError("Invalid index, wanted %s[i,j]" % self)
开发者ID:alexako,项目名称:sympy,代码行数:31,代码来源:matexpr.py

示例14: test_issue_15265

def test_issue_15265():
    from sympy.core.sympify import sympify
    from sympy.core.singleton import S

    matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
    if not matplotlib:
        skip("Matplotlib not the default backend")

    x = Symbol('x')
    eqn = sin(x)

    p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
    p._backend.close()

    p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
    p._backend.close()

    p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
    p._backend.close()

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-S.Infinity, 1), ylim=(-1, 1)))

    raises(ValueError,
        lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
开发者ID:Lenqth,项目名称:sympy,代码行数:34,代码来源:test_plot.py

示例15: compute_fps

def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
    """Computes the formula for Formal Power Series of a function.

    Returns (sequence of coefficients, sequence of x, independent terms,
    common terms).

    Tries to compute the formula by applying the following techniques
    (in order)

    * rational_algorithm
    * Hypergeomitric algorithm

    Parameters
    ==========

    x : Symbol
    x0 : number, optional
        Point to perform series expansion about. Default is 0.
    dir : {1, -1, '+', '-'}, optional
        If dir is 1 or '+' the series is calculated from the right and
        for -1 or '-' the series is calculated from the left. For smooth
        functions this flag will not alter the results. Default is 1.
    hyper : {True, False}, optional
        Set hyper to False to skip the hypergeometric algorithm.
        By default it is set to False.
    order : int, optional
        Order of the derivative of ``f``, Default is 4.
    rational : {True, False}, optional
        Set rational to False to skip rational algorithm. By default it is set
        to True.
    full : {True, False}, optional
        Set full to True to increase the range of rational algorithm.
        See :func:`rational_algorithm` for details. By default it is set to
        False.

    See Also
    ========

    sympy.series.rational_algorithm
    sympy.series.hyper_algorithm
    """
    f = sympify(f)
    x = sympify(x)

    if not f.has(x):
        return None

    x0 = sympify(x0)

    if dir == "+":
        dir = S.One
    elif dir == "-":
        dir = -S.One
    elif dir not in [S.One, -S.One]:
        raise ValueError("Dir must be '+' or '-'")
    else:
        dir = sympify(dir)

    return _compute_fps(f, x, x0, dir, hyper, order, rational, full)
开发者ID:neitzke,项目名称:sympy,代码行数:59,代码来源:formal.py


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