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

Python sympy.Expr类代码示例

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

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



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

示例1: __new__

 def __new__(cls, *args, **hints):
     if not len(args) == 6:
         raise ValueError('6 parameters expected, got %s' % args)
     evaluate = hints.get('evaluate', False)
     if evaluate:
         return Expr.__new__(cls, *args)._eval_wignerd()
     return Expr.__new__(cls, *args, **{'evaluate': False})
开发者ID:101man,项目名称:sympy,代码行数:7,代码来源:spin.py


示例2: __new__

    def __new__(cls, expr, condition=None, **kwargs):
        expr = _sympify(expr)
        if not kwargs.pop('evaluate', global_evaluate[0]):
            if condition is None:
                obj = Expr.__new__(cls, expr)
            else:
                condition = _sympify(condition)
                obj = Expr.__new__(cls, expr, condition)
            obj._condition = condition
            return obj

        if not expr.has(RandomSymbol):
            return expr

        if condition is not None:
            condition = _sympify(condition)

        if isinstance(expr, Add):
            return Add(*[Expectation(a, condition=condition) for a in expr.args])
        elif isinstance(expr, Mul):
            rv = []
            nonrv = []
            for a in expr.args:
                if isinstance(a, RandomSymbol) or a.has(RandomSymbol):
                    rv.append(a)
                else:
                    nonrv.append(a)
            return Mul(*nonrv)*Expectation(Mul(*rv), condition=condition, evaluate=False)
        else:
            if condition is None:
                obj = Expr.__new__(cls, expr)
            else:
                obj = Expr.__new__(cls, expr, condition)
            obj._condition = condition
            return obj
开发者ID:AStorus,项目名称:sympy,代码行数:35,代码来源:symbolic_probability.py


示例3: _eval_adjoint

 def _eval_adjoint(self):
     obj = Expr._eval_adjoint(self)
     if obj is None:
         obj = Expr.__new__(Dagger, self)
     if isinstance(obj, QExpr):
         obj.hilbert_space = self.hilbert_space
     return obj
开发者ID:cklb,项目名称:sympy,代码行数:7,代码来源:qexpr.py


示例4: __new__

    def __new__(cls, *args):
        """ Construct a Trace object.

        Parameters
        ==========
        args = sympy expression

        """

        expr = args[0]
        indices = Tuple(*args[1]) if len(args) == 2 else Tuple()
        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, 'trace') and callable(t.x):
            #for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                nc_part_ordered = _cycle_permute(_rearrange_args(nc_part))
                return Mul(*c_part) * Expr.__new__(cls, Mul(*nc_part_ordered), indices )
        elif isinstance(expr, Pow):
            if (_is_scalar(expr.args[0]) and
                _is_scalar(expr.args[1])):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if (_is_scalar(expr)):
                return expr
            return Expr.__new__(cls, expr, indices)
开发者ID:yanchao727,项目名称:sympy,代码行数:35,代码来源:trace.py


示例5: __new__

    def __new__(cls, *args, **kwargs):
        from sympy.tensor.array import NDimArray, tensorproduct, Array
        from sympy import MatrixBase, MatrixExpr
        from sympy.strategies import flatten

        args = [sympify(arg) for arg in args]
        evaluate = kwargs.get("evaluate", global_evaluate[0])

        if not evaluate:
            obj = Expr.__new__(cls, *args)
            return obj

        arrays = []
        other = []
        scalar = S.One
        for arg in args:
            if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
                arrays.append(Array(arg))
            elif isinstance(arg, (MatrixExpr,)):
                other.append(arg)
            else:
                scalar *= arg

        coeff = scalar*tensorproduct(*arrays)
        if len(other) == 0:
            return coeff
        if coeff != 1:
            newargs = [coeff] + other
        else:
            newargs = other
        obj = Expr.__new__(cls, *newargs, **kwargs)
        return flatten(obj)
开发者ID:Lenqth,项目名称:sympy,代码行数:32,代码来源:functions.py


示例6: _call_super_constructor

 def _call_super_constructor(cls, arg1, arg2, condition):
     if condition is not None:
         obj = Expr.__new__(cls, arg1, arg2, condition)
     else:
         obj = Expr.__new__(cls, arg1, arg2)
     obj._condition = condition
     return obj
开发者ID:Asnelchristian,项目名称:sympy,代码行数:7,代码来源:symbolic_probability.py


示例7: __new__

    def __new__(cls, *args):
        """ Construct a Trace object.

        """
        expr = args[0]
        indices = args[1] if len(args) == 2 else -1  # -1 indicates full trace
        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, "trace") and callable(t.x):
            # for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                # cyclic permute nc_part for canonical ordering
                nc_part_ordered = _cycle_permute(nc_part)
                return Mul(*c_part) * Expr.__new__(cls, Mul(*nc_part_ordered), indices)
        elif isinstance(expr, Pow):
            if _is_scalar(expr.args[0]) and _is_scalar(expr.args[1]):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if _is_scalar(expr):
                return expr
            return Expr.__new__(cls, expr, indices)
开发者ID:piyushbansal,项目名称:sympy,代码行数:30,代码来源:trace.py


示例8: __new__

 def __new__(cls, *args, **hints):
     if not len(args) == 6:
         raise ValueError("6 parameters expected, got %s" % args)
     args = sympify(args)
     evaluate = hints.get("evaluate", False)
     if evaluate:
         return Expr.__new__(cls, *args)._eval_wignerd()
     return Expr.__new__(cls, *args, **{"evaluate": False})
开发者ID:jackey-qiu,项目名称:sympy,代码行数:8,代码来源:spin.py


示例9: __new__

 def __new__(cls, arg, condition=None, **kwargs):
     arg = _sympify(arg)
     if condition is None:
         obj = Expr.__new__(cls, arg)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, arg, condition)
     obj._condition = condition
     return obj
开发者ID:AlexanderKulka,项目名称:sympy,代码行数:9,代码来源:symbolic_probability.py


示例10: __new__

    def __new__(cls, *args):
        """ Construct a Trace object.

        Parameters
        ==========
        args = sympy expression
        indices = tuple/list if indices, optional

        """

        # expect no indices,int or a tuple/list/Tuple
        if (len(args) == 2):
            if not isinstance(args[1], (list, Tuple, tuple)):
                indices = Tuple(args[1])
            else:
                indices = Tuple(*args[1])

            expr = args[0]
        elif (len(args) == 1):
            indices = Tuple()
            expr = args[0]
        else:
            raise ValueError("Arguments to Tr should be of form"
                             "(expr[, [indices]])")


        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, 'trace') and callable(expr.trace):
            #for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                obj = Expr.__new__(cls, Mul(*nc_part), indices )
                #this check is needed to prevent cached instances
                #being returned even if len(c_part)==0
                return Mul(*c_part)*obj if len(c_part)>0 else obj
        elif isinstance(expr, Pow):
            if (_is_scalar(expr.args[0]) and
                _is_scalar(expr.args[1])):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if (_is_scalar(expr)):
                return expr

            return Expr.__new__(cls, expr, indices)
开发者ID:StefenYin,项目名称:sympy,代码行数:53,代码来源:trace.py


示例11: __new__

 def __new__(cls, arg, **old_assumptions):
     # Return the dagger of a sympy Matrix immediately.
     if isinstance(arg, (Matrix, numpy_ndarray, scipy_sparse_matrix)):
         return matrix_dagger(arg)
     arg = sympify(arg)
     r = cls.eval(arg)
     if isinstance(r, Expr):
         return r
     #make unevaluated dagger commutative or non-commutative depending on arg
     if arg.is_commutative:
         obj = Expr.__new__(cls, arg, **{'commutative':True})
     else:
         obj = Expr.__new__(cls, arg, **{'commutative':False})
     if isinstance(obj, QExpr):
         obj.hilbert_space = arg.hilbert_space
     return obj
开发者ID:arunenigma,项目名称:sympy,代码行数:16,代码来源:dagger.py


示例12: __new__

    def __new__(cls, *args, **old_assumptions):
        """Construct a new quantum object.

        Parameters
        ==========
        args : tuple
            The list of numbers or parameters that uniquely specify the
            quantum object. For a state, this will be its symbol or its
            set of quantum numbers.

        Examples
        ========

        >>> from sympy.physics.quantum.qexpr import QExpr
        >>> q = QExpr(0)
        >>> q
        0
        >>> q.label
        (0,)
        >>> q.hilbert_space
        H
        >>> q.args
        (0,)
        >>> q.is_commutative
        False
        """

        # First compute args and call Expr.__new__ to create the instance
        args = cls._eval_args(args)
        inst = Expr.__new__(cls, *args, **{'commutative':False})
        # Now set the slots on the instance
        inst.hilbert_space = cls._eval_hilbert_space(args)
        return inst
开发者ID:Aang,项目名称:sympy,代码行数:33,代码来源:qexpr.py


示例13: __new__

 def __new__(cls, bra, ket):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, bra, ket)
     return obj
开发者ID:A-turing-machine,项目名称:sympy,代码行数:7,代码来源:innerproduct.py


示例14: __mul__

 def __mul__(self, other):
     """KetBase*other"""
     from sympsi.operator import OuterProduct
     if isinstance(other, BraBase):
         return OuterProduct(self, other)
     else:
         return Expr.__mul__(self, other)
开发者ID:eunjongkim,项目名称:sympsi,代码行数:7,代码来源:state.py


示例15: __new__

 def __new__(cls, bra, ket, **old_assumptions):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, *(bra, ket), **{'commutative':True})
     return obj
开发者ID:arunenigma,项目名称:sympy,代码行数:7,代码来源:innerproduct.py


示例16: __new__

    def __new__(cls, factor=1, unit=None, abbrev='', **assumptions):

        if not isinstance(factor, str):
            factor = sympify(factor)

        # if the given unit is a number (because of some operations) and
        # the factor is represented as a number, then return a number
        if ((unit is None or isinstance(unit, (Number, numbers.Real)))
                    and isinstance(factor, (Number, numbers.Real))):
            return factor * (unit or 1)

        #TODO: if factor is of the form "1 m", parse the factor and the unit
        if isinstance(factor, (Number, numbers.Real)):
            unit = cls.qsimplify(unit)
            if isinstance(unit, Quantity):
                unit = unit.as_unit
            if not isinstance(unit, Unit):
                raise TypeError("'unit' should be a Unit instance; %s found"
                                % type(unit))
        else:
            raise NotImplementedError

        obj = Expr.__new__(cls, factor, unit, **assumptions)
        obj.factor, obj.unit = factor, unit
        obj._abbrev = abbrev

        return obj
开发者ID:chaffra,项目名称:sympy,代码行数:27,代码来源:quantities.py


示例17: _eval_evalf

 def _eval_evalf(self, prec):
     from sympy.mpmath import mp, workprec
     from sympy import Expr
     z = self.args[0]._to_mpmath(prec)
     with workprec(prec):
         res = mp.airybi(z, derivative=1)
     return Expr._from_mpmath(res, prec)
开发者ID:AdrianPotter,项目名称:sympy,代码行数:7,代码来源:bessel.py


示例18: jn_zeros

def jn_zeros(n, k, method="sympy", dps=15):
    """
    Zeros of the spherical Bessel function of the first kind.

    This returns an array of zeros of jn up to the k-th zero.

    * method = "sympy": uses mpmath besseljzero
    * method = "scipy": uses the SciPy's sph_jn and newton to find all
      roots, which is faster than computing the zeros using a general
      numerical solver, but it requires SciPy and only works with low
      precision floating point numbers.  [the function used with
      method="sympy" is a recent addition to mpmath, before that a general
      solver was used]

    Examples
    ========

    >>> from sympy import jn_zeros
    >>> jn_zeros(2, 4, dps=5)
    [5.7635, 9.095, 12.323, 15.515]

    See Also
    ========

    jn, yn, besselj, besselk, bessely
    """
    from math import pi

    if method == "sympy":
        from sympy.mpmath import besseljzero
        from sympy.mpmath.libmp.libmpf import dps_to_prec
        from sympy import Expr
        prec = dps_to_prec(dps)
        return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec),
                                              int(k)), prec)
                for k in xrange(1, k + 1)]
    elif method == "scipy":
        from scipy.special import sph_jn
        from scipy.optimize import newton
        f = lambda x: sph_jn(n, x)[0][-1]
    else:
        raise NotImplementedError("Unknown method.")

    def solver(f, x):
        if method == "scipy":
            root = newton(f, x)
        else:
            raise NotImplementedError("Unknown method.")
        return root

    # we need to approximate the position of the first root:
    root = n + pi
    # determine the first root exactly:
    root = solver(f, root)
    roots = [root]
    for i in range(k - 1):
        # estimate the position of the next root using the last root + pi:
        root = solver(f, root + pi)
        roots.append(root)
    return roots
开发者ID:malikdiarra,项目名称:sympy,代码行数:60,代码来源:bessel.py


示例19: __rmul__

 def __rmul__(self, other):
     """other*BraBase"""
     from sympy.physics.quantum.operator import OuterProduct
     if isinstance(other, KetBase):
         return OuterProduct(other, self)
     else:
         return Expr.__rmul__(self, other)
开发者ID:asmeurer,项目名称:sympy,代码行数:7,代码来源:state.py


示例20: __mul__

 def __mul__(self, other):
     """BraBase*other"""
     from sympy.physics.quantum.innerproduct import InnerProduct
     if isinstance(other, KetBase):
         return InnerProduct(self, other)
     else:
         return Expr.__mul__(self, other)
开发者ID:asmeurer,项目名称:sympy,代码行数:7,代码来源:state.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python sympy.FiniteSet类代码示例发布时间:2022-05-27
下一篇:
Python sympy.EulerGamma类代码示例发布时间: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