本文整理汇总了Python中sympy.core.sympify._sympify函数的典型用法代码示例。如果您正苦于以下问题:Python _sympify函数的具体用法?Python _sympify怎么用?Python _sympify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_sympify函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __new__
def __new__(cls, start, end, left_open=False, right_open=False):
start = _sympify(start)
end = _sympify(end)
left_open = _sympify(left_open)
right_open = _sympify(right_open)
if not all(isinstance(a, (type(true), type(false))) for a in [left_open, right_open]):
raise NotImplementedError(
"left_open and right_open can have only true/false values, "
"got %s and %s" % (left_open, right_open))
inftys = [S.Infinity, S.NegativeInfinity]
# Only allow real intervals (use symbols with 'is_real=True').
if not (start.is_real or start in inftys) or not (end.is_real or end in inftys):
raise ValueError("Only real intervals are supported")
# Make sure that the created interval will be valid.
if end.is_comparable and start.is_comparable:
if end < start:
return S.EmptySet
if end == start and (left_open or right_open):
return S.EmptySet
if end == start and not (left_open or right_open):
return FiniteSet(end)
# Make sure infinite interval end points are open.
if start == S.NegativeInfinity:
left_open = true
if end == S.Infinity:
right_open = true
return Basic.__new__(cls, start, end, left_open, right_open)
开发者ID:alphaitis,项目名称:sympy,代码行数:34,代码来源:sets.py
示例2: __new__
def __new__(cls, b, e, evaluate=True):
b = _sympify(b)
e = _sympify(e)
obj = sympy.Expr.__new__(cls, b, e)
obj.is_commutative = b.is_commutative and e.is_commutative
return obj
开发者ID:nebffa,项目名称:MathsExams,代码行数:7,代码来源:noevals.py
示例3: __new__
def __new__(cls, arg1, arg2, condition=None, **kwargs):
arg1 = _sympify(arg1)
arg2 = _sympify(arg2)
if not kwargs.pop('evaluate', global_evaluate[0]):
if condition is None:
obj = Expr.__new__(cls, arg1, arg2)
else:
condition = _sympify(condition)
obj = Expr.__new__(cls, arg1, arg2, condition)
obj._condition = condition
return obj
if condition is not None:
condition = _sympify(condition)
if arg1 == arg2:
return Variance(arg1, condition)
if not arg1.has(RandomSymbol):
return S.Zero
if not arg2.has(RandomSymbol):
return S.Zero
arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)
if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
return Expr.__new__(cls, arg1, arg2)
coeff_rv_list1 = cls._expand_single_argument(arg1.expand())
coeff_rv_list2 = cls._expand_single_argument(arg2.expand())
addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), evaluate=False)
for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
return Add(*addends)
开发者ID:AStorus,项目名称:sympy,代码行数:35,代码来源:symbolic_probability.py
示例4: __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:bjodah,项目名称:sympy,代码行数:34,代码来源:matexpr.py
示例5: __new__
def __new__(cls, index, system, pretty_str=None, latex_str=None):
from sympy.vector.coordsysrect import CoordSys3D
if pretty_str is None:
pretty_str = "x{0}".format(index)
elif isinstance(pretty_str, Symbol):
pretty_str = pretty_str.name
if latex_str is None:
latex_str = "x_{0}".format(index)
elif isinstance(latex_str, Symbol):
latex_str = latex_str.name
index = _sympify(index)
system = _sympify(system)
obj = super(BaseScalar, cls).__new__(cls, index, system)
if not isinstance(system, CoordSys3D):
raise TypeError("system should be a CoordSys3D")
if index not in range(0, 3):
raise ValueError("Invalid index specified.")
# The _id is used for equating purposes, and for hashing
obj._id = (index, system)
obj._name = obj.name = system._name + '.' + system._variable_names[index]
obj._pretty_form = u'' + pretty_str
obj._latex_form = latex_str
obj._system = system
return obj
开发者ID:asmeurer,项目名称:sympy,代码行数:26,代码来源:scalar.py
示例6: __new__
def __new__(cls, start, end, left_open=False, right_open=False):
start = _sympify(start)
end = _sympify(end)
# Only allow real intervals (use symbols with 'is_real=True').
if not start.is_real or not end.is_real:
raise ValueError("Only real intervals are supported")
# Make sure that the created interval will be valid.
if end.is_comparable and start.is_comparable:
if end < start:
return S.EmptySet
if end == start and (left_open or right_open):
return S.EmptySet
if end == start and not (left_open or right_open):
return FiniteSet(end)
# Make sure infinite interval end points are open.
if start == S.NegativeInfinity:
left_open = True
if end == S.Infinity:
right_open = True
return Basic.__new__(cls, start, end, left_open, right_open)
开发者ID:piyushbansal,项目名称:sympy,代码行数:26,代码来源:sets.py
示例7: __new__
def __new__(cls, name, index, system, pretty_str, latex_str):
from sympy.vector.coordsysrect import CoordSys3D
if isinstance(name, Symbol):
name = name.name
if isinstance(pretty_str, Symbol):
pretty_str = pretty_str.name
if isinstance(latex_str, Symbol):
latex_str = latex_str.name
index = _sympify(index)
system = _sympify(system)
obj = super(BaseScalar, cls).__new__(cls, Symbol(name), index, system,
Symbol(pretty_str),
Symbol(latex_str))
if not isinstance(system, CoordSys3D):
raise TypeError("system should be a CoordSys3D")
if index not in range(0, 3):
raise ValueError("Invalid index specified.")
# The _id is used for equating purposes, and for hashing
obj._id = (index, system)
obj._name = obj.name = name
obj._pretty_form = u'' + pretty_str
obj._latex_form = latex_str
obj._system = system
return obj
开发者ID:abhi98khandelwal,项目名称:sympy,代码行数:26,代码来源:scalar.py
示例8: __new__
def __new__(cls, label, shape=None, **kw_args):
from sympy import MatrixBase, NDimArray
if isinstance(label, string_types):
label = Symbol(label)
elif isinstance(label, Symbol):
pass
elif isinstance(label, (MatrixBase, NDimArray)):
return label
elif isinstance(label, Iterable):
return _sympify(label)
else:
label = _sympify(label)
if is_sequence(shape):
shape = Tuple(*shape)
elif shape is not None:
shape = Tuple(shape)
offset = kw_args.pop('offset', S.Zero)
strides = kw_args.pop('strides', None)
if shape is not None:
obj = Expr.__new__(cls, label, shape)
else:
obj = Expr.__new__(cls, label)
obj._shape = shape
obj._offset = offset
obj._strides = strides
obj._name = str(label)
return obj
开发者ID:bjodah,项目名称:sympy,代码行数:31,代码来源:indexed.py
示例9: 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:SungSingSong,项目名称:sympy,代码行数:7,代码来源:test_sympify.py
示例10: __new__
def __new__(cls, lhs, op, rhs):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed)
if not isinstance(lhs, assignable):
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs don't align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
if isinstance(op, str):
op = operator(op)
elif op not in op_registry.values():
raise TypeError("Unrecognized Operator")
return Basic.__new__(cls, lhs, op, rhs)
开发者ID:jcrist,项目名称:symcc,代码行数:25,代码来源:ast.py
示例11: compare_pretty
def compare_pretty(a, b):
"""
Is a > b in the sense of ordering in printing?
THIS FUNCTION IS DEPRECATED. Use ``default_sort_key`` instead.
::
yes ..... return 1
no ...... return -1
equal ... return 0
Strategy:
It uses Basic.compare as a fallback, but improves it in many cases,
like ``x**3``, ``x**4``, ``O(x**3)`` etc. In those simple cases, it just parses the
expression and returns the "sane" ordering such as::
1 < x < x**2 < x**3 < O(x**4) etc.
Examples
========
>>> from sympy.abc import x
>>> from sympy import Basic, Number
>>> Basic._compare_pretty(x, x**2)
-1
>>> Basic._compare_pretty(x**2, x**2)
0
>>> Basic._compare_pretty(x**3, x**2)
1
>>> Basic._compare_pretty(Number(1, 2), Number(1, 3))
1
>>> Basic._compare_pretty(Number(0), Number(-1))
1
"""
try:
a = _sympify(a)
except SympifyError:
pass
try:
b = _sympify(b)
except SympifyError:
pass
# both objects are non-SymPy
if (not isinstance(a, Basic)) and (not isinstance(b, Basic)):
return cmp(a, b)
if not isinstance(a, Basic):
return -1 # other < sympy
if not isinstance(b, Basic):
return +1 # sympy > other
# now both objects are from SymPy, so we can proceed to usual comparison
return cmp(a.sort_key(), b.sort_key())
开发者ID:bladewang,项目名称:sympy,代码行数:59,代码来源:basic.py
示例12: __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
示例13: __new__
def __new__(cls, target, iter, body):
target = _sympify(target)
if not iterable(iter):
raise TypeError("iter must be an iterable")
if isinstance(iter, list):
# _sympify errors on lists because they are mutable
iter = tuple(iter)
iter = _sympify(iter)
if not isinstance(body, CodeBlock):
if not iterable(body):
raise TypeError("body must be an iterable or CodeBlock")
body = CodeBlock(*(_sympify(i) for i in body))
return Basic.__new__(cls, target, iter, body)
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:13,代码来源:ast.py
示例14: __setitem__
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableSparseNDimArray
>>> a = MutableSparseNDimArray.zeros(2, 2)
>>> a[0, 0] = 1
>>> a[1, 1] = 1
>>> a
[[1, 0], [0, 1]]
"""
index = self._parse_index(index)
if not isinstance(value, MutableNDimArray):
value = _sympify(value)
if isinstance(value, NDimArray):
return NotImplementedError
if value == 0 and index in self._sparse_array:
self._sparse_array.pop(index)
else:
self._sparse_array[index] = value
开发者ID:jarthurgross,项目名称:sympy,代码行数:26,代码来源:sparse_ndim_array.py
示例15: __new__
def __new__(cls, routine_call, idx):
if not isinstance(routine_call, RoutineCall):
raise TypeError("routine_call must be of type RoutineCall")
idx = _sympify(idx)
if isinstance(idx, Integer):
if not -1 <= idx < len(routine_call.routine.returns):
raise ValueError("idx out of bounds")
elif isinstance(idx, Symbol):
names = [a.name.name for a in routine_call.routine.inplace]
if idx not in names:
raise KeyError("unknown inplace result %s" % idx)
# Get the name of the symbol
if idx == -1:
expr = routine_call.routine.returns[0].expr
elif isinstance(idx, Integer):
expr = routine_call.routine.returns[idx].expr
else:
inp = routine_call.routine.inplace
expr = [i.expr for i in inp if idx == i.name.name][0]
# Sub in values to expression
args = [i.name for i in routine_call.routine.arguments]
values = [i for i in routine_call.arguments]
expr = expr.subs(dict(zip(args, values)))
# Create the object
s = cls._alias_type.__new__(cls, routine_call, idx)
s._expr = expr
cls._alias_assumptions(s, expr)
return s
开发者ID:gitter-badger,项目名称:symcc,代码行数:28,代码来源:routines.py
示例16: __contains__
def __contains__(self, other):
"""
Returns True if other is contained in self, where other
belongs to extended real numbers, False if not contained,
otherwise TypeError is raised.
Examples
========
>>> from sympy import AccumBounds, oo
>>> 1 in AccumBounds(-1, 3)
True
-oo and oo go together as limits (in AccumulationBounds).
>>> -oo in AccumBounds(1, oo)
True
>>> oo in AccumBounds(-oo, 0)
True
"""
other = _sympify(other)
if not (other.is_Symbol or other.is_number):
raise TypeError("Input of type real symbol or Number expected")
if other is S.Infinity or other is S.NegativeInfinity:
if self.min is S.NegativeInfinity or self.max is S.Infinity:
return True
return False
return And(self.min <= other and self.max >= other)
开发者ID:tclose,项目名称:sympy,代码行数:32,代码来源:util.py
示例17: __eq__
def __eq__(self, other):
"""a == b -> Compare two symbolic trees and see whether they are equal
this is the same as:
a.compare(b) == 0
but faster
"""
if type(self) is not type(other):
# issue 3001 a**1.0 == a like a**2.0 == a**2
while isinstance(self, C.Pow) and self.exp == 1:
self = self.base
while isinstance(other, C.Pow) and other.exp == 1:
other = other.base
try:
other = _sympify(other)
except SympifyError:
return False # sympy != other
if type(self) is not type(other):
return False
return self._hashable_content() == other._hashable_content()
开发者ID:rishabh11,项目名称:sympy,代码行数:25,代码来源:basic.py
示例18: __setitem__
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableSparseNDimArray
>>> a = MutableSparseNDimArray.zeros(2, 2)
>>> a[0, 0] = 1
>>> a[1, 1] = 1
>>> a
[[1, 0], [0, 1]]
"""
if isinstance(index, tuple) and any([isinstance(i, slice) for i in index]):
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
for i in eindices:
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
other_value = value[other_i]
complete_index = self._parse_index(i)
if other_value != 0:
self._sparse_array[complete_index] = other_value
elif complete_index in self._sparse_array:
self._sparse_array.pop(complete_index)
else:
index = self._parse_index(index)
value = _sympify(value)
if value == 0 and index in self._sparse_array:
self._sparse_array.pop(index)
else:
self._sparse_array[index] = value
开发者ID:cmarqu,项目名称:sympy,代码行数:30,代码来源:sparse_ndim_array.py
示例19: _contains
def _contains(self, other):
if (((self.start - other)/self.step).is_integer or
((self.stop - other)/self.step).is_integer):
return _sympify(other >= self.inf and other <= self.sup)
elif (((self.start - other)/self.step).is_integer is False and
((self.stop - other)/self.step).is_integer is False):
return S.false
开发者ID:atsao72,项目名称:sympy,代码行数:7,代码来源:fancysets.py
示例20: __new__
def __new__(cls, *args, **options):
args = [_sympify(arg) for arg in args]
argset = multiset(args) # dictionary
args_final=[]
# xor is commutative and is false if count of x is even and x
# if count of x is odd. Here x can be True, False or any Symbols
for x, freq in argset.items():
if freq % 2 == 0:
argset[x] = false
else:
argset[x] = x
for _, z in argset.items():
args_final.append(z)
argset = set(args_final)
truecount = 0
for x in args:
if isinstance(x, Number) or x in [True, False]: # Includes 0, 1
argset.discard(x)
if x:
truecount += 1
if len(argset) < 1:
return true if truecount % 2 != 0 else false
if truecount % 2 != 0:
return Not(Xor(*argset))
_args = frozenset(argset)
obj = super(Xor, cls).__new__(cls, *_args, **options)
if isinstance(obj, Xor):
obj._argset = _args
return obj
开发者ID:JiraiyaGerotora,项目名称:sympy,代码行数:29,代码来源:boolalg.py
注:本文中的sympy.core.sympify._sympify函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论