本文整理汇总了Python中sympify.sympify函数的典型用法代码示例。如果您正苦于以下问题:Python sympify函数的具体用法?Python sympify怎么用?Python sympify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sympify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _symbolgen
def _symbolgen(*symbols):
"""
Generator of all symbols in the argument of the Derivative.
Example:
>> ._symbolgen(x, 3, y)
(x, x, x, y)
>> ._symbolgen(x, 10**6)
(x, x, x, x, x, x, x, ...)
The second example shows why we don't return a list, but a generator,
so that the code that calls _symbolgen can return earlier for special
cases, like x.diff(x, 10**6).
"""
last_s = sympify(symbols[len(symbols)-1])
for i in xrange(len(symbols)):
s = sympify(symbols[i])
next_s = None
if s != last_s:
next_s = sympify(symbols[i+1])
if isinstance(s, Integer):
continue
elif isinstance(s, Symbol):
# handle cases like (x, 3)
if isinstance(next_s, Integer):
# yield (x, x, x)
for copy_s in repeat(s,int(next_s)):
yield copy_s
else:
yield s
else:
yield s
示例2: series
def series(self, x, point=0, n=6, dir="+"):
"""
Series expansion of "self" around "point".
Usage:
Returns the Taylor (Laurent or generalized) series of "self" around
the point "point" (default 0) with respect to "x" until the n-th
term (default n is 6).
For dir="+" (default) it calculates the series from the right
and for dir="-" the series from the left.
For smooth functions this argument doesn't matter.
Notes:
This method is the most high level method and it returns the
series including the O(x**n) term.
Internally, it executes a method nseries(), see nseries() docstring
for more information.
"""
x = sympify(x)
point = sympify(point)
if dir == "+":
return self.nseries(x, point, n)
elif dir == "-":
return self.subs(x, -x).nseries(x, -point, n).subs(x, -x)
else:
raise ValueError("Dir has to be '+' or '-'")
示例3: __new__
def __new__(cls, expr, *symbols, **assumptions):
expr = sympify(expr)
if not symbols: return expr
symbols = Derivative._symbolgen(*symbols)
if expr.is_commutative:
assumptions["commutative"] = True
if "evaluate" in assumptions:
evaluate = assumptions["evaluate"]
del assumptions["evaluate"]
else:
evaluate = False
if not evaluate and not isinstance(expr, Derivative):
obj = Basic.__new__(cls, expr, *symbols, **assumptions)
return obj
unevaluated_symbols = []
for s in symbols:
s = sympify(s)
if not isinstance(s, Symbol):
raise ValueError('Invalid literal: %s is not a valid variable' % s)
if not expr.has(s):
return S.Zero
obj = expr._eval_derivative(s)
if obj is None:
unevaluated_symbols.append(s)
elif obj is S.Zero:
return S.Zero
else:
expr = obj
if not unevaluated_symbols:
return expr
return Basic.__new__(cls, expr, *unevaluated_symbols, **assumptions)
示例4: __new__
def __new__(cls, expr, variables, point, **assumptions):
if not ordered_iter(variables, Tuple):
variables = [variables]
variables = Tuple(*sympify(variables))
if uniq(variables) != variables:
repeated = repeated = [ v for v in set(variables)
if list(variables).count(v) > 1 ]
raise ValueError('cannot substitute expressions %s more than '
'once.' % repeated)
if not ordered_iter(point, Tuple):
point = [point]
point = Tuple(*sympify(point))
if len(point) != len(variables):
raise ValueError('Number of point values must be the same as '
'the number of variables.')
# it's necessary to use dummy variables internally
new_variables = Tuple(*[ arg.as_dummy() if arg.is_Symbol else
C.Dummy(str(arg)) for arg in variables ])
expr = sympify(expr).subs(tuple(zip(variables, new_variables)))
if expr.is_commutative:
assumptions['commutative'] = True
obj = Expr.__new__(cls, expr, new_variables, point, **assumptions)
return obj
示例5: __new__
def __new__(cls, expr, *symbols, **assumptions):
expr = sympify(expr)
if not symbols:
return expr
symbols = Derivative._symbolgen(*symbols)
if expr.is_commutative:
assumptions['commutative'] = True
evaluate = assumptions.pop('evaluate', False)
if not evaluate and not isinstance(expr, Derivative):
symbols = list(symbols)
if len(symbols) == 0:
# We make a special case for 0th derivative, because there
# is no good way to unambiguously print this.
return expr
obj = Expr.__new__(cls, expr, *symbols, **assumptions)
return obj
unevaluated_symbols = []
for s in symbols:
s = sympify(s)
if not isinstance(s, C.Symbol):
raise ValueError('Invalid literal: %s is not a valid variable' % s)
obj = expr._eval_derivative(s)
if obj is None:
unevaluated_symbols.append(s)
elif obj is S.Zero:
return S.Zero
else:
expr = obj
if not unevaluated_symbols:
return expr
return Expr.__new__(cls, expr, *unevaluated_symbols, **assumptions)
示例6: as_leading_term
def as_leading_term(self, *symbols):
"""
Returns the leading term.
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).as_leading_term(x)
1
>>> (1/x**2+x+x**2).as_leading_term(x)
x**(-2)
Note:
self is assumed to be the result returned by Basic.series().
"""
from sympy import powsimp
if len(symbols)>1:
c = self
for x in symbols:
c = c.as_leading_term(x)
return c
elif not symbols:
return self
x = sympify(symbols[0])
assert x.is_Symbol, `x`
if not self.has(x):
return self
obj = self._eval_as_leading_term(x)
if obj is not None:
return powsimp(obj, deep=True, combine='exp')
raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
示例7: _has
def _has(p):
p = sympify(p)
if isinstance(p, BasicType):
return search(self, lambda w: isinstance(w, p), lambda w: True)
if p.is_Atom and not isinstance(p, Wild):
return search(self, lambda w: isinstance(w, p.func), lambda w: w in [p])
return search(self, lambda w: p.matches(w) is not None, lambda w: True)
示例8: has
def has(self, *patterns):
"""
Return True if self has any of the patterns.
Example:
>>> from sympy.abc import x
>>> (2*x).has(x)
True
>>> (2*x/x).has(x)
False
"""
from sympy.utilities.iterables import flatten
from sympy.core.symbol import Wild
if len(patterns)>1:
for p in patterns:
if self.has(p):
return True
return False
elif not patterns:
raise TypeError("has() requires at least 1 argument (got none)")
p = sympify(patterns[0])
if isinstance(p, BasicType):
return bool(self.atoms(p))
if p.is_Atom and not isinstance(p, Wild):
return p in self.atoms(p.func)
if p.matches(self) is not None:
return True
for e in flatten(self.args):
if isinstance(e, Basic) and e.has(p):
return True
return False
示例9: find
def find(self, query, group=False):
"""Find all subexpressions matching a query. """
if not callable(query):
query = sympify(query)
if isinstance(query, type):
_query = lambda expr: isinstance(expr, query)
elif isinstance(query, Basic):
_query = lambda expr: expr.match(query)
else:
_query = query
results = []
def rec_find(expr):
q = _query(expr)
if q or q == {}:
results.append(expr)
for arg in expr.args:
rec_find(arg)
rec_find(self)
if not group:
return set(results)
else:
groups = {}
for result in results:
if result in groups:
groups[result] += 1
else:
groups[result] = 1
return groups
示例10: matches
def matches(self, expr, repl_dict={}, evaluate=False):
"""
Helper method for match() - switches the pattern and expr.
Can be used to solve linear equations:
>>> from sympy import Symbol, Wild, Integer
>>> a,b = map(Symbol, 'ab')
>>> x = Wild('x')
>>> (a+b*x).matches(Integer(0))
{x_: -a/b}
"""
if evaluate:
return self.subs(repl_dict).matches(expr, repl_dict)
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if self == expr:
return repl_dict
if len(self.args) != len(expr.args):
return None
d = repl_dict.copy()
for arg, other_arg in zip(self.args, expr.args):
if arg == other_arg:
continue
d = arg.subs(d).matches(other_arg, d)
if d is None:
return None
return d
示例11: match
def match(self, pattern):
"""
Pattern matching.
Wild symbols match all.
Return None when expression (self) does not match
with pattern. Otherwise return a dictionary such that
pattern.subs(self.match(pattern)) == self
Example:
>>> from sympy import symbols, Wild
>>> from sympy.abc import x, y
>>> p = Wild("p")
>>> q = Wild("q")
>>> r = Wild("r")
>>> e = (x+y)**(x+y)
>>> e.match(p**p)
{p_: x + y}
>>> e.match(p**q)
{p_: x + y, q_: x + y}
>>> e = (2*x)**2
>>> e.match(p*q**r)
{p_: 4, q_: x, r_: 2}
>>> (p*q**r).subs(e.match(p*q**r))
4*x**2
"""
pattern = sympify(pattern)
return pattern.matches(self)
示例12: __new__
def __new__(cls, name, exclude=(), properties=(), **assumptions):
exclude = tuple([sympify(x) for x in exclude])
properties = tuple(properties)
is_commutative = fuzzy_bool(assumptions.get("commutative", True))
if is_commutative is None:
raise ValueError("""Wild's commutativity must be True or False.""")
assumptions["commutative"] = is_commutative
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
示例13: taylor_term
def taylor_term(cls, n, x, *previous_terms):
"""General method for the taylor term.
This method is slow, because it differentiates n-times. Subclasses can
redefine it to make it faster by using the "previous_terms".
"""
x = sympify(x)
return cls(x).diff(x, n).subs(x, 0) * x**n / C.Factorial(n)
示例14: __sympifyit_wrapper
def __sympifyit_wrapper(a, b):
try:
# If an external class has _op_priority, it knows how to deal
# with sympy objects. Otherwise, it must be converted.
if not hasattr(b, '_op_priority'):
b = sympify(b, strict=True)
return func(a, b)
except SympifyError:
return retval
示例15: _matches
def _matches(self, expr, repl_dict={}):
# weed out negative one prefixes
sign = 1
a, b = self.as_two_terms()
if a is S.NegativeOne:
if b.is_Mul:
sign = -sign
else:
# the remainder, b, is not a Mul anymore
return b.matches(-expr, repl_dict)
expr = sympify(expr)
if expr.is_Mul and expr.args[0] is S.NegativeOne:
expr = -expr
sign = -sign
if not expr.is_Mul:
# expr can only match if it matches b and a matches +/- 1
if len(self.args) == 2:
# quickly test for equality
if b == expr:
return a.matches(Rational(sign), repl_dict)
# do more expensive match
dd = b.matches(expr, repl_dict)
if dd == None:
return None
dd = a.matches(Rational(sign), dd)
return dd
return None
d = repl_dict.copy()
# weed out identical terms
pp = list(self.args)
ee = list(expr.args)
for p in self.args:
if p in expr.args:
ee.remove(p)
pp.remove(p)
# only one symbol left in pattern -> match the remaining expression
if len(pp) == 1 and isinstance(pp[0], C.Wild):
if len(ee) == 1:
d[pp[0]] = sign * ee[0]
else:
d[pp[0]] = sign * expr.func(*ee)
return d
if len(ee) != len(pp):
return None
for p, e in zip(pp, ee):
d = p.xreplace(d).matches(e, d)
if d is None:
return None
return d