核心#
同情#
- sympy.core.sympify.sympify(a, locals=None, convert_xor=True, strict=False, rational=False, evaluate=None)[源代码]#
将任意表达式转换为可在SymPy中使用的类型。
- 参数:
a :
任何在SymPy中定义的对象
standard numeric Python types:
int
,long
,float
,Decimal
strings (like
"0.09"
,"2e-19"
or'sin(x)'
)布尔人,包括
None
(将离开None
不变)dicts, lists, sets or tuples containing any of the above
convert_xor : bool, optional
If true, treats
^
as exponentiation. If False, treats^
as XOR itself. Used only when input is a string.当地人 :在SymPy中定义的任何对象,可选
为了识别字符串,可以将其导入命名空间字典并作为局部变量传递。
严格的 :bool,可选
If the option strict is set to
True
, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.理性的 :bool,可选
If
True
, converts floats intoRational
. IfFalse
, it lets floats remain as it is. Used only when input is a string.评价 :bool,可选
如果为False,则算术和运算符将转换为它们的SymPy等价物。如果为True,将计算表达式并返回结果。
解释
It will convert Python ints into instances of
Integer
, floats into instances ofFloat
, etc. It is also able to coerce symbolic expressions which inherit fromBasic
. This can be useful in cooperation with SAGE.警告
请注意,此函数使用
eval
,因此不应用于未初始化的输入。如果参数已经是SymPy能够理解的类型,那么它将只返回该值。这可以在函数的开头使用,以确保使用的是正确的类型。
实例
>>> from sympy import sympify
>>> sympify(2).is_integer True >>> sympify(2).is_real True
>>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e-45").is_real True
如果无法转换表达式,则会引发一个交感错误。
>>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse 'x***2'"
When attempting to parse non-Python syntax using
sympify
, it raises aSympifyError
:>>> sympify("2x+1") Traceback (most recent call last): ... SympifyError: Sympify of expression 'could not parse '2x+1'' failed
To parse non-Python syntax, use
parse_expr
fromsympy.parsing.sympy_parser
.>>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("2x+1", transformations="all") 2*x + 1
For more details about
transformations
: seeparse_expr()
当地人
The sympification happens with access to everything that is loaded by
from sympy import *
; anything used in a string that is not defined by that import will be converted to a symbol. In the following, thebitcount
function is treated as a symbol and theO
is interpreted as theOrder
object (used with series) and it raises an error when used improperly:>>> s = 'bitcount(42)' >>> sympify(s) bitcount(42) >>> sympify("O(x)") O(x) >>> sympify("O + 1") Traceback (most recent call last): ... TypeError: unbound method...
为了拥有
bitcount
可以将其导入命名空间字典并作为局部变量传递:>>> ns = {} >>> exec('from sympy.core.evalf import bitcount', ns) >>> sympify(s, locals=ns) 6
为了拥有
O
解释为符号,在名称空间字典中标识它。这可以通过多种方式实现;以下三种方法都是可行的:>>> from sympy import Symbol >>> ns["O"] = Symbol("O") # method 1 >>> exec('from sympy.abc import O', ns) # method 2 >>> ns.update(dict(O=Symbol("O"))) # method 3 >>> sympify("O + 1", locals=ns) O + 1
If you want all single-letter and Greek-letter variables to be symbols then you can use the clashing-symbols dictionaries that have been defined there as private variables:
_clash1
(single-letter variables),_clash2
(the multi-letter Greek names) or_clash
(both single and multi-letter names that are defined inabc
).>>> from sympy.abc import _clash1 >>> set(_clash1) # if this fails, see issue #23903 {'E', 'I', 'N', 'O', 'Q', 'S'} >>> sympify('I & Q', _clash1) I & Q
严格的
如果选择
strict
设置为True
,仅转换已定义显式转换的类型。在其他情况下,会引发SympifyError。>>> print(sympify(None)) None >>> sympify(None, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: None
自 1.6 版本弃用:
sympify(obj)
automatically falls back tostr(obj)
when all other conversion methods fail, but this is deprecated.strict=True
will disable this deprecated behavior. See The string fallback in sympify().评价
If the option
evaluate
is set toFalse
, then arithmetic and operators will be converted into their SymPy equivalents and theevaluate=False
option will be added. NestedAdd
orMul
will be denested first. This is done via an AST transformation that replaces operators with their SymPy equivalents, so if an operand redefines any of those operations, the redefined operators will not be used. If argument a is not a string, the mathematical expression is evaluated before being passed to sympify, so addingevaluate=False
will still return the evaluated result of expression.>>> sympify('2**2 / 3 + 5') 19/3 >>> sympify('2**2 / 3 + 5', evaluate=False) 2**2/3 + 5 >>> sympify('4/2+7', evaluate=True) 9 >>> sympify('4/2+7', evaluate=False) 4/2 + 7 >>> sympify(4/2+7, evaluate=False) 9.00000000000000
延伸
延伸
sympify
转换自定义对象(不是从Basic
),只需定义一个_sympy_
方法。您甚至可以通过在运行时子类化或添加方法来对不属于自己的类执行此操作。>>> from sympy import Matrix >>> class MyList1(object): ... def __iter__(self): ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] ... def _sympy_(self): return Matrix(self) >>> sympify(MyList1()) Matrix([ [1], [2]])
如果不能控制类定义,也可以使用
converter
全球词典。键是类,值是一个接受单个参数并返回所需的SymPy对象的函数,例如。converter[MyList] = lambda x: Matrix(x)
.>>> class MyList2(object): # XXX Do not do this if you control the class! ... def __iter__(self): # Use _sympy_! ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] >>> from sympy.core.sympify import converter >>> converter[MyList2] = lambda x: Matrix(x) >>> sympify(MyList2()) Matrix([ [1], [2]])
笔记
关键词
rational
和convert_xor
仅当输入为字符串时使用。Convert_xor
>>> sympify('x^y',convert_xor=True) x**y >>> sympify('x^y',convert_xor=False) x ^ y
理性的
>>> sympify('0.1',rational=False) 0.1 >>> sympify('0.1',rational=True) 1/10
Sometimes autosimplification during sympification results in expressions that are very different in structure than what was entered. Until such autosimplification is no longer done, the
kernS
function might be of some use. In the example below you can see how an expression reduces to \(-1\) by autosimplification, but does not do so whenkernS
is used.>>> from sympy.core.sympify import kernS >>> from sympy.abc import x >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1 -1 >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1' >>> sympify(s) -1 >>> kernS(s) -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
假设#
This module contains the machinery handling assumptions. Do also consider the guide Assumptions.
All symbolic objects have assumption attributes that can be accessed via
.is_<assumption name>
attribute.
Assumptions determine certain properties of symbolic objects and can
have 3 possible values: True
, False
, None
. True
is returned if the
object has the property and False
is returned if it does not or cannot
(i.e. does not make sense):
>>> from sympy import I
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False
When the property cannot be determined (or when a method is not
implemented) None
will be returned. For example, a generic symbol, x
,
may or may not be positive so a value of None
is returned for x.is_positive
.
默认情况下,所有符号值都在给定上下文中的最大集合中,而不指定属性。例如,一个具有整数属性的符号也是实的、复杂的等等。
以下是可能的假设名称列表:
- 交换的#
object commutes with any other object with respect to multiplication operation. See [12].
- 复杂的#
object can have only values from the set of complex numbers. See [13].
- 想像的#
object value is a number that can be written as a real number multiplied by the imaginary unit
I
. See [R112]. Please note that0
is not considered to be an imaginary number, see issue #7649.- 真实的#
对象只能有实数集合中的值。
- extended_real#
object can have only values from the set of real numbers,
oo
and-oo
.- 整数#
对象只能有整数集中的值。
- 古怪的#
- 即使#
object can have only values from the set of odd (even) integers [R111].
- 首要的#
object is a natural number greater than 1 that has no positive divisors other than 1 and itself. See [R115].
- 混合成的#
object is a positive integer that has at least one positive divisor other than 1 or the number itself. See [R113].
- 零#
object has the value of 0.
- 非零#
对象是一个不为零的实数。
- 理性的#
对象只能有来自有理数集的值。
- 代数的#
对象只能有代数数集合中的值 [11].
- 超验的#
对象只能具有先验数集中的值 [10].
- 不合理的#
object value cannot be represented exactly by
Rational
, see [R114].- 有限的#
- 无限的#
object absolute value is bounded (arbitrarily large). See [R116], [R117], [R118].
- 负面#
- 非阴性#
object can have only negative (nonnegative) values [R110].
- 积极的#
- 非阳性#
object can have only positive (nonpositive) values.
- extended_negative#
- extended_nonnegative#
- extended_positive#
- extended_nonpositive#
- extended_nonzero#
as without the extended part, but also including infinity with corresponding sign, e.g., extended_positive includes
oo
- 埃尔米特#
- 抗热剂#
object belongs to the field of Hermitian (antihermitian) operators.
实例#
>>> from sympy import Symbol
>>> x = Symbol('x', real=True); x
x
>>> x.is_real
True
>>> x.is_complex
True
也见#
笔记#
任何sypy表达式的完全解析假设可以得到如下:
>>> from sympy.core.assumptions import assumptions
>>> x = Symbol('x',positive=True)
>>> assumptions(x + I)
{'commutative': True, 'complex': True, 'composite': False, 'even':
False, 'extended_negative': False, 'extended_nonnegative': False,
'extended_nonpositive': False, 'extended_nonzero': False,
'extended_positive': False, 'extended_real': False, 'finite': True,
'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
False, 'negative': False, 'noninteger': False, 'nonnegative': False,
'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
False, 'prime': False, 'rational': False, 'real': False, 'zero':
False}
开发者注意事项#
当前值(可能不完整)存储在 obj._assumptions dictionary
;对getter方法(使用属性修饰符)或对象/类的属性的查询将返回值并更新字典。
>>> eq = x**2 + I
>>> eq._assumptions
{}
>>> eq.is_finite
True
>>> eq._assumptions
{'finite': True, 'infinite': False}
For a Symbol
, there are two locations for assumptions that may
be of interest. The assumptions0
attribute gives the full set of
assumptions derived from a given set of initial assumptions. The
latter assumptions are stored as Symbol._assumptions_orig
>>> Symbol('x', prime=True, even=True)._assumptions_orig
{'even': True, 'prime': True}
The _assumptions_orig
are not necessarily canonical nor are they filtered
in any way: they records the assumptions used to instantiate a Symbol and (for
storage purposes) represent a more compact representation of the assumptions
needed to recreate the full set in Symbol.assumptions0
.
工具书类#
隐藏物#
- sympy.core.cache.__cacheit(maxsize)[源代码]#
缓存装饰器。
重要提示:缓存函数的结果必须是 不变的
实例
>>> from sympy import cacheit >>> @cacheit ... def f(a, b): ... return a+b
>>> @cacheit ... def f(a, b): # noqa: F811 ... return [a, b] # <-- WRONG, returns mutable object
若要强制cacheit检查返回结果的可变性和一致性,请将环境变量SYMPY_USE_CACHE设置为“debug”
基本的#
- class sympy.core.basic.Basic(*args)[源代码]#
所有sypy对象的基类。
注释和惯例
总是使用
.args
,访问某个实例的参数时:
>>> from sympy import cot >>> from sympy.abc import x, y
>>> cot(x).args (x,)
>>> cot(x).args[0] x
>>> (x*y).args (x, y)
>>> (x*y).args[1] y
不要使用内部方法或变量(前缀为
_
):
>>> cot(x)._args # do not use this, use cot(x).args instead (x,)
“SymPy object”是指可以通过
sympify
. 但并不是所有使用SymPy遇到的对象都是Basic的子类。例如,可变对象不是:>>> from sympy import Basic, Matrix, sympify >>> A = Matrix([[1, 2], [3, 4]]).as_mutable() >>> isinstance(A, Basic) False
>>> B = sympify(A) >>> isinstance(B, Basic) True
- property args: tuple[Basic, ...]#
返回“self”参数的元组。
实例
>>> from sympy import cot >>> from sympy.abc import x, y
>>> cot(x).args (x,)
>>> cot(x).args[0] x
>>> (x*y).args (x, y)
>>> (x*y).args[1] y
笔记
Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Do not override .args() from Basic (so that it is easy to change the interface in the future if needed).
- as_dummy()[源代码]#
返回表达式,其中任何对象的结构绑定符号替换为对象中出现的唯一规范符号,并且只有交换性为真的默认假设。当应用于符号时,只有相同交换性的新符号将被返回。
实例
>>> from sympy import Integral, Symbol >>> from sympy.abc import x >>> r = Symbol('r', real=True) >>> Integral(r, (r, x)).as_dummy() Integral(_0, (_0, x)) >>> _.variables[0].is_real is None True >>> r.as_dummy() _r
笔记
任何在结构上绑定变量的对象都应该有一个属性, \(bound_symbols\) 返回对象中出现的那些符号。
- property assumptions0#
返回对象 \(type\) 假设。
例如:
符号('x',real=True)符号('x',integer=True)
是不同的对象。换句话说,除了Python类型(在本例中是Symbol),初始假设也在形成它们的typeinfo。
实例
>>> from sympy import Symbol >>> from sympy.abc import x >>> x.assumptions0 {'commutative': True} >>> x = Symbol("x", positive=True) >>> x.assumptions0 {'commutative': True, 'complex': True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False}
- atoms(*types)[源代码]#
返回构成当前对象的原子。
By default, only objects that are truly atomic and cannot be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below.
实例
>>> from sympy import I, pi, sin >>> from sympy.abc import x, y >>> (1 + x + 2*sin(y + I*pi)).atoms() {1, 2, I, pi, x, y}
如果给出一个或多个类型,结果将只包含这些类型的原子。
>>> from sympy import Number, NumberSymbol, Symbol >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol) {x, y}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number) {1, 2}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol) {1, 2, pi}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I) {1, 2, I, pi}
注意,I(虚单位)和zoo(复数无穷大)是特殊类型的数字符号,不是NumberSymbol类的一部分。
类型也可以隐式给定:
>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol {x, y}
Be careful to check your assumptions when using the implicit option since
S(1).is_Integer = True
buttype(S(1))
isOne
, a special type of SymPy atom, whiletype(S(2))
is typeInteger
and will find all integers in an expression:>>> from sympy import S >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1)) {1}
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2)) {1, 2}
Finally, arguments to atoms() can select more than atomic atoms: any SymPy type (loaded in core/__init__.py) can be listed as an argument and those types of "atoms" as found in scanning the arguments of the expression recursively:
>>> from sympy import Function, Mul >>> from sympy.core.function import AppliedUndef >>> f = Function('f') >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function) {f(x), sin(y + I*pi)} >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) {f(x)}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) {I*pi, 2*sin(y + I*pi)}
- property canonical_variables#
返回字典映射中定义的任何变量
self.bound_symbols
与表达式中的任何自由符号不冲突的符号。实例
>>> from sympy import Lambda >>> from sympy.abc import x >>> Lambda(x, 2*x).canonical_variables {x: _0}
- compare(other)[源代码]#
Return -1, 0, 1 if the object is less than, equal, or greater than other in a canonical sense. Non-Basic are always greater than Basic. If both names of the classes being compared appear in the \(ordering_of_classes\) then the ordering will depend on the appearance of the names there. If either does not appear in that list, then the comparison is based on the class name. If the names are the same then a comparison is made on the length of the hashable content. Items of the equal-lengthed contents are then successively compared using the same rules. If there is never a difference then 0 is returned.
实例
>>> from sympy.abc import x, y >>> x.compare(y) -1 >>> x.compare(x) 0 >>> y.compare(x) 1
- doit(**hints)[源代码]#
计算默认情况下未计算的对象,如极限、积分、和和和积。除非某些物种通过“提示”被排除,或者“deep”提示被设置为“False”,否则所有此类对象都将递归求值。
>>> from sympy import Integral >>> from sympy.abc import x
>>> 2*Integral(x, x) 2*Integral(x, x)
>>> (2*Integral(x, x)).doit() x**2
>>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x)
- dummy_eq(other, symbol=None)[源代码]#
比较两个表达式并处理伪符号。
实例
>>> from sympy import Dummy >>> from sympy.abc import x, y
>>> u = Dummy('u')
>>> (u**2 + 1).dummy_eq(x**2 + 1) True >>> (u**2 + 1) == (x**2 + 1) False
>>> (u**2 + y).dummy_eq(x**2 + y, x) True >>> (u**2 + y).dummy_eq(x**2 + y, y) False
- property free_symbols: set[Basic]#
从自我的原子中回归那些自由的符号。
Not all free symbols are
Symbol
. Eg: IndexedBase('I')[0].free_symbols对于大多数表达式,所有符号都是自由符号。对于某些课程来说,这是不正确的。e、 积分使用符号来表示虚拟变量,因为虚拟变量是绑定变量,所以积分有一种方法来返回除那些符号外的所有符号。导数跟踪执行导数的符号,这些符号也是绑定变量,因此它有自己的自由符号方法。
任何其他使用绑定变量的方法都应该实现一个自由的符号方法。
- classmethod fromiter(args, **assumptions)[源代码]#
从iterable创建新对象。
这是一个方便的函数,它允许从任何iterable创建对象,而不必先转换为列表或元组。
实例
>>> from sympy import Tuple >>> Tuple.fromiter(i for i in range(5)) (0, 1, 2, 3, 4)
- property func#
表达式中的顶级函数。
所有对象都应符合以下条件:
>> x == x.func(*x.args)
实例
>>> from sympy.abc import x >>> a = 2*x >>> a.func <class 'sympy.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True
- has(*patterns)[源代码]#
测试是否有任何子表达式匹配任何模式。
实例
>>> from sympy import sin >>> from sympy.abc import x, y, z >>> (x**2 + sin(x*y)).has(z) False >>> (x**2 + sin(x*y)).has(x, y, z) True >>> x.has(x) True
注意
has
是一个没有数学知识的结构化算法。考虑以下半开区间:>>> from sympy import Interval >>> i = Interval.Lopen(0, 5); i Interval.Lopen(0, 5) >>> i.args (0, 5, True, False) >>> i.has(4) # there is no "4" in the arguments False >>> i.has(0) # there *is* a "0" in the arguments True
相反,使用
contains
要确定某个数字是否在间隔内,请执行以下操作:>>> i.contains(4) True >>> i.contains(0) False
注意
expr.has(*patterns)
完全等同于any(expr.has(p) for p in patterns)
. 特别地,False
当模式列表为空时返回。>>> x.has() False
- has_free(*patterns)[源代码]#
Return True if self has object(s)
x
as a free expression else False.实例
>>> from sympy import Integral, Function >>> from sympy.abc import x, y >>> f = Function('f') >>> g = Function('g') >>> expr = Integral(f(x), (f(x), 1, g(y))) >>> expr.free_symbols {y} >>> expr.has_free(g(y)) True >>> expr.has_free(*(x, f(x))) False
This works for subexpressions and types, too:
>>> expr.has_free(g) True >>> (x + y + 1).has_free(y + 1) True
- has_xfree(s: set[Basic])[源代码]#
Return True if self has any of the patterns in s as a free argument, else False. This is like \(Basic.has_free\) but this will only report exact argument matches.
实例
>>> from sympy import Function >>> from sympy.abc import x, y >>> f = Function('f') >>> f(x).has_xfree({f}) False >>> f(x).has_xfree({f(x)}) True >>> f(x + 1).has_xfree({x}) True >>> f(x + 1).has_xfree({x + 1}) True >>> f(x + y + 1).has_xfree({x + 1}) False
- property is_comparable#
如果self可以精确计算为实数(或已经是实数),则返回True,否则返回False。
实例
>>> from sympy import exp_polar, pi, I >>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False
错误的结果并不意味着 \(self\) 不能重写成可比较的形式。例如,下面计算的差值为零,但如果不进行简化,则无法精确计算为零:
>>> e = 2**pi*(1 + 2**pi) >>> dif = e - e.expand() >>> dif.is_comparable False >>> dif.n(2)._prec 1
- is_same(b, approx=None)[源代码]#
Return True if a and b are structurally the same, else False. If \(approx\) is supplied, it will be used to test whether two numbers are the same or not. By default, only numbers of the same type will compare equal, so S.Half != Float(0.5).
实例
In SymPy (unlike Python) two numbers do not compare the same if they are not of the same type:
>>> from sympy import S >>> 2.0 == S(2) False >>> 0.5 == S.Half False
By supplying a function with which to compare two numbers, such differences can be ignored. e.g. \(equal_valued\) will return True for decimal numbers having a denominator that is a power of 2, regardless of precision.
>>> from sympy import Float >>> from sympy.core.numbers import equal_valued >>> (S.Half/4).is_same(Float(0.125, 1), equal_valued) True >>> Float(1, 2).is_same(Float(1, 10), equal_valued) True
But decimals without a power of 2 denominator will compare as not being the same.
>>> Float(0.1, 9).is_same(Float(0.1, 10), equal_valued) False
But arbitrary differences can be ignored by supplying a function to test the equivalence of two numbers:
>>> import math >>> Float(0.1, 9).is_same(Float(0.1, 10), math.isclose) True
Other objects might compare the same even though types are not the same. This routine will only return True if two expressions are identical in terms of class types.
>>> from sympy import eye, Basic >>> eye(1) == S(eye(1)) # mutable vs immutable True >>> Basic.is_same(eye(1), S(eye(1))) False
- match(pattern, old=False)[源代码]#
模式匹配。
通配符匹配所有。
返回
None
当表达式(self)与模式不匹配时。否则,这样的词典:pattern.xreplace(self.match(pattern)) == self
实例
>>> from sympy import Wild, Sum >>> 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).xreplace(e.match(p*q**r)) 4*x**2
匹配过程中忽略结构绑定符号:
>>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p))) {p_: 2}
但如果需要,可以识别:
>>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p))) {p_: 2, q_: x}
这个
old
flag将提供旧样式的模式匹配,其中表达式和模式基本上是通过求解来实现匹配的。以下两项都没有给出除非old=True
:>>> (x - 2).match(p - x, old=True) {p_: 2*x - 2} >>> (2/x).match(p*x, old=True) {p_: 2/x**2}
- matches(expr, repl_dict=None, old=False)[源代码]#
match()的帮助器方法,用于查找self中的通配符和expr中的表达式之间的匹配。
实例
>>> from sympy import symbols, Wild, Basic >>> a, b, c = symbols('a b c') >>> x = Wild('x') >>> Basic(a + x, x).matches(Basic(a + b, c)) is None True >>> Basic(a + x, x).matches(Basic(a + b + c, b + c)) {x_: b + c}
- rcall(*args)[源代码]#
通过表达式树递归地应用于参数。
This method is used to simulate a common abuse of notation for operators. For instance, in SymPy the following will not work:
(x+Lambda(y, 2*y))(z) == x+2*z
,however, you can use:
>>> from sympy import Lambda >>> from sympy.abc import x, y, z >>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z
- replace(query, value, map=False, simultaneous=True, exact=None)[源代码]#
替换匹配的子表达式
self
具有value
.If
map = True
then also return the mapping {old: new} whereold
was a sub-expression found with query andnew
is the replacement value for it. If the expression itself does not match the query, then the returned value will beself.xreplace(map)
otherwise it should beself.subs(ordered(map.items()))
.遍历表达式树并从树的底部到顶部执行匹配子表达式的替换。默认方法是同时进行替换,这样所做的更改只针对一次。如果这不是我们想要的或导致问题,
simultaneous
可以设置为False。此外,如果包含多个通配符的表达式用于匹配子表达式和
exact
flag为None它将被设置为True,因此只有当匹配模式中出现的每个通配符都接收到所有非零值时,匹配才会成功。将其设置为False将接受0的匹配;将其设置为True时,将接受其中包含0的所有匹配。注意事项见下例。下面列出了查询和替换值的可能组合:
实例
初始设置
>>> from sympy import log, sin, cos, tan, Wild, Mul, Add >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2))
- 1.1条。类型->类型
目标替换(类型,新型)
当对象类型
type
,将其替换为将其参数传递给的结果newtype
.>>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> (x*y).replace(Mul, Add) x + y
- 1.2条。类型->功能
目标替换(类型,功能)
当对象类型
type
找到了,申请func
对其论点。func
必须写入以处理type
.>>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y)
- 2.1条。模式->表达式
目标替换(pattern(野生),expr(野生)
替换匹配的子表达式
pattern
用狂野的符号来表达pattern
.>>> a, b = map(Wild, 'ab') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y
使用多个通配符时,默认情况下匹配是精确的:除非匹配为所有通配符提供非零值,否则匹配失败:
>>> (2*x + y).replace(a*x + b, b - a) y - 2 >>> (2*x).replace(a*x + b, b - a) 2*x
非直观结果设置为假时:
>>> (2*x).replace(a*x + b, b - a, exact=False) 2/x
- 2.2条。模式->功能
目标替换(pattern(野生),lambda wild:expr(wild))
所有行为都与2.1中的相同,但现在使用的是模式变量的函数,而不是表达式:
>>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2))
- 3.1条。函数->函数
目标替换(过滤器,功能)
替换子表达式
e
具有func(e)
如果filter(e)
是True。>>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9)
表达式本身也是查询的目标,但以这样一种方式进行,即不会进行两次更改。
>>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1)
当匹配单个符号时, \(exact\) 将默认为True,但这可能是也可能不是所需的行为:
在这里,我们想要 \(exact=False\) :
>>> from sympy import Function >>> f = Function('f') >>> e = f(1) + f(0) >>> q = f(a), lambda a: f(a + 1) >>> e.replace(*q, exact=False) f(1) + f(2) >>> e.replace(*q, exact=True) f(0) + f(2)
但在这里,匹配的本质使得选择正确的设置变得很棘手:
>>> e = x**(1 + y) >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(-x - y + 1) >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(1 - y)
最好使用更精确地描述目标表达式的不同形式的查询:
>>> (1 + x**(1 + y)).replace( ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1, ... lambda x: x.base**(1 - (x.exp - 1))) ... x**(1 - y) + 1
- rewrite(*args, deep=True, **hints)[源代码]#
Rewrite self using a defined rule.
Rewriting transforms an expression to another, which is mathematically equivalent but structurally different. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function.
This method takes a pattern and a rule as positional arguments. pattern is optional parameter which defines the types of expressions that will be transformed. If it is not passed, all possible expressions will be rewritten. rule defines how the expression will be rewritten.
- 参数:
args : Expr
A rule, or pattern and rule. - pattern is a type or an iterable of types. - rule can be any object.
deep : bool, optional
If
True
, subexpressions are recursively transformed. Default isTrue
.
实例
If pattern is unspecified, all possible expressions are transformed.
>>> from sympy import cos, sin, exp, I >>> from sympy.abc import x >>> expr = cos(x) + I*sin(x) >>> expr.rewrite(exp) exp(I*x)
Pattern can be a type or an iterable of types.
>>> expr.rewrite(sin, exp) exp(I*x)/2 + cos(x) - exp(-I*x)/2 >>> expr.rewrite([cos,], exp) exp(I*x)/2 + I*sin(x) + exp(-I*x)/2 >>> expr.rewrite([cos, sin], exp) exp(I*x)
Rewriting behavior can be implemented by defining
_eval_rewrite()
method.>>> from sympy import Expr, sqrt, pi >>> class MySin(Expr): ... def _eval_rewrite(self, rule, args, **hints): ... x, = args ... if rule == cos: ... return cos(pi/2 - x, evaluate=False) ... if rule == sqrt: ... return sqrt(1 - cos(x)**2) >>> MySin(MySin(x)).rewrite(cos) cos(-cos(-x + pi/2) + pi/2) >>> MySin(x).rewrite(sqrt) sqrt(1 - cos(x)**2)
Defining
_eval_rewrite_as_[...]()
method is supported for backwards compatibility reason. This may be removed in the future and using it is discouraged.>>> class MySin(Expr): ... def _eval_rewrite_as_cos(self, *args, **hints): ... x, = args ... return cos(pi/2 - x, evaluate=False) >>> MySin(x).rewrite(cos) cos(-x + pi/2)
- sort_key(order=None)[源代码]#
返回排序键。
实例
>>> from sympy import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key()) [1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]") [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
- subs(*args, **kwargs)[源代码]#
在对args进行共化后,在表达式中以旧代新。
- \(args\) 是:
两个论点,例如。食品添加剂(旧的,新的)
- 一个合理的论点,例如。食品添加剂(相当于)。iterable可能是
- o一个包含(旧的、新的)对的iterable容器。在这种情况下
替换按照给定的顺序进行处理,连续的模式可能会影响已经进行的替换。
- o其键/值项对应于旧/新对的字典或集合。
在这种情况下,旧/新对将按运算计数排序,如果是平局,则按参数数和默认的“排序”键排序。结果排序后的列表将作为iterable容器处理(参见前面的)。
如果关键字
simultaneous
为True,则在完成所有替换之前不会计算子表达式。实例
>>> from sympy import pi, exp, limit, oo >>> from sympy.abc import x, y >>> (1 + x*y).subs(x, pi) pi*y + 1 >>> (1 + x*y).subs({x:pi, y:2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2
>>> (x**2 + x**4).subs(x**2, y) y**2 + y
只替换x 2但不是x 4、使用xreplace:
>>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y
若要延迟求值,直到完成所有替换,请设置关键字
simultaneous
为真:>>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan
这还增加了一个特点,即不允许后续替换影响已经进行的替换:
>>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y)
为了获得规范结果,无序iterables按count_uOP长度、参数数和默认的u sort_u键来排序,以打破任何联系。所有其他的不可分割的东西都没有分类。
>>> from sympy import sqrt, sin, cos >>> from sympy.abc import a, b, c, d, e
>>> A = (sqrt(sin(2*x)), a) >>> B = (sin(2*x), b) >>> C = (cos(2*x), c) >>> D = (x, d) >>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs(dict([A, B, C, D, E])) a*c*sin(d*e) + b
结果表达式表示用新参数对旧参数进行文字替换。这可能不反映表达式的限制行为:
>>> (x**3 - 3*x).subs({x: oo}) nan
>>> limit(x**3 - 3*x, x, oo) oo
如果替换之后将进行数值计算,则最好将代换传递给evalf as
>>> (1/x).evalf(subs={x: 3.0}, n=21) 0.333333333333333333333
而不是
>>> (1/x).subs({x: 3.0}).evalf(21) 0.333333333333333314830
因为前者将确保获得所需的精度水平。
参见
replace
能够执行通配符匹配、匹配解析和条件替换的替换
xreplace
表达式树中精确的节点替换;也可以使用匹配规则
sympy.core.evalf.EvalfMixin.evalf
将给定公式计算到所需的精度
- xreplace(rule)[源代码]#
替换表达式中对象的引用。
- 参数:
rule :dict样
表示替换规则
- 返回:
X更换 :更换结果
实例
>>> from sympy import symbols, pi, exp >>> x, y, z = symbols('x y z') >>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi
仅当表达式树中的整个节点匹配时才会进行替换:
>>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) x + exp(y) + 2
xreplace does not differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:
>>> from sympy import Integral >>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y))
试图用表达式替换x会引发错误:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) ValueError: Invalid limits given: ((2*y, 1, 4*y),)
独生子女#
- class sympy.core.singleton.SingletonRegistry[源代码]#
单例类的注册表(作为
S
)解释
这个类充当两个独立的东西。
首先是
SingletonRegistry
. SymPy中的几个类经常出现,以致于它们都是单音化的,也就是说,使用一些元编程使它们只能实例化一次(参见sympy.core.singleton.Singleton
类获取详细信息)。例如,每次创建Integer(0)
,这将返回相同的实例,sympy.core.numbers.Zero
. 所有单例实例都是S
反对,所以Integer(0)
也可以作为S.Zero
.单音化有两个优点:节省内存,并允许快速比较。它可以节省内存,因为无论在内存中表达式中出现多少次单音化对象,它们都指向内存中的同一个实例。快速比较是因为你可以使用
is
要比较Python中的精确实例(通常,需要使用==
比较事物)。is
按内存地址比较对象,速度非常快。实例
>>> from sympy import S, Integer >>> a = Integer(0) >>> a is S.Zero True
For the most part, the fact that certain objects are singletonized is an implementation detail that users should not need to worry about. In SymPy library code,
is
comparison is often used for performance purposes The primary advantage ofS
for end users is the convenient access to certain instances that are otherwise difficult to type, likeS.Half
(instead ofRational(1, 2)
).使用时
is
比较一下,确保论点是一致的。例如,>>> x = 0 >>> x is S.Zero False
使用时,此问题不是问题
==
,建议在大多数用例中使用:>>> 0 == S.Zero True
第二件事
S
是sympy.core.sympify.sympify()
.sympy.core.sympify.sympify()
是转换Python对象的函数,例如int(1)
例如Integer(1)
. 它还将表达式的字符串形式转换为SymPy表达式,例如sympify("x**2")
>Symbol("x")**2
.S(1)
和sympify(1)
(基本上,S.__call__
已定义为调用sympify
)This is for convenience, since
S
is a single letter. It's mostly useful for defining rational numbers. Consider an expression likex + 1/2
. If you enter this directly in Python, it will evaluate the1/2
and give0.5
, because both arguments are ints (see also Two Final Notes: ^ and /). However, in SymPy, you usually want the quotient of two integers to give an exact rational number. The way Python's evaluation works, at least one side of an operator needs to be a SymPy object for the SymPy evaluation to take over. You could write this asx + Rational(1, 2)
, but this is a lot more typing. A shorter version isx + S(1)/2
. SinceS(1)
returnsInteger(1)
, the division will return aRational
type, since it will callInteger.__truediv__
, which knows how to return aRational
.
- class sympy.core.singleton.Singleton(*args, **kwargs)[源代码]#
单例类的元类。
解释
单例类只有一个实例,每次实例化该类时都会返回该实例。此外,可以通过全局注册表对象访问此实例
S
作为S.<class_name>
.实例
>>> from sympy import S, Basic >>> from sympy.core.singleton import Singleton >>> class MySingleton(Basic, metaclass=Singleton): ... pass >>> Basic() is Basic() False >>> MySingleton() is MySingleton() True >>> S.MySingleton is MySingleton() True
笔记
实例创建将延迟到第一次访问该值。在创建SymPy之前,可能会创建SymPy.0版本(在类创建期间容易导入)
EXPR#
- class sympy.core.expr.Expr(*args)[源代码]#
代数表达式的基类。
解释
所有需要定义算术运算的东西都应该是这个类的子类,而不是Basic类(Basic只能用于参数存储和表达式操作,即模式匹配、替换等)。
如果你想用等式u来比较u,那么你应该用u来代替u。_eval_is_ge如果x>=y,则返回true;如果x<y,则返回false;如果两种类型不可比较或比较不确定,则返回None
- args_cnc(cset=False, warn=True, split_1=True)[源代码]#
返回 [commutative factors, non-commutative factors] 自我的。
解释
self被视为Mul,并保持因子的顺序。如果
cset
则交换因子将在一个集合中返回。如果存在重复的因素(可能发生在未评估的Mul中),则将引发错误,除非通过设置明确抑制warn
错了。注意:除非split_1为False,否则-1总是与数字分隔开。
实例
>>> from sympy import symbols, oo >>> A, B = symbols('A B', commutative=0) >>> x, y = symbols('x y') >>> (-2*x*y).args_cnc() [[-1, 2, x, y], []] >>> (-2.5*x).args_cnc() [[-1, 2.5, x], []] >>> (-2*x*A*B*y).args_cnc() [[-1, 2, x, y], [A, B]] >>> (-2*x*A*B*y).args_cnc(split_1=False) [[-2, x, y], [A, B]] >>> (-2*x*y).args_cnc(cset=True) [{-1, 2, x, y}, []]
arg始终被视为Mul:
>>> (-2 + x + A).args_cnc() [[], [x - 2 + A]] >>> (-oo).args_cnc() # -oo is a singleton [[-1, oo], []]
- as_coeff_add(*deps) tuple[Expr, tuple[Expr, ...]] [源代码]#
返回self作为Add写入的元组(c,args),
a
.c应该是一个有理数加在任何与dep无关的Add中。
args应该是所有其他术语的元组
a
;如果self是一个数字或self独立于dep(如果给定),则args为空。This should be used when you do not know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.
如果你知道self是一个Add并且只想要头部,使用自身参数 [0] ;
if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.
如果你想把自己分成一个独立的和依赖的部分使用
self.as_independent(*deps)
>>> from sympy import S >>> from sympy.abc import x, y >>> (S(3)).as_coeff_add() (3, ()) >>> (3 + x).as_coeff_add() (3, (x,)) >>> (3 + x + y).as_coeff_add(x) (y + 3, (x,)) >>> (3 + y).as_coeff_add(x) (y + 3, ())
- as_coeff_mul(*deps, **kwargs) tuple[Expr, tuple[Expr, ...]] [源代码]#
返回将self写成Mul的元组(c,args),
m
.c应该是有理数乘以Mul中与dep无关的任何因子。
args应该是m的所有其他因子的元组;如果self是一个数字或者self独立于deps(当给定时),args为空。
This should be used when you do not know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.
如果你知道自己是一头骡子,只想要头,那就用自身参数 [0] ;
if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;
如果你想把自己分成一个独立的和依赖的部分使用
self.as_independent(*deps)
>>> from sympy import S >>> from sympy.abc import x, y >>> (S(3)).as_coeff_mul() (3, ()) >>> (3*x*y).as_coeff_mul() (3, (x, y)) >>> (3*x*y).as_coeff_mul(x) (3*y, (x,)) >>> (3*y).as_coeff_mul(x) (3*y, ())
- as_coefficient(expr)[源代码]#
在给定表达式处提取符号系数。换句话说,这个函数将“self”分解为“expr”和“expr”自由系数的乘积。如果这种分离是不可能的,它将不返回任何。
实例
>>> from sympy import E, pi, sin, I, Poly >>> from sympy.abc import x
>>> E.as_coefficient(E) 1 >>> (2*E).as_coefficient(E) 2 >>> (2*sin(E)*E).as_coefficient(E)
两个项中有E,因此返回一个和。(如果需要精确匹配E的项的系数,则可以从返回的表达式中选择常数。或者,为了获得更高的精度,可以使用Poly方法来表示所需的系数项。)
>>> (2*E + x*E).as_coefficient(E) x + 2 >>> _.args[0] # just want the exact match 2 >>> p = Poly(2*E + x*E); p Poly(x*E + 2*E, x, E, domain='ZZ') >>> p.coeff_monomial(E) 2 >>> p.nth(0, 1) 2
由于以下内容不能写成包含E作为因子的产品,因此不会返回任何结果。(如果系数
2*x
则coeff
方法。)>>> (2*E*x + x).as_coefficient(E) >>> (2*E*x + x).coeff(E) 2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I) 2 >>> (2*I).as_coefficient(pi*I)
参见
coeff
条件的返回和有一个给定的因子
as_coeff_Add
将加法常量与表达式分开
as_coeff_Mul
将乘法常数与表达式分开
as_independent
将x相关项/因子与其他项分开
sympy.polys.polytools.Poly.coeff_monomial
有效求多元单项式的单系数
sympy.polys.polytools.Poly.nth
与coeff_单项式相似,但是使用了单项式项的幂
- as_coefficients_dict(*syms)[源代码]#
Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0.
If symbols
syms
are provided, any multiplicative terms independent of them will be considered a coefficient and a regular dictionary of syms-dependent generators as keys and their corresponding coefficients as values will be returned.实例
>>> from sympy.abc import a, x, y >>> (3*x + a*x + 4).as_coefficients_dict() {1: 4, x: 3, a*x: 1} >>> _[a] 0 >>> (3*a*x).as_coefficients_dict() {a*x: 3} >>> (3*a*x).as_coefficients_dict(x) {x: 3*a} >>> (3*a*x).as_coefficients_dict(y) {1: 3*a*x}
- as_content_primitive(radical=False, clear=True)[源代码]#
这个方法应该递归地从所有参数中删除一个有理数,并返回它(内容)和新的自我(原语)。内容应始终是积极的和
Mul(*foo.as_content_primitive()) == foo
. 原语不必是规范形式,如果可能的话,应该尽量保留底层结构(即,expand_mul不应用于self)。实例
>>> from sympy import sqrt >>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
as_content_原语函数是递归的,并保留结构:
>>> eq.as_content_primitive() (2, x + 3*y*(y + 1) + 1)
整数幂函数将从基数中提取有理数:
>>> ((2 + 6*x)**2).as_content_primitive() (4, (3*x + 1)**2) >>> ((2 + 6*x)**(2*y)).as_content_primitive() (1, (2*(3*x + 1))**(2*y))
一旦添加了as_content_原语,这些术语可能最终会合并:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (11, x*(y + 1)) >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (9, x*(y + 1)) >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive() (1, 6.0*x*(y + 1) + 3*z*(y + 1)) >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() (121, x**2*(y + 1)**2) >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive() (1, 4.84*x**2*(y + 1)**2)
也可以将基元内容分解为:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))
如果clear=False(默认值为True),那么如果内容可以分布以留下一个或多个具有整数系数的项,则不会从Add中删除内容。
>>> (x/2 + y).as_content_primitive() (1/2, x + 2*y) >>> (x/2 + y).as_content_primitive(clear=False) (1, x/2 + y)
- as_expr(*gens)[源代码]#
把一个多项式转换成一个共形表达式。
实例
>>> from sympy import sin >>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y) >>> f.as_expr() x**2 + x*y
>>> sin(x).as_expr() sin(x)
- as_independent(*deps, **hint) tuple[Expr, Expr] [源代码]#
对不依赖于dep的Mul或Add-into参数的一种基本幼稚的分离。为了尽可能完整地分离变量,首先使用分离方法,例如:
separatevars()将Mul、Add和Pow(包括exp)更改为Mul
.expand(mul=True)将Add或mul更改为Add
.expand(log=True)将log expr更改为Add
这里所做的唯一非天真的事情是尊重变量的非交换顺序,并始终返回(0,0)for \(self\) 零提示。
对于非零 \(self\) ,返回的元组(i,d)有以下解释:
我将没有出现在deps中的变量
d将包含deps中的变量,或者等于0(当self是Add)或1(self是Mul时)
如果self是Add,则self=i+d
如果self是Mul,那么self=i*d
否则返回(self,S.One)或(S.One,self)。
若要强制将表达式视为Add,请将提示使用为u Add=True
实例
--自我是一种补充
>>> from sympy import sin, cos, exp >>> from sympy.abc import x, y, z
>>> (x + x*y).as_independent(x) (0, x*y + x) >>> (x + x*y).as_independent(y) (x, x*y) >>> (2*x*sin(x) + y + x + z).as_independent(x) (y + z, 2*x*sin(x) + x) >>> (2*x*sin(x) + y + x + z).as_independent(x, y) (z, 2*x*sin(x) + x + y)
--自我是一头骡子
>>> (x*sin(x)*cos(y)).as_independent(x) (cos(y), x*sin(x))
当自我是Mul时,非交换项不能总是分离出来
>>> from sympy import symbols >>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False) >>> (n1 + n1*n2).as_independent(n2) (n1, n1*n2) >>> (n2*n1 + n1*n2).as_independent(n2) (0, n1*n2 + n2*n1) >>> (n1*n2*n3).as_independent(n1) (1, n1*n2*n3) >>> (n1*n2*n3).as_independent(n2) (n1, n2*n3) >>> ((x-n1)*(x-y)).as_independent(x) (1, (x - y)*(x - n1))
--自我就是其他一切:
>>> (sin(x)).as_independent(x) (1, sin(x)) >>> (sin(x)).as_independent(y) (sin(x), 1) >>> exp(x+y).as_independent(x) (1, exp(x + y))
--强迫自己被视为附加:
>>> (3*x).as_independent(x, as_Add=True) (0, 3*x)
--强迫自己被视为Mul:
>>> (3+x).as_independent(x, as_Add=False) (1, x + 3) >>> (-3+x).as_independent(x, as_Add=False) (1, x - 3)
注意以下与上述不同之处在于使dep术语上的常数为正。
>>> (y*(-3+x)).as_independent(x) (y, x - 3)
- --请改用.as_independent()进行真正的独立性测试
的.has()。前者只考虑自由符号中的符号,后者考虑所有符号
>>> from sympy import Integral >>> I = Integral(x, (x, 1, 2)) >>> I.has(x) True >>> x in I.free_symbols False >>> I.as_independent(x) == (I, 1) True >>> (I + x).as_independent(x) == (I, x) True
注意:当尝试获取独立项时,可能需要首先使用分离方法。在这种情况下,跟踪发送到此例程的内容非常重要,这样您就知道如何解释返回的值
>>> from sympy import separatevars, log >>> separatevars(exp(x+y)).as_independent(x) (exp(y), exp(x)) >>> (x + x*y).as_independent(y) (x, x*y) >>> separatevars(x + x*y).as_independent(y) (x, y + 1) >>> (x*(1 + y)).as_independent(y) (x, y + 1) >>> (x*(1 + y)).expand(mul=True).as_independent(y) (x, x*y) >>> a, b=symbols('a b', positive=True) >>> (log(a*b).expand(log=True)).as_independent(b) (log(a), log(b))
- as_leading_term(*symbols, logx=None, cdir=0)[源代码]#
返回self级数展开的前导项(非零)。
要执行此操作,需要使用“eval”as“u leading”term例程,并且它们必须始终返回非零值。
实例
>>> 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)
- as_numer_denom()[源代码]#
Return the numerator and the denominator of an expression.
表达式->a/b->a,b
这只是一个存根,它应该由一个对象的类方法定义,以获取其他任何东西。
参见
normal
return
a/b
instead of(a, b)
- as_ordered_terms(order=None, data=False)[源代码]#
将表达式转换为有序的术语列表。
实例
>>> from sympy import sin, cos >>> from sympy.abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms() [sin(x)**2*cos(x), sin(x)**2, 1]
- as_poly(*gens, **args)[源代码]#
皈依者
self
多项式或返回None
.解释
>>> from sympy import sin >>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y)) None
- as_powers_dict()[源代码]#
把自我作为一个因素的字典返回,每个因素都被视为一种力量。关键是因子和值的基础,以及相应的指数。如果表达式是Mul且包含非交换因子,则应谨慎使用生成的字典,因为它们在字典中出现的顺序将丢失。
参见
as_ordered_factors
非交换应用程序的另一种选择,返回有序的因子列表。
args_cnc
类似于有序因子,但保证了交换因子和非交换因子的分离。
- as_real_imag(deep=True, **hints)[源代码]#
Performs complex expansion on 'self' and returns a tuple containing collected both real and imaginary parts. This method cannot be confused with re() and im() functions, which does not perform complex expansion at evaluation.
但是,可以同时扩展re()和im()函数,并获得与调用此函数完全相同的结果。
>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag() (x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag() (re(z) - im(w), re(w) + im(z))
- aseries(x=None, n=6, bound=0, hir=False)[源代码]#
自我的渐近级数展开。这相当于
self.series(x, oo, n)
.- 参数:
self :表达式
要展开其级数的表达式。
x :符号
它是要计算的表达式的变量。
n :值
The value used to represent the order in terms of
x**n
, up to which the series is to be expanded.hir :布尔值
将此参数设置为True以生成分层序列。它可以在早期停止递归,并可能提供更好和更有用的结果。
跳跃 :值,整数
使用
bound
参数来限制以其标准化形式重写系数。- 返回:
表达式
表达式的渐近级数展开。
实例
>>> from sympy import sin, exp >>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x) (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True) -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x) exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3) exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
For rational expressions this method may return original expression without the Order term. >>> (1/x).aseries(x, n=8) 1/x
笔记
该算法直接由Gruntz提供的极限计算算法推导而来。它主要使用mrv和重写子程序。该算法的总体思想是先寻找给定表达式f中变化最快的子表达式w,然后将f展开为w中的一个级数,然后对前导系数递归地做同样的事情,直到得到常数系数。
如果给定表达式f的变化最快的子表达式是f本身,则该算法将尝试找到mrv集的规范化表示,并使用该归一化表示重写f。
如果扩展包含订单项,它将是
O(x ** (-n))
或O(w ** (-n))
在哪里?w
属于变化最快的self
.参见
Expr.aseries
有关此包装器的完整详细信息,请参阅此函数的docstring。
工具书类
- coeff(x, n=1, right=False, _first=True)[源代码]#
返回包含
x**n
.如果n
等于零,则所有项都独立于x
将被退回。解释
什么时候?
x
是非交换的,左边(默认)或右边的系数x
可以退货。关键字“right”在以下情况下被忽略x
是交换的。实例
>>> from sympy import symbols >>> from sympy.abc import x, y, z
您可以选择前面有明确否定的术语:
>>> (-x + 2*y).coeff(-1) x >>> (x - 2*y).coeff(-1) 2*y
您可以选择没有有理系数的项:
>>> (x + 2*y).coeff(1) x >>> (3 + 2*x + 4*x**2).coeff(1) 0
可以通过使n=0来选择与x无关的项;在这种情况下独立表达式(十) [0] 返回(将返回0而不是“无”):
>>> (3 + 2*x + 4*x**2).coeff(x, 0) 3 >>> eq = ((x + 1)**3).expand() + 1 >>> eq x**3 + 3*x**2 + 3*x + 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 2] >>> eq -= 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 0]
您可以选择前面有数字项的术语:
>>> (-x - 2*y).coeff(2) -y >>> from sympy import sqrt >>> (x + sqrt(2)*x).coeff(sqrt(2)) x
匹配准确:
>>> (3 + 2*x + 4*x**2).coeff(x) 2 >>> (3 + 2*x + 4*x**2).coeff(x**2) 4 >>> (3 + 2*x + 4*x**2).coeff(x**3) 0 >>> (z*(x + y)**2).coeff((x + y)**2) z >>> (z*(x + y)**2).coeff(x + y) 0
此外,没有进行因子分解,因此不能从以下公式中获得1+z*(1+y):
>>> (x + z*(x + x*y)).coeff(x) 1
如果需要这种保理,可以首先使用因子项:
>>> from sympy import factor_terms >>> factor_terms(x + z*(x + x*y)).coeff(x) z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False) >>> n.coeff(n) 1 >>> (3*n).coeff(n) 3 >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m 1 + m >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m m
如果有多个可能的系数0返回:
>>> (n*m + m*n).coeff(n) 0
如果只有一个可能的系数,则返回:
>>> (n*m + x*m*n).coeff(m*n) x >>> (n*m + x*m*n).coeff(m*n, right=1) 1
参见
as_coefficient
将表达式分为系数和因子
as_coeff_Add
将加法常量与表达式分开
as_coeff_Mul
将乘法常数与表达式分开
as_independent
将x相关项/因子与其他项分开
sympy.polys.polytools.Poly.coeff_monomial
有效求多元单项式的单系数
sympy.polys.polytools.Poly.nth
与coeff_单项式相似,但是使用了单项式项的幂
- collect(syms, func=None, evaluate=True, exact=False, distribute_order_term=True)[源代码]#
请参见中的collect函数简化
- compute_leading_term(x, logx=None)[源代码]#
Deprecated function to compute the leading term of a series.
因为只有.series()的结果才允许使用“前导”项,所以这是一个先计算序列的包装器。
- could_extract_minus_sign()[源代码]#
Return True if self has -1 as a leading factor or has more literal negative signs than positive signs in a sum, otherwise False.
实例
>>> from sympy.abc import x, y >>> e = x - y >>> {i.could_extract_minus_sign() for i in (e, -e)} {False, True}
Though the
y - x
is considered like-(x - y)
, since it is in a product without a leading factor of -1, the result is false below:>>> (x*(y - x)).could_extract_minus_sign() False
To put something in canonical form wrt to sign, use \(signsimp\):
>>> from sympy import signsimp >>> signsimp(x*(y - x)) -x*(x - y) >>> _.could_extract_minus_sign() True
- equals(other, failing_expression=False)[源代码]#
Return True if self == other, False if it does not, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.
解释
如果
self
是一个不为零的数(或复数),则结果为False。如果
self
是一个数字,并且尚未计算为零,则evalf将用于测试表达式的计算结果是否为零。如果它这样做并且结果有意义(即对于有理结果,精度为-1,或者大于1),那么evalf值将用于返回True或False。
- expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[源代码]#
使用提示展开表达式。
请参见中的expand()函数的docstringsympy.core.function公司了解更多信息。
- property expr_free_symbols#
喜欢
free_symbols
,但仅当自由符号包含在表达式节点中时才返回它们。实例
>>> from sympy.abc import x, y >>> (x + y).expr_free_symbols {x, y}
If the expression is contained in a non-expression object, do not return the free symbols. Compare:
>>> from sympy import Tuple >>> t = Tuple(x + y) >>> t.expr_free_symbols set() >>> t.free_symbols {x, y}
- extract_additively(c)[源代码]#
如果有可能从self中减去c并使所有匹配系数朝零移动,则返回self-c,否则返回None。
实例
>>> from sympy.abc import x, y >>> e = 2*x + 3 >>> e.extract_additively(x + 1) x + 2 >>> e.extract_additively(3*x) >>> e.extract_additively(4) >>> (y*(x + 1)).extract_additively(x + 1) >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1) (x + 1)*(x + 2*y) + 3
- extract_branch_factor(allow_half=False)[源代码]#
试着把自己写成
exp_polar(2*pi*I*n)*z
以一种很好的方式。返回(z,n)。>>> from sympy import exp_polar, I, pi >>> from sympy.abc import x, y >>> exp_polar(I*pi).extract_branch_factor() (exp_polar(I*pi), 0) >>> exp_polar(2*I*pi).extract_branch_factor() (1, 1) >>> exp_polar(-pi*I).extract_branch_factor() (exp_polar(I*pi), -1) >>> exp_polar(3*pi*I + x).extract_branch_factor() (exp_polar(x + I*pi), 1) >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor() (y*exp_polar(2*pi*x), -1) >>> exp_polar(-I*pi/2).extract_branch_factor() (exp_polar(-I*pi/2), 0)
如果allow_half为真,也提取exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True) (1, 1/2) >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True) (1, 1) >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True) (1, 3/2) >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True) (1, -1/2)
- extract_multiplicatively(c)[源代码]#
如果不可能以一种好的方式使self以c*的形式出现,则返回None,即保留self参数的属性。
实例
>>> from sympy import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y) x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2) x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3) x/6
- fourier_series(limits=None)[源代码]#
计算自己的傅立叶正弦/余弦级数。
请参见
fourier_series()
在傅里叶级数了解更多信息。
- fps(x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False)[源代码]#
计算自我的形式幂级数。
请参见
fps()
函数正式系列了解更多信息。
- getn()[源代码]#
返回表达式的顺序。
解释
顺序由O(…)项决定。如果没有O(…)项,则返回None。
实例
>>> from sympy import O >>> from sympy.abc import x >>> (1 + x + O(x**2)).getn() 2 >>> (1 + x).getn()
- is_algebraic_expr(*syms)[源代码]#
这测试给定的表达式是否是代数的,在给定的符号syms中。当没有给出符号时,将使用所有自由符号。有理函数不必是展开的或任何形式的规范形式。
对于具有符号指数的“代数表达式”,此函数返回False。这是is_有理函数的一个简单扩展,包括有理求幂。
实例
>>> from sympy import Symbol, sqrt >>> x = Symbol('x', real=True) >>> sqrt(1 + x).is_rational_function() False >>> sqrt(1 + x).is_algebraic_expr() True
此函数不尝试任何可能导致看起来不是代数表达式的表达式变为代数表达式的非平凡简化。
>>> from sympy import exp, factor >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1) >>> a.is_algebraic_expr(x) False >>> factor(a).is_algebraic_expr() True
工具书类
- is_constant(*wrt, **flags)[源代码]#
如果self为常量,则返回True;如果self不是常量,则返回False;如果无法确定恒常性,则返回None。
解释
如果一个表达式没有自由符号,那么它就是一个常量。如果存在自由符号,则表达式可能是常数,可能(但不一定)为零。为了测试这些表达式,我们尝试了几种策略:
1) 两个随机点的数值计算。如果两个这样的计算给出两个不同的值,并且这些值的精度大于1,则self不是常数。如果评估结果一致或无法获得精确性,则不会做出任何决定。只有在以下情况下才进行数值试验
wrt
不同于自由符号。2) 对'wrt'中的变量进行微分(如果省略,则为所有自由符号),以查看表达式是否为常量。这并不总是导致表达式为零,即使表达式是常量(请参见测试中添加的测试)_表达式). 如果所有导数都为零,那么self对于给定的符号是常数。
3) finding out zeros of denominator expression with free_symbols. It will not be constant if there are zeros. It gives more negative answers for expression that are not constant.
如果求值和微分都不能证明表达式是常量,则除非两个数值恰好相同且标志相同,否则不返回任何表达式
failing_number
为True——在这种情况下,将返回数值。如果传递了标志simplify=False,则不会简化self;默认值为True,因为self应该在测试之前被简化。
实例
>>> from sympy import cos, sin, Sum, S, pi >>> from sympy.abc import a, n, x, y >>> x.is_constant() False >>> S(2).is_constant() True >>> Sum(x, (x, 1, 10)).is_constant() True >>> Sum(x, (x, 1, n)).is_constant() False >>> Sum(x, (x, 1, n)).is_constant(y) True >>> Sum(x, (x, 1, n)).is_constant(n) False >>> Sum(x, (x, 1, n)).is_constant(x) True >>> eq = a*cos(x)**2 + a*sin(x)**2 - a >>> eq.is_constant() True >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 True
>>> (0**x).is_constant() False >>> x.is_constant() False >>> (x**x).is_constant() False >>> one = cos(x)**2 + sin(x)**2 >>> one.is_constant() True >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1 True
- is_meromorphic(x, a)[源代码]#
这测试一个表达式作为给定符号的函数是否是亚纯的
x
在这一点上a
.这种方法是一种快速测试,如果没有简化或更详细的分析就无法做出决定,则不会返回任何结果。
实例
>>> from sympy import zoo, log, sin, sqrt >>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3 >>> f.is_meromorphic(x, 0) True >>> f.is_meromorphic(x, 1) True >>> f.is_meromorphic(x, zoo) True
>>> g = x**log(3) >>> g.is_meromorphic(x, 0) False >>> g.is_meromorphic(x, 1) True >>> g.is_meromorphic(x, zoo) False
>>> h = sin(1/x)*x**2 >>> h.is_meromorphic(x, 0) False >>> h.is_meromorphic(x, 1) True >>> h.is_meromorphic(x, zoo) True
当多值函数的分支是亚纯函数时,它们被认为是亚纯函数。因此,除了在本质奇点和分支点外,大多数函数在任何地方都是亚纯的。特别是,它们在分支切割上也是亚纯的,除了在端点处。
>>> log(x).is_meromorphic(x, -1) True >>> log(x).is_meromorphic(x, 0) False >>> sqrt(x).is_meromorphic(x, -1) True >>> sqrt(x).is_meromorphic(x, 0) False
- property is_number#
返回true
self
没有自由符号和未定义函数(精确地说,AppliedUndef)。它会比if not self.free_symbols
但是,自从is_number
一旦遇到自由符号或未定义的函数,将失败。实例
>>> from sympy import Function, Integral, cos, sin, pi >>> from sympy.abc import x >>> f = Function('f')
>>> x.is_number False >>> f(1).is_number False >>> (2*x).is_number False >>> (2 + Integral(2, x)).is_number False >>> (2 + Integral(2, (x, 1, 2))).is_number True
并非所有的数字都是同一意义上的数字:
>>> pi.is_number, pi.is_Number (True, False)
如果某个东西是一个数,它应该计算出一个带有实数和虚数部分的数;但是,结果可能不具有可比性,因为结果的实部和/或虚部可能没有精度。
>>> cos(1).is_number and cos(1).is_comparable True
>>> z = cos(1)**2 + sin(1)**2 - 1 >>> z.is_number True >>> z.is_comparable False
- is_polynomial(*syms)[源代码]#
如果self是syms中的多项式,则返回True,否则返回False。
这将检查self在syms中是否是一个精确的多项式。对于具有符号指数的“多项式”表达式,此函数返回False。因此,您应该能够将多项式算法应用于返回True的表达式,并且Poly(expr, * 当且仅当表达式是多项式( * syms)返回True。多项式不必是展开形式。如果没有给出符号,表达式中的所有自由符号都将被使用。
这不是假设系统的一部分。不能执行符号('z',polyminal=True)。
实例
>>> from sympy import Symbol, Function >>> x = Symbol('x') >>> ((x**2 + 1)**4).is_polynomial(x) True >>> ((x**2 + 1)**4).is_polynomial() True >>> (2**x + 1).is_polynomial(x) False >>> (2**x + 1).is_polynomial(2**x) True >>> f = Function('f') >>> (f(x) + 1).is_polynomial(x) False >>> (f(x) + 1).is_polynomial(f(x)) True >>> (1/f(x) + 1).is_polynomial(f(x)) False
>>> n = Symbol('n', nonnegative=True, integer=True) >>> (x**n + 1).is_polynomial(x) False
此函数不尝试任何可能导致表达式看起来不是多项式的非平凡简化。
>>> from sympy import sqrt, factor, cancel >>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1) >>> a.is_polynomial(y) False >>> factor(a) y + 1 >>> factor(a).is_polynomial(y) True
>>> b = (y**2 + 2*y + 1)/(y + 1) >>> b.is_polynomial(y) False >>> cancel(b) y + 1 >>> cancel(b).is_polynomial(y) True
另请参见.is_rational_function()
- is_rational_function(*syms)[源代码]#
测试函数是否是给定符号syms中两个多项式的比值。当没有给出符号时,将使用所有自由符号。有理函数不必是展开的或任何形式的规范形式。
对于具有符号指数的“有理函数”表达式,此函数返回False。因此,您应该能够调用.as_numer_denom(),并将多项式算法应用到表达式的结果中,从而返回True。
这不是假设系统的一部分。你不能做Symbol('z',rational_function=True)。
实例
>>> from sympy import Symbol, sin >>> from sympy.abc import x, y
>>> (x/y).is_rational_function() True
>>> (x**2).is_rational_function() True
>>> (x/sin(y)).is_rational_function(y) False
>>> n = Symbol('n', integer=True) >>> (x**n + 1).is_rational_function(x) False
此函数不尝试任何可能导致表达式看起来不是有理函数的非平凡简化。
>>> from sympy import sqrt, factor >>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1)/y >>> a.is_rational_function(y) False >>> factor(a) (y + 1)/y >>> factor(a).is_rational_function(y) True
另请参见is_algebratic_expr()。
- leadterm(x, logx=None, cdir=0)[源代码]#
返回前导项a x *b作为元组(a,b)。
实例
>>> from sympy.abc import x >>> (1+x+x**2).leadterm(x) (1, 0) >>> (1/x**2+x+x**2).leadterm(x) (1, -2)
- lseries(x=None, x0=0, dir='+', logx=None, cdir=0)[源代码]#
生成序列项的迭代器的序列的包装器。
注意:无穷级数将产生无限迭代器。例如,下面的内容永远不会终止。它只会继续打印sin(x)系列的术语:
for term in sin(x).lseries(x): print term
The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you do not know how many you should ask for in nseries() using the "n" parameter.
另请参见N系列()。
- normal()[源代码]#
Return the expression as a fraction.
expression -> a/b
参见
as_numer_denom
return
(a, b)
instead ofa/b
- nseries(x=None, x0=0, n=6, dir='+', logx=None, cdir=0)[源代码]#
如果要对序列进行评估,请考虑包装器。
如果给定x,x0为0,dir='+',self有x,则调用u evaln系列。这将计算最里面表达式中的“n”项,然后通过将所有项“交叉相乘”来构建最后的序列。
可选的
logx
参数可用于将返回序列中的任何日志(x)替换为符号值,以避免将log(x)计算为0。应提供一个符号来代替log(x)。Advantage -- it's fast, because we do not have to determine how many terms we need to calculate in advance.
缺点——最终得到的术语可能比预期的要少,但是附加的O(x**n)项总是正确的,因此结果虽然可能更短,但也将是正确的。
如果这些假设中的任何一个都不满足,这将被视为序列的包装器,它将更加努力地返回正确数量的术语。
另请参见lseries()。
实例
>>> from sympy import sin, log, Symbol >>> from sympy.abc import x, y >>> sin(x).nseries(x, 0, 6) x - x**3/6 + x**5/120 + O(x**6) >>> log(x+1).nseries(x, 0, 5) x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
处理
logx
参数---在下面的示例中,扩展失败,因为sin
在-oo处没有渐近展开(当x接近0时对数(x)的极限):>>> e = sin(log(x)) >>> e.nseries(x, 0, 6) Traceback (most recent call last): ... PoleError: ... ... >>> logx = Symbol('logx') >>> e.nseries(x, 0, 6, logx=logx) sin(logx)
In the following example, the expansion works but only returns self unless the
logx
parameter is used:>>> e = x**y >>> e.nseries(x, 0, 2) x**y >>> e.nseries(x, 0, 2, logx=logx) exp(logx*y)
- primitive()[源代码]#
返回可以非递归地从self的每个项中提取的正有理数(即self被当作Add处理)。这类似于as_coeff_Mul()方法,但是primitive总是提取一个正有理数(而不是负数或浮点数)。
实例
>>> from sympy.abc import x >>> (3*(x + 1)**2).primitive() (3, (x + 1)**2) >>> a = (6*x + 2); a.primitive() (2, 3*x + 1) >>> b = (x/2 + 3); b.primitive() (1/2, x + 6) >>> (a*b).primitive() == (1, a*b) True
- round(n=None)[源代码]#
返回x四舍五入到给定的小数位。
如果结果是复数,则对该数的实部和虚部进行舍入。
实例
>>> from sympy import pi, E, I, S, Number >>> pi.round() 3 >>> pi.round(2) 3.14 >>> (2*pi + E*I).round() 6 + 3*I
“圆形”方法具有切碎效果:
>>> (2*pi + I/10).round() 6 >>> (pi/10 + 2*I).round() 2*I >>> (pi/10 + E*I).round(2) 0.31 + 2.72*I
笔记
Python
round
函数使用sypyround
方法,因此它将始终返回一个SymPy数字(而不是Python float或int):>>> isinstance(round(S(123), -2), Number) True
- series(x=None, x0=0, n=6, dir='+', logx=None, cdir=0)[源代码]#
关于“自我”的系列扩张
x = x0
一个接一个地产生级数中的任一项(n=无时给出的懒惰级数),当n=时同时产生所有项!=无。返回“self”在该点周围的级数展开
x = x0
关于x
高达O((x - x0)**n, x, x0)
(默认n为6)。如果
x=None
和self
为单变量时,将提供单变量符号,否则将引发错误。- 参数:
expr :表达式
要展开其级数的表达式。
x :符号
它是要计算的表达式的变量。
x0 :值
围绕它的价值
x
是经过计算的。可以是来自-oo
到oo
.n :值
The value used to represent the order in terms of
x**n
, up to which the series is to be expanded.dir :字符串,可选
串联扩展可以是双向的。如果
dir="+"
,然后(x->x0+)。如果dir="-", then (x->x0-). For infinite `` x0号
(oo
或-oo
)dir
自变量由无穷大的方向决定(即。,dir="-"
对于oo
)logx :可选
它用于将返回序列中的任何log(x)替换为符号值,而不是计算实际值。
cdir :可选
它代表复杂方向,指示需要评估扩展的方向。
- 返回:
Expr :表达式
关于x0的表达式的级数展开
- 加薪:
TypeError
如果“n”和“x0”是无穷大对象
PoleError
如果“x0”是无穷大的对象
实例
>>> from sympy import cos, exp, tan >>> from sympy.abc import x, y >>> cos(x).series() 1 - x**2/2 + x**4/24 + O(x**6) >>> cos(x).series(n=4) 1 - x**2/2 + O(x**4) >>> cos(x).series(x, x0=1, n=2) cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1)) >>> e = cos(x + exp(y)) >>> e.series(y, n=2) cos(x + 1) - y*sin(x + 1) + O(y**2) >>> e.series(x, n=2) cos(exp(y)) - x*sin(exp(y)) + O(x**2)
如果
n=None
然后将返回一个系列术语的生成器。>>> term=cos(x).series(n=None) >>> [next(term) for i in range(2)] [1, -x**2/2]
为了
dir=+
(默认)从右侧和dir=-
从左边开始的系列。对于平滑函数,此标志不会改变结果。>>> abs(x).series(dir="+") x >>> abs(x).series(dir="-") -x >>> f = tan(x) >>> f.series(x, 2, 6, "+") tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) + (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 + 5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 + 2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-") tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2)) + O((x - 2)**3, (x, 2))
For rational expressions this method may return original expression without the Order term. >>> (1/x).series(x, n=8) 1/x
符号#
- class sympy.core.symbol.Symbol(name, **assumptions)[源代码]#
Symbol class is used to create symbolic variables.
- 参数:
AtomicExpr: variable name
Boolean: Assumption with a boolean value(True or False)
解释
Symbolic variables are placeholders for mathematical symbols that can represent numbers, constants, or any other mathematical entities and can be used in mathematical expressions and to perform symbolic computations.
假设:
commutative = True positive = True real = True imaginary = True complex = True complete list of more assumptions- Predicates
您可以重写构造函数中的默认假设。
实例
>>> from sympy import Symbol >>> x = Symbol("x", positive=True) >>> x.is_positive True >>> x.is_negative False
passing in greek letters:
>>> from sympy import Symbol >>> alpha = Symbol('alpha') >>> alpha α
Trailing digits are automatically treated like subscripts of what precedes them in the name. General format to add subscript to a symbol :
<var_name> = Symbol('<symbol_name>_<subscript>')
>>> from sympy import Symbol >>> alpha_i = Symbol('alpha_i') >>> alpha_i αᵢ
- class sympy.core.symbol.Wild(name, exclude=(), properties=(), **assumptions)[源代码]#
通配符匹配任何内容,或任何未显式排除任何内容的内容。
- 参数:
name :结构
野生实例的名称。
排除 :iterable,可选
中的实例
exclude
不会匹配。性质 :iterable of functions,可选
函数,每个函数都以表达式作为输入并返回
bool
. 中的所有函数properties
需要返回吗True
以使Wild实例与表达式匹配。
实例
>>> from sympy import Wild, WildFunction, cos, pi >>> from sympy.abc import x, y, z >>> a = Wild('a') >>> x.match(a) {a_: x} >>> pi.match(a) {a_: pi} >>> (3*x**2).match(a*x) {a_: 3*x} >>> cos(x).match(a) {a_: cos(x)} >>> b = Wild('b', exclude=[x]) >>> (3*x**2).match(b*x) >>> b.match(a) {a_: b_} >>> A = WildFunction('A') >>> A.match(a) {a_: A_}
提示
使用Wild时,一定要使用exclude关键字使模式更精确。如果没有排除模式,您可能会得到技术上正确的匹配,但不是您想要的。例如,使用上述不排除:
>>> from sympy import symbols >>> a, b = symbols('a b', cls=Wild) >>> (2 + 3*y).match(a*x + b*y) {a_: 2/x, b_: 3}
This is technically correct, because (2/x)*x + 3*y == 2 + 3*y, but you probably wanted it to not match at all. The issue is that you really did not want a and b to include x and y, and the exclude parameter lets you specify exactly this. With the exclude parameter, the pattern will not match.
>>> a = Wild('a', exclude=[x, y]) >>> b = Wild('b', exclude=[x, y]) >>> (2 + 3*y).match(a*x + b*y)
排除也有助于消除匹配中的歧义。
>>> E = 2*x**3*y*z >>> a, b = symbols('a b', cls=Wild) >>> E.match(a*b) {a_: 2*y*z, b_: x**3} >>> a = Wild('a', exclude=[x, y]) >>> E.match(a*b) {a_: z, b_: 2*x**3*y} >>> a = Wild('a', exclude=[x, y, z]) >>> E.match(a*b) {a_: 2, b_: x**3*y*z}
Wild也接受
properties
参数:>>> a = Wild('a', properties=[lambda k: k.is_Integer]) >>> E.match(a*b) {a_: 2, b_: x**3*y*z}
- class sympy.core.symbol.Dummy(name=None, dummy_index=None, **assumptions)[源代码]#
即使虚拟符号具有相同的名称,每个符号都是唯一的:
实例
>>> from sympy import Dummy >>> Dummy("x") == Dummy("x") False
如果未提供名称,则将使用内部计数的字符串值。当需要临时变量且表达式中使用的变量的名称不重要时,此选项非常有用。
>>> Dummy() _Dummy_10
- sympy.core.symbol.symbols(names, *, cls=<class 'sympy.core.symbol.Symbol'>, **args) Any [源代码]#
将字符串转换为
Symbol
班级。symbols()
函数返回一系列符号,其名称取自names
参数,可以是逗号或空格分隔的字符串,也可以是字符串序列:>>> from sympy import symbols, Function >>> x, y, z = symbols('x,y,z') >>> a, b, c = symbols('a b c')
输出类型取决于输入参数的属性:
>>> symbols('x') x >>> symbols('x,') (x,) >>> symbols('x,y') (x, y) >>> symbols(('a', 'b', 'c')) (a, b, c) >>> symbols(['a', 'b', 'c']) [a, b, c] >>> symbols({'a', 'b', 'c'}) {a, b, c}
如果单个符号需要iterable容器,请设置
seq
参数True
或用逗号终止符号名:>>> symbols('x', seq=True) (x,)
为了减少键入,支持范围语法来创建索引符号。范围由冒号表示,范围类型由冒号右侧的字符决定。如果字符是一个数字,则左边的所有连续数字都作为非负起始值(如果冒号左边没有数字,则为0),右边的所有连续数字都被视为大于结束值的1::
>>> symbols('x:10') (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) >>> symbols('x5:10') (x5, x6, x7, x8, x9) >>> symbols('x5(:2)') (x50, x51) >>> symbols('x5:10,y:5') (x5, x6, x7, x8, x9, y0, y1, y2, y3, y4) >>> symbols(('x5:10', 'y:5')) ((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
如果冒号右侧的字符是字母,则左侧的单个字母(如果没有,则为“a”)作为起始字符,并将所有字符置于词典编纂范围内 通过 右边的字母用作范围:
>>> symbols('x:z') (x, y, z) >>> symbols('x:c') # null range () >>> symbols('x(:c)') (xa, xb, xc) >>> symbols(':c') (a, b, c) >>> symbols('a:d, x:z') (a, b, c, d, x, y, z) >>> symbols(('a:d', 'x:z')) ((a, b, c, d), (x, y, z))
支持多个范围;连续的数值范围应该用括号隔开,以消除一个范围的结束编号与下一个范围的起始编号之间的歧义:
>>> symbols('x:2(1:3)') (x01, x02, x11, x12) >>> symbols(':3:2') # parsing is from left to right (00, 01, 10, 11, 20, 21)
只删除了一对包围范围的圆括号,因此要在范围周围包括圆括号,请将其加倍。用空格或逗号括起来:
>>> symbols('x((a:b))') (x(a), x(b)) >>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))' (x(0,0), x(0,1))
所有新创建的符号都有根据
args
::>>> a = symbols('a', integer=True) >>> a.is_integer True >>> x, y, z = symbols('x,y,z', real=True) >>> x.is_real and y.is_real and z.is_real True
尽管它的名字,
symbols()
可以创建类似符号的对象,如函数或通配符类的实例。为了达到这个目的,设置cls
所需类型的关键字参数::>>> symbols('f,g,h', cls=Function) (f, g, h) >>> type(_[0]) <class 'sympy.core.function.UndefinedFunction'>
- sympy.core.symbol.var(names, **args)[源代码]#
创建符号并将其注入全局命名空间。
解释
这叫
symbols()
使用相同的参数,并将结果放入 全球的 命名空间。建议不要使用var()
在库代码中,其中symbols()
必须使用:.. rubric:: Examples
>>> from sympy import var
>>> var('x') x >>> x # noqa: F821 x
>>> var('a,ab,abc') (a, ab, abc) >>> abc # noqa: F821 abc
>>> var('x,y', real=True) (x, y) >>> x.is_real and y.is_real # noqa: F821 True
intfunc#
- sympy.core.intfunc.num_digits(n, base=10)[源代码]#
Return the number of digits needed to express n in give base.
- 参数:
n: 整数
The number whose digits are counted.
b: 整数
计算位数的基数。
实例
>>> from sympy.core.intfunc import num_digits >>> num_digits(10) 2 >>> num_digits(10, 2) # 1010 -> 4 digits 4 >>> num_digits(-100, 16) # -64 -> 2 digits 2
- sympy.core.intfunc.trailing(n)[源代码]#
计算n的二进制表示中的尾随零位数,即确定2除以n的最大幂。
实例
>>> from sympy import trailing >>> trailing(128) 7 >>> trailing(63) 0
- sympy.core.intfunc.ilcm(*args)[源代码]#
计算整数最小公倍数。
实例
>>> from sympy import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30
- sympy.core.intfunc.igcd(*args)#
计算非负整数的最大公约数。
解释
The algorithm is based on the well known Euclid's algorithm [R123]. To improve speed,
igcd()
has its own caching mechanism. If you do not need the cache mechanism, usingsympy.external.gmpy.gcd
.实例
>>> from sympy import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5
工具书类
- sympy.core.intfunc.igcd_lehmer(a, b)[源代码]#
Computes greatest common divisor of two integers.
解释
Euclid's algorithm for the computation of the greatest common divisor
gcd(a, b)
of two (positive) integers \(a\) and \(b\) is based on the division identity $$ a = q \times b + r$$, where the quotient \(q\) and the remainder \(r\) are integers and \(0 \le r < b\). Then each common divisor of \(a\) and \(b\) divides \(r\), and it follows thatgcd(a, b) == gcd(b, r)
. The algorithm works by constructing the sequence r0, r1, r2, ..., where r0 = a, r1 = b, and each rn is the remainder from the division of the two preceding elements.In Python,
q = a // b
andr = a % b
are obtained by the floor division and the remainder operations, respectively. These are the most expensive arithmetic operations, especially for large a and b.Lehmer's algorithm [R124] is based on the observation that the quotients
qn = r(n-1) // rn
are in general small integers even when a and b are very large. Hence the quotients can be usually determined from a relatively small number of most significant bits.The efficiency of the algorithm is further enhanced by not computing each long remainder in Euclid's sequence. The remainders are linear combinations of a and b with integer coefficients derived from the quotients. The coefficients can be computed as far as the quotients can be determined from the chosen most significant parts of a and b. Only then a new pair of consecutive remainders is computed and the algorithm starts anew with this pair.
工具书类
- sympy.core.intfunc.igcdex(a, b)[源代码]#
Returns x, y, g such that g = x*a + y*b = gcd(a, b).
实例
>>> from sympy.core.intfunc import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2)
>>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4
- sympy.core.intfunc.isqrt(n)[源代码]#
Return the largest integer less than or equal to \(\sqrt{n}\).
- 参数:
n : non-negative integer
- 返回:
int : \(\left\lfloor\sqrt{n}\right\rfloor\)
- 加薪:
ValueError
If n is negative.
TypeError
If n is of a type that cannot be compared to
int
. Therefore, a TypeError is raised forstr
, but not forfloat
.
实例
>>> from sympy.core.intfunc import isqrt >>> isqrt(0) 0 >>> isqrt(9) 3 >>> isqrt(10) 3 >>> isqrt("30") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' >>> from sympy.core.numbers import Rational >>> isqrt(Rational(-1, 2)) Traceback (most recent call last): ... ValueError: n must be nonnegative
- sympy.core.intfunc.integer_nthroot(y, n)[源代码]#
返回一个包含x=floor(y)的元组 (1/n)) and a boolean indicating whether the result is exact (that is, whether x n==y)。
实例
>>> from sympy import integer_nthroot >>> integer_nthroot(16, 2) (4, True) >>> integer_nthroot(26, 2) (5, False)
要简单地确定一个数字是否为完全平方,应使用is_square函数:
>>> from sympy.ntheory.primetest import is_square >>> is_square(26) False
- sympy.core.intfunc.integer_log(n, b)[源代码]#
Returns
(e, bool)
where e is the largest nonnegative integer such that \(|n| \geq |b^e|\) andbool
is True if \(n = b^e\).实例
>>> from sympy import integer_log >>> integer_log(125, 5) (3, True) >>> integer_log(17, 9) (1, False)
If the base is positive and the number negative the return value will always be the same except for 2:
>>> integer_log(-4, 2) (2, False) >>> integer_log(-16, 4) (0, False)
When the base is negative, the returned value will only be True if the parity of the exponent is correct for the sign of the base:
>>> integer_log(4, -2) (2, True) >>> integer_log(8, -2) (3, False) >>> integer_log(-8, -2) (3, True) >>> integer_log(-4, -2) (2, False)
- sympy.core.intfunc.mod_inverse(a, m)[源代码]#
Return the number \(c\) such that, \(a \times c = 1 \pmod{m}\) where \(c\) has the same sign as \(m\). If no such value exists, a ValueError is raised.
实例
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse \(x\) of 3 modulo 11. This is the same as finding \(x\) such that \(3x = 1 \pmod{11}\). One value of x that satisfies this congruence is 4. Because \(3 \times 4 = 12\) and \(12 = 1 \pmod{11}\). This is the value returned by
mod_inverse
:>>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7
When there is a common factor between the numerators of \(a\) and \(m\) the inverse does not exist:
>>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2) 7/2
工具书类
数字#
- class sympy.core.numbers.Number(*obj)[源代码]#
表示sypy中的原子序数。
解释
浮点数由Float类表示。有理数(任何大小)由有理类表示。整数(任何大小)由Integer类表示。Float和Rational是Number的子类;Integer是Rational的子类。
例如,
2/3
表示为Rational(2, 3)
它与使用Python除法获得的浮点数不同2/3
. 即使对于完全用二进制表示的数字,两种形式之间也有区别,例如Rational(1, 2)
和Float(0.5)
,在SymPy中使用。在符号计算中,有理形式是首选的。其他类型的数,如代数数
sqrt(2)
或者复数3 + 4*I
,不是Number类的实例,因为它们不是原子的。
- class sympy.core.numbers.Float(num, dps=None, precision=None)[源代码]#
表示任意精度的浮点数。
实例
>>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000
从字符串(和Python)创建浮动
int
和long
类型)将提供15位数字的最小精度,但精度将自动增加以捕获输入的所有数字。>>> Float(1) 1.00000000000000 >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 100000000000000000000.
然而, floating-point 数字(Python
float
类型)仅保留15位精度:>>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457
最好输入高精度的十进制数字作为字符串:
>>> Float('1.23456789123456789') 1.23456789123456789
还可以指定所需的位数:
>>> Float('1e-3', 3) 0.00100 >>> Float(100, 4) 100.0
如果发送空字符串以获得精度,Float可以自动计算有效数字;也允许使用空格或下划线。只允许字符串和long-ints进行自动计数)。
>>> Float('123 456 789.123_456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3.
如果一个数字是用科学记数法写的,如果出现十进制数,则只有指数前的数字才被认为是有效的,否则“e”只表示如何移动小数:
>>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00
笔记
浮点数本质上是不精确的,除非它们的值是二进制精确值。
>>> approx, exact = Float(.1, 1), Float(.125, 1)
出于计算目的,evalf需要能够改变精度,但这不会增加不精确值的精度。以下是0.1值的最精确5位近似值,其精度只有1位:
>>> approx.evalf(5) 0.099609
相比之下,0.125在二进制中是精确的(正如它以10为基数),因此它可以传递给Float或evalf,以获得具有匹配精度的任意精度:
>>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000
试图从一个浮点数中产生一个高精度的浮点数是不允许的,但是必须记住 基本浮动 (不是明显的十进制值)正在以高精度获得。例如,0.3没有有限的二进制表示。最接近的有理数是分数5404319552844595/2**54。因此,如果你试图获得0.3到20位精度的浮点值,你将不会看到与0.3后跟19个零相同的结果:
>>> Float(0.3, 20) 0.29999999999999998890
如果您想要一个20位数的十进制0.3(不是0.3的浮点近似值),您应该将0.3作为字符串发送。底层表示仍然是二进制的,但使用了比Python的float更高的精度:
>>> Float('0.3', 20) 0.30000000000000000000
虽然您可以使用Float提高现有浮点的精度,但它不会提高精度--基本值不会更改:
>>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10
在浮点上使用evalf时也会发生同样的情况:
>>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10
最后,float可以用一个mpf元组(n,c,p)实例化以生成数字(-1) n*c*2 p:
>>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000
实际的mpf元组还包含c中的位数,作为元组的最后一个元素:
>>> _._mpf_ (1, 5, 0, 3)
这不是实例化所需要的,也与精度不是一回事。mpf元组和精度是浮动轨迹的两个独立的量。
在SymPy中,Float是可以任意精度计算的数字。虽然浮点'inf'和'nan'不是这样的数字,但Float可以创建这些数字:
>>> Float('-inf') -oo >>> _.is_Float False
Zero in Float only has a single value. Values are not separate for positive and negative zeroes.
- class sympy.core.numbers.Rational(p, q=None, gcd=None)[源代码]#
表示任何大小的有理数(p/q)。
实例
>>> from sympy import Rational, nsimplify, S, pi >>> Rational(1, 2) 1/2
Rational在接受输入时没有偏见。如果传递浮点值,则将返回二进制表示的基础值:
>>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984
如果需要更简单的浮点数表示,则考虑将分母限制为所需值或将浮点数转换为字符串(这大致相当于将分母限制为10**12):
>>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5
当传递字符串文本时,可以获得任意精确的有理数:
>>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320
其他类型的字符串的转换可以通过sympify()函数来处理,而浮点转换为表达式或简单分数可以用nsimplify来处理:
>>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10
但是,如果输入没有减少到字面上的有理数,则会引发一个错误:
>>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi
低水平
以.p和.q访问分子和分母:
>>> r = Rational(3, 4) >>> r 3/4 >>> r.p 3 >>> r.q 4
请注意,p和q返回整数(而不是SymPy整数),因此在表达式中使用它们时需要小心:
>>> r.p/r.q 0.75
If an unevaluated Rational is desired,
gcd=1
can be passed and this will keep common divisors of the numerator and denominator from being eliminated. It is not possible, however, to leave a negative value in the denominator.>>> Rational(2, 4, gcd=1) 2/4 >>> Rational(2, -4, gcd=1).q 4
- as_content_primitive(radical=False, clear=True)[源代码]#
返回元组(R,self/R),其中R是从self提取的正有理数。
实例
>>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1)
参见文档字符串Expr.as_content_原语更多例子。
- class sympy.core.numbers.Integer(i)[源代码]#
表示任意大小的整数。
实例
>>> from sympy import Integer >>> Integer(3) 3
如果一个浮点数或有理数被传递给整数,小数部分将被丢弃;结果是四舍五入到零。
>>> Integer(3.8) 3 >>> Integer(-3.8) -3
如果字符串可以解析为整数,则它是可接受的输入:
>>> Integer("9" * 20) 99999999999999999999
很少需要显式实例化整数,因为Python整数在SymPy表达式中使用时会自动转换为整数。
- class sympy.core.numbers.AlgebraicNumber(expr, coeffs=None, alias=None, **args)[源代码]#
在SymPy中表示代数数的类。
Symbolically, an instance of this class represents an element \(\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}\). That is, the algebraic number \(\alpha\) is represented as an element of a particular number field \(\mathbb{Q}(\theta)\), with a particular embedding of this field into the complex numbers.
Formally, the primitive element \(\theta\) is given by two data points: (1) its minimal polynomial (which defines \(\mathbb{Q}(\theta)\)), and (2) a particular complex number that is a root of this polynomial (which defines the embedding \(\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}\)). Finally, the algebraic number \(\alpha\) which we represent is then given by the coefficients of a polynomial in \(\theta\).
- static __new__(cls, expr, coeffs=None, alias=None, **args)[源代码]#
Construct a new algebraic number \(\alpha\) belonging to a number field \(k = \mathbb{Q}(\theta)\).
There are four instance attributes to be determined:
Attribute
Type/Meaning
root
Expr
for \(\theta\) as a complex numberminpoly
Poly
, the minimal polynomial of \(\theta\)rep
DMP
giving \(\alpha\) as poly in \(\theta\)alias
Symbol
for \(\theta\), orNone
See Parameters section for how they are determined.
- 参数:
expr :
Expr
, or pair \((m, r)\)There are three distinct modes of construction, depending on what is passed as expr.
(1) expr is an
AlgebraicNumber
: In this case we begin by copying all four instance attributes from expr. If coeffs were also given, we compose the two coeff polynomials (see below). If an alias was given, it overrides.(2) expr is any other type of
Expr
: Thenroot
will equal expr. Therefore it must express an algebraic quantity, and we will compute itsminpoly
.(3) expr is an ordered pair \((m, r)\) giving the
minpoly
\(m\), and aroot
\(r\) thereof, which together define \(\theta\). In this case \(m\) may be either a univariatePoly
or anyExpr
which represents the same, while \(r\) must be someExpr
representing a complex number that is a root of \(m\), including both explicit expressions in radicals, and instances ofComplexRootOf
orAlgebraicNumber
.coeffs : list,
ANP
, None, optional (default=None)This defines
rep
, giving the algebraic number \(\alpha\) as a polynomial in \(\theta\).If a list, the elements should be integers or rational numbers. If an
ANP
, we take its coefficients (using itsto_list()
method). IfNone
, then the list of coefficients defaults to[1, 0]
, meaning that \(\alpha = \theta\) is the primitive element of the field.If expr was an
AlgebraicNumber
, let \(g(x)\) be itsrep
polynomial, and let \(f(x)\) be the polynomial defined by coeffs. Thenself.rep
will represent the composition \((f \circ g)(x)\).alias : str,
Symbol
, None, optional (default=None)This is a way to provide a name for the primitive element. We described several ways in which the expr argument can define the value of the primitive element, but none of these methods gave it a name. Here, for example, alias could be set as
Symbol('theta')
, in order to make this symbol appear when \(\alpha\) is printed, or rendered as a polynomial, using theas_poly()
method.
实例
Recall that we are constructing an algebraic number as a field element \(\alpha \in \mathbb{Q}(\theta)\).
>>> from sympy import AlgebraicNumber, sqrt, CRootOf, S >>> from sympy.abc import x
Example (1): \(\alpha = \theta = \sqrt{2}\)
>>> a1 = AlgebraicNumber(sqrt(2)) >>> a1.minpoly_of_element().as_expr(x) x**2 - 2 >>> a1.evalf(10) 1.414213562
Example (2): \(\alpha = 3 \sqrt{2} - 5\), \(\theta = \sqrt{2}\). We can either build on the last example:
>>> a2 = AlgebraicNumber(a1, [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2)
or start from scratch:
>>> a2 = AlgebraicNumber(sqrt(2), [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2)
Example (3): \(\alpha = 6 \sqrt{2} - 11\), \(\theta = \sqrt{2}\). Again we can build on the previous example, and we see that the coeff polys are composed:
>>> a3 = AlgebraicNumber(a2, [2, -1]) >>> a3.as_expr() -11 + 6*sqrt(2)
reflecting the fact that \((2x - 1) \circ (3x - 5) = 6x - 11\).
Example (4): \(\alpha = \sqrt{2}\), \(\theta = \sqrt{2} + \sqrt{3}\). The easiest way is to use the
to_number_field()
function:>>> from sympy import to_number_field >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) >>> a4.minpoly_of_element().as_expr(x) x**2 - 2 >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) >>> a4.coeffs() [1/2, 0, -9/2, 0]
but if you already knew the right coefficients, you could construct it directly:
>>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3)
Example (5): Construct the Golden Ratio as an element of the 5th cyclotomic field, supposing we already know its coefficients. This time we introduce the alias \(\zeta\) for the primitive element of the field:
>>> from sympy import cyclotomic_poly >>> from sympy.abc import zeta >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), ... [-1, -1, 0, 0], alias=zeta) >>> a5.as_poly().as_expr() -zeta**3 - zeta**2 >>> a5.evalf() 1.61803398874989
(The index
-1
toCRootOf
selects the complex root with the largest real and imaginary parts, which in this case is \(\mathrm{e}^{2i\pi/5}\). SeeComplexRootOf
.)Example (6): Building on the last example, construct the number \(2 \phi \in \mathbb{Q}(\phi)\), where \(\phi\) is the Golden Ratio:
>>> from sympy.abc import phi >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi) >>> a6.as_poly().as_expr() 2*phi >>> a6.primitive_element().evalf() 1.61803398874989
Note that we needed to use
a5.to_root()
, since passinga5
as the first argument would have constructed the number \(2 \phi\) as an element of the field \(\mathbb{Q}(\zeta)\):>>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0]) >>> a6_wrong.as_poly().as_expr() -2*zeta**3 - 2*zeta**2 >>> a6_wrong.primitive_element().evalf() 0.309016994374947 + 0.951056516295154*I
- field_element(coeffs)[源代码]#
Form another element of the same number field.
- 参数:
coeffs : list,
ANP
Like the coeffs arg to the class
constructor
, defines the new element as a polynomial in the primitive element.If a list, the elements should be integers or rational numbers. If an
ANP
, we take its coefficients (using itsto_list()
method).
解释
If we represent \(\alpha \in \mathbb{Q}(\theta)\), form another element \(\beta \in \mathbb{Q}(\theta)\) of the same number field.
实例
>>> from sympy import AlgebraicNumber, sqrt >>> a = AlgebraicNumber(sqrt(5), [-1, 1]) >>> b = a.field_element([3, 2]) >>> print(a) 1 - sqrt(5) >>> print(b) 2 + 3*sqrt(5) >>> print(b.primitive_element() == a.primitive_element()) True
- property is_aliased#
返回
True
如果alias
被设定。
- property is_primitive_element#
Say whether this algebraic number \(\alpha \in \mathbb{Q}(\theta)\) is equal to the primitive element \(\theta\) for its field.
- minpoly_of_element()[源代码]#
Compute the minimal polynomial for this algebraic number.
解释
Recall that we represent an element \(\alpha \in \mathbb{Q}(\theta)\). Our instance attribute
self.minpoly
is the minimal polynomial for our primitive element \(\theta\). This method computes the minimal polynomial for \(\alpha\).
- primitive_element()[源代码]#
Get the primitive element \(\theta\) for the number field \(\mathbb{Q}(\theta)\) to which this algebraic number \(\alpha\) belongs.
- 返回:
AlgebraicNumber
- to_primitive_element(radicals=True)[源代码]#
Convert
self
to anAlgebraicNumber
instance that is equal to its own primitive element.- 参数:
radicals : boolean, optional (default=True)
If
True
, then we will try to return anAlgebraicNumber
whoseroot
is an expression in radicals. If that is not possible (or if radicals isFalse
),root
will be aComplexRootOf
.- 返回:
AlgebraicNumber
解释
If we represent \(\alpha \in \mathbb{Q}(\theta)\), \(\alpha \neq \theta\), construct a new
AlgebraicNumber
that represents \(\alpha \in \mathbb{Q}(\alpha)\).实例
>>> from sympy import sqrt, to_number_field >>> from sympy.abc import x >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
The
AlgebraicNumber
a
represents the number \(\sqrt{2}\) in the field \(\mathbb{Q}(\sqrt{2} + \sqrt{3})\). Renderinga
as a polynomial,>>> a.as_poly().as_expr(x) x**3/2 - 9*x/2
reflects the fact that \(\sqrt{2} = \theta^3/2 - 9 \theta/2\), where \(\theta = \sqrt{2} + \sqrt{3}\).
a
is not equal to its own primitive element. Its minpoly>>> a.minpoly.as_poly().as_expr(x) x**4 - 10*x**2 + 1
is that of \(\theta\).
Converting to a primitive element,
>>> a_prim = a.to_primitive_element() >>> a_prim.minpoly.as_poly().as_expr(x) x**2 - 2
we obtain an
AlgebraicNumber
whoseminpoly
is that of the number itself.
- to_root(radicals=True, minpoly=None)[源代码]#
Convert to an
Expr
that is not anAlgebraicNumber
, specifically, either aComplexRootOf
, or, optionally and where possible, an expression in radicals.- 参数:
radicals : boolean, optional (default=True)
If
True
, then we will try to return the root as an expression in radicals. If that is not possible, we will return aComplexRootOf
.minpoly :
Poly
If the minimal polynomial for \(self\) has been pre-computed, it can be passed in order to save time.
- sympy.core.numbers.seterr(divide=False)[源代码]#
Should SymPy raise an exception on 0/0 or return a nan?
除==真。。。。引发异常divide==False。。。返回nan
- class sympy.core.numbers.Zero[源代码]#
数字0。
Zero是一个singleton,可以通过
S.Zero
实例
>>> from sympy import S, Integer >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo
工具书类
- class sympy.core.numbers.One[源代码]#
第一名。
一个是单例的,可以通过
S.One
.实例
>>> from sympy import S, Integer >>> Integer(1) is S.One True
工具书类
- class sympy.core.numbers.NegativeOne[源代码]#
数字负一。
NegativeOne是单例的,可以通过
S.NegativeOne
.实例
>>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True
参见
工具书类
- class sympy.core.numbers.Half[源代码]#
有理数1/2。
Half是单例的,可以通过
S.Half
.实例
>>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True
工具书类
- class sympy.core.numbers.NaN[源代码]#
不是数字。
解释
它用作不确定数值的占位符。对NaN的大多数操作都会产生另一个NaN。最不确定的形式,如
0/0
或oo - oo` produce NaN. Two exceptions are `` 0 **0
andoo** 0`
,它们都产生1
(这与Python的float一致)。NaN与浮点NaN松散相关,后者在ieee754浮点标准中定义,并对应于Python
float('nan')
. 差异如下所示。即使在数学上,NaN本身也不等于其他任何东西。这解释了最初与直觉相反的结果
Eq
和==
在下面的例子中。NaN是不可比较的,因此不等式会引起类型错误。这与所有不等式都为假的浮点nan相反。
NaN是一个singleton,可以通过
S.NaN
,也可以作为nan
.实例
>>> from sympy import nan, S, oo, Eq >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality False >>> nan == nan # structural equality True
工具书类
- class sympy.core.numbers.Infinity[源代码]#
正无穷量。
解释
在实际分析中 \(\infty\) 表示无限限制: \(x\to\infty\) 意思是说 \(x\) 不受约束地成长。
在仿射扩展实数系统中,无穷远不仅用来定义一个极限,而且作为一个值。标记的点 \(+\infty\) 和 \(-\infty\) 可以加到实数的拓扑空间中,产生实数的两点紧化。加上代数性质,我们得到了扩展实数。
Infinity是一个singleton,可以通过
S.Infinity
,也可以作为oo
.实例
>>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo
参见
工具书类
- class sympy.core.numbers.NegativeInfinity[源代码]#
负无穷量。
NegativeInfinity是一个单实例,可以通过
S.NegativeInfinity
.参见
- class sympy.core.numbers.ComplexInfinity[源代码]#
复无穷大。
解释
在复分析中,符号 \(\tilde\infty\) ,称为“复无穷大”,表示一个量值无穷大,但复相位未定的量。
complexfinity是一个单实例,可以通过
S.ComplexInfinity
,也可以作为zoo
.实例
>>> from sympy import zoo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo
参见
- class sympy.core.numbers.Exp1[源代码]#
这个 \(e\) 常数。
解释
超越数 \(e = 2.718281828\ldots\) 是自然对数和指数函数的基, \(e = \exp(1)\) . 有时称为欧拉数或纳皮尔常数。
Exp1是一个singleton,可以通过
S.Exp1
,也可以作为E
.实例
>>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1
工具书类
- class sympy.core.numbers.ImaginaryUnit[源代码]#
想象单位, \(i = \sqrt{{-1}}\) .
我是单身汉,可以通过
S.I
,也可以作为I
.实例
>>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I
工具书类
- class sympy.core.numbers.Pi[源代码]#
这个 \(\pi\) 常数。
解释
超越数 \(\pi = 3.141592654\ldots\) 表示圆的周长与直径之比,单位圆的面积,三角函数的半周期,以及数学中的许多其他东西。
Pi是一个singleton,可以通过
S.Pi
,也可以作为pi
.实例
>>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi)
工具书类
- class sympy.core.numbers.EulerGamma[源代码]#
欧拉-马斯切罗尼常数。
解释
\(\gamma = 0.5772157\ldots\) (也称为欧拉常数)是在分析和数论中反复出现的数学常数。它被定义为谐波级数与自然对数之间的极限差:
\[\gamma=\lim\限制{n\到\infty}\]EulerGamma是单例的,可以通过
S.EulerGamma
.实例
>>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False
工具书类
- class sympy.core.numbers.Catalan[源代码]#
加泰罗尼亚常数。
解释
\(G = 0.91596559\ldots\) is given by the infinite series
\[G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}\]Catalan是一个singleton,可以通过
S.Catalan
.实例
>>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False
工具书类
- class sympy.core.numbers.GoldenRatio[源代码]#
黄金比例, \(\phi\) .
解释
\(\phi = \frac{1 + \sqrt{5}}{2}\) is an algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum.
GoldenRatio是一个单例,可以通过
S.GoldenRatio
.实例
>>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True
工具书类
- class sympy.core.numbers.TribonacciConstant[源代码]#
tribonaci常数。
解释
tribonacci数类似于Fibonacci数,但是序列不是从两个预定项开始,而是从三个预定项开始,之后的每个项都是前三个项的和。
tribonaci常数是相邻tribonaci数趋于的比率。它是多项式的根 \(x^3 - x^2 - x - 1 = 0\) ,并满足方程 \(x + x^{{-3}} = 2\) .
TribonacciConstant是一个单实例,可以通过
S.TribonacciConstant
.实例
>>> from sympy import S >>> S.TribonacciConstant > 1 True >>> S.TribonacciConstant.expand(func=True) 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3 >>> S.TribonacciConstant.is_irrational True >>> S.TribonacciConstant.n(20) 1.8392867552141611326
工具书类
[R139]https://en.wikipedia.org/wiki/Generalizations_Fibonacci_数#Tribonacci_数
- sympy.core.numbers.mod_inverse(a, m)[源代码]#
Return the number \(c\) such that, \(a \times c = 1 \pmod{m}\) where \(c\) has the same sign as \(m\). If no such value exists, a ValueError is raised.
实例
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse \(x\) of 3 modulo 11. This is the same as finding \(x\) such that \(3x = 1 \pmod{11}\). One value of x that satisfies this congruence is 4. Because \(3 \times 4 = 12\) and \(12 = 1 \pmod{11}\). This is the value returned by
mod_inverse
:>>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7
When there is a common factor between the numerators of \(a\) and \(m\) the inverse does not exist:
>>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2) 7/2
工具书类
- sympy.core.numbers.equal_valued(x, y)[源代码]#
Compare expressions treating plain floats as rationals.
实例
>>> from sympy import S, symbols, Rational, Float >>> from sympy.core.numbers import equal_valued >>> equal_valued(1, 2) False >>> equal_valued(1, 1) True
In SymPy expressions with Floats compare unequal to corresponding expressions with rationals:
>>> x = symbols('x') >>> x**2 == x**2.0 False
However an individual Float compares equal to a Rational:
>>> Rational(1, 2) == Float(0.5) False
In a future version of SymPy this might change so that Rational and Float compare unequal. This function provides the behavior currently expected of
==
so that it could still be used if the behavior of==
were to change in future.>>> equal_valued(1, 1.0) # Float vs Rational True >>> equal_valued(S(1).n(3), S(1).n(5)) # Floats of different precision True
解释
In future SymPy verions Float and Rational might compare unequal and floats with different precisions might compare unequal. In that context a function is needed that can check if a number is equal to 1 or 0 etc. The idea is that instead of testing
if x == 1:
if we want to accept floats like1.0
as well then the test can be written asif equal_valued(x, 1):
orif equal_valued(x, 2):
. Since this function is intended to be used in situations where one or both operands are expected to be concrete numbers like 1 or 0 the function does not recurse through the args of any compound expression to compare any nested floats.工具书类
权力#
- class sympy.core.power.Pow(b, e, evaluate=None)[源代码]#
将表达式x**y定义为“x提升为幂y”
自 1.7 版本弃用: Using arguments that aren't subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.单例定义涉及(0,1,-1,oo,-oo,I,-I):
EXPR
价值
原因
z**0
1
尽管存在0**0上的参数,请参见 [2] .
z**1
Z
(-oo)**(-1)
0
(-1)**-1
-1
S、 零**-1
动物园
严格来说,这不是真的,因为0**-1可能是未定义的,但是在某些假定基数为正的上下文中是方便的。
1**-1
1
oo**-1
0
0**哦
0
因为对于所有接近0的复数z,z**oo->0。
0**-哦
动物园
这不是严格意义上的,因为0**oo可能在正值和负值之间振荡,或者在复杂平面上旋转。但是,当基数为正时,这是方便的。
1 oo 1 -哦
南
因为有很多情况下lim(x(t),t)=1,lim(y(t),t)=oo(或-oo),但是lim(x(t)**y(t),t)!=1。看到了吗 [3] .
b**动物园
南
因为b**z没有z->zoo的限制
(- 1) oo (-1) (-oo)
南
因为极限的振荡。
哦**哦
面向对象
哦**-哦
0
(-oo) oo (-oo) -哦
南
面向对象 I (-oo) I
南
面向对象 e可能是x的极限 当x趋于oo时,e代表实x。如果e是I,则极限不存在,并且使用nan表示。
面向对象 (1+I) (-oo) (1+I)
动物园
如果e的实部为正,则abs(x**e)的极限为oo。所以极限值是zoo。
面向对象 (-1+I) -oo (-1+I)
0
如果e的实部为负,则极限为0。
Because symbolic computations are more flexible than floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra test-case code in the calculation of limits.
工具书类
- as_base_exp()[源代码]#
返回自身的基数和经验值。
解释
If base a Rational less than 1, then return 1/Rational, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments.
实例
>>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2) >>> p.base, p.exp (1/2, 2)
- as_content_primitive(radical=False, clear=True)[源代码]#
返回元组(R,self/R),其中R是从self提取的正有理数。
实例
>>> from sympy import sqrt >>> sqrt(4 + 4*sqrt(2)).as_content_primitive() (2, sqrt(1 + sqrt(2))) >>> sqrt(3 + 3*sqrt(2)).as_content_primitive() (1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from sympy import expand_power_base, powsimp, Mul >>> from sympy.abc import x, y
>>> ((2*x + 2)**2).as_content_primitive() (4, (x + 1)**2) >>> (4**((1 + y)/2)).as_content_primitive() (2, 4**(y/2)) >>> (3**((1 + y)/2)).as_content_primitive() (1, 3**((y + 1)/2)) >>> (3**((5 + y)/2)).as_content_primitive() (9, 3**((y + 1)/2)) >>> eq = 3**(2 + 2*x) >>> powsimp(eq) == eq True >>> eq.as_content_primitive() (9, 3**(2*x)) >>> powsimp(Mul(*_)) 3**(2*x + 2)
>>> eq = (2 + 2*x)**y >>> s = expand_power_base(eq); s.is_Mul, s (False, (2*x + 2)**y) >>> eq.as_content_primitive() (1, (2*(x + 1))**y) >>> s = expand_power_base(_[1]); s.is_Mul, s (True, 2**y*(x + 1)**y)
参见文档字符串Expr.as_content_原语更多例子。
骡子#
- class sympy.core.mul.Mul(*args, evaluate=None, _sympify=True)[源代码]#
Expression representing multiplication operation for algebraic field.
自 1.7 版本弃用: Using arguments that aren't subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.Every argument of
Mul()
must beExpr
. Infix operator*
on most scalar objects in SymPy calls this class.Another use of
Mul()
is to represent the structure of abstract multiplication so that its arguments can be substituted to return different class. Refer to examples section for this.Mul()
evaluates the argument unlessevaluate=False
is passed. The evaluation logic includes:- Flattening
Mul(x, Mul(y, z))
->Mul(x, y, z)
- Identity removing
Mul(x, 1, y)
->Mul(x, y)
- Exponent collecting by
.as_base_exp()
Mul(x, x**2)
->Pow(x, 3)
- Exponent collecting by
- Term sorting
Mul(y, x, 2)
->Mul(2, x, y)
Since multiplication can be vector space operation, arguments may have the different
sympy.core.kind.Kind()
. Kind of the resulting object is automatically inferred.实例
>>> from sympy import Mul >>> from sympy.abc import x, y >>> Mul(x, 1) x >>> Mul(x, x) x**2
If
evaluate=False
is passed, result is not evaluated.>>> Mul(1, 2, evaluate=False) 1*2 >>> Mul(x, x, evaluate=False) x*x
Mul()
also represents the general structure of multiplication operation.>>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> expr = Mul(x,y).subs({y:A}) >>> expr x*A >>> type(expr) <class 'sympy.matrices.expressions.matmul.MatMul'>
参见
- as_content_primitive(radical=False, clear=True)[源代码]#
返回元组(R,self/R),其中R是从self提取的正有理数。
实例
>>> from sympy import sqrt >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive() (6, -sqrt(2)*(1 - sqrt(2)))
参见文档字符串Expr.as_content_原语更多例子。
- as_ordered_factors(order=None)[源代码]#
将表达式转换为因子的有序列表。
实例
>>> from sympy import sin, cos >>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors() [2, x, y, sin(x), cos(x)]
- as_two_terms()[源代码]#
回归自我的头和尾。
这是获取表达式头和尾的最有效方法。
如果你只想要头,用自身参数 [0] ;
如果要处理尾部的参数,则使用自我介绍()当被视为Mul时,它给出包含尾部参数的头和元组。
当self被视为Add时,如果你想要这个系数,那么使用self.as_coeff_添加() [0]
实例
>>> from sympy.abc import x, y >>> (3*x*y).as_two_terms() (3, x*y)
- classmethod flatten(seq)[源代码]#
通过组合相关项返回交换、非交换和顺序参数。
笔记
In an expression like
a*b*c
, Python process this through SymPy asMul(Mul(a, b), c)
. This can have undesirable consequences.有时术语的组合不是人们想的那样:{c.f。https://github.com/sympy/sympy/issues/4596}
>>> from sympy import Mul, sqrt >>> from sympy.abc import x, y, z >>> 2*(x + 1) # this is the 2-arg Mul behavior 2*x + 2 >>> y*(x + 1)*2 2*y*(x + 1) >>> 2*(x + 1)*y # 2-arg result will be obtained first y*(2*x + 2) >>> Mul(2, x + 1, y) # all 3 args simultaneously processed 2*y*(x + 1) >>> 2*((x + 1)*y) # parentheses can control this behavior 2*y*(x + 1)
具有复合基的幂函数可能找不到一个可以组合的基,除非同时处理所有参数。在这种情况下,可能需要进行后期处理。{c.f。https://github.com/sympy/sympy/issues/5728}
>>> a = sqrt(x*sqrt(y)) >>> a**3 (x*sqrt(y))**(3/2) >>> Mul(a,a,a) (x*sqrt(y))**(3/2) >>> a*a*a x*sqrt(y)*sqrt(x*sqrt(y)) >>> _.subs(a.base, z).subs(z, a.base) (x*sqrt(y))**(3/2)
如果两个以上的项被相乘,则每个新参数将重新处理之前的所有项。所以如果
a
,b
和c
是Mul
那么表达吧a*b*c
(或用*=
)将处理a
和b
两次:一次a*b
当c
乘以。使用
Mul(a, b, c)
将处理所有参数一次。
Mul的结果是根据参数缓存的,因此flant只会被调用一次
Mul(a, b, c)
. 如果你可以构造一个计算,这样参数很可能是重复的,那么这可以节省计算答案的时间。例如,假设你有一个Mul,M,你想除以它d[i]
再乘以n[i]
你怀疑有很多重复n
. 最好计算一下M*n[i]/d[i]
而不是M/d[i]*n[i]
每次n [i] 重复,产品,M*n[i]
将返回而不展平--将返回缓存的值。如果你除以d[i]
首先(这些比n[i]
)这样就会产生一个新的Mul,M/d[i]
它的参数将在乘以时再次遍历n[i]
.{c.f。https://github.com/sympy/sympy/issues/5706}
如果缓存被关闭,这个考虑就没有意义了。
Nb公司
以上注释的有效性取决于Mul和flant的实现细节,这些细节可能随时改变。因此,只有在代码对性能高度敏感时才应考虑它们。
已由处理从序列中移除1 AssocOp.__new__.
添加#
- class sympy.core.add.Add(*args, evaluate=None, _sympify=True)[源代码]#
Expression representing addition operation for algebraic group.
自 1.7 版本弃用: Using arguments that aren't subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.Every argument of
Add()
must beExpr
. Infix operator+
on most scalar objects in SymPy calls this class.Another use of
Add()
is to represent the structure of abstract addition so that its arguments can be substituted to return different class. Refer to examples section for this.Add()
evaluates the argument unlessevaluate=False
is passed. The evaluation logic includes:- Flattening
Add(x, Add(y, z))
->Add(x, y, z)
- Identity removing
Add(x, 0, y)
->Add(x, y)
- Coefficient collecting by
.as_coeff_Mul()
Add(x, 2*x)
->Mul(3, x)
- Coefficient collecting by
- Term sorting
Add(y, x, 2)
->Add(2, x, y)
If no argument is passed, identity element 0 is returned. If single element is passed, that element is returned.
Note that
Add(*args)
is more efficient thansum(args)
because it flattens the arguments.sum(a, b, c, ...)
recursively adds the arguments asa + (b + (c + ...))
, which has quadratic complexity. On the other hand,Add(a, b, c, d)
does not assume nested structure, making the complexity linear.Since addition is group operation, every argument should have the same
sympy.core.kind.Kind()
.实例
>>> from sympy import Add, I >>> from sympy.abc import x, y >>> Add(x, 1) x + 1 >>> Add(x, x) 2*x >>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1 2*x**2 + 17*x/5 + 3.0*y + I*y + 1
If
evaluate=False
is passed, result is not evaluated.>>> Add(1, 2, evaluate=False) 1 + 2 >>> Add(x, x, evaluate=False) x + x
Add()
also represents the general structure of addition operation.>>> from sympy import MatrixSymbol >>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2) >>> expr = Add(x,y).subs({x:A, y:B}) >>> expr A + B >>> type(expr) <class 'sympy.matrices.expressions.matadd.MatAdd'>
Note that the printers do not display in args order.
>>> Add(x, 1) x + 1 >>> Add(x, 1).args (1, x)
参见
- as_coeff_add(*deps)[源代码]#
返回一个元组(coeff,args),其中self被视为Add,coeff是数字项,args是所有其他项的元组。
实例
>>> from sympy.abc import x >>> (7 + 3*x).as_coeff_add() (7, (3*x,)) >>> (7*x).as_coeff_add() (0, (7*x,))
- as_content_primitive(radical=False, clear=True)[源代码]#
返回元组(R,self/R),其中R是从self提取的正有理数。如果字根为真(默认值为假),则公共根式将被删除并作为基元表达式的一个因子包含在内。
实例
>>> from sympy import sqrt >>> (3 + 3*sqrt(2)).as_content_primitive() (3, 1 + sqrt(2))
也可以将基元内容分解为:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))
参见文档字符串Expr.as_content_原语更多例子。
- as_numer_denom()[源代码]#
将表达式分解为分子部分和分母部分。
实例
>>> from sympy.abc import x, y, z >>> (x*y/z).as_numer_denom() (x*y, z) >>> (x*(y + 1)/y**7).as_numer_denom() (x*(y + 1), y**7)
- as_real_imag(deep=True, **hints)[源代码]#
Return a tuple representing a complex number.
实例
>>> from sympy import I >>> (7 + 9*I).as_real_imag() (7, 9) >>> ((1 + I)/(1 - I)).as_real_imag() (0, 1) >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag() (-5, 5)
- as_two_terms()[源代码]#
回归自我的头和尾。
这是获取表达式头和尾的最有效方法。
如果你只想要头,用自身参数 [0] ;
如果要处理尾部的参数,则使用self.as_coef_添加(),当作为Add处理时,它给出包含尾部参数的头和元组。
当self被视为Mul时,如果你想要这个系数,那么使用self.as_coeff_mul() [0]
>>> from sympy.abc import x, y >>> (3*x - 2*y + 5).as_two_terms() (5, 3*x - 2*y)
- extract_leading_order(symbols, point=None)[源代码]#
返回前导项及其顺序。
实例
>>> from sympy.abc import x >>> (x + 1 + 1/x**5).extract_leading_order(x) ((x**(-5), O(x**(-5))),) >>> (1 + x).extract_leading_order(x) ((1, O(1)),) >>> (x + x**2).extract_leading_order(x) ((x, O(x)),)
- classmethod flatten(seq)[源代码]#
接受嵌套加法的序列“seq”,并返回一个展平列表。
返回:(交换的_部分,非交换的部分,顺序的符号)
应用关联性,所有的术语都可以相对于加法进行交换。
注意:0的移除已由处理 AssocOp.__new__
- primitive()[源代码]#
返回
(R, self/R)
在哪里?R
\(是的合理GCD ``self`\) '.R
只从每项的领先系数中收集。实例
>>> from sympy.abc import x, y
>>> (2*x + 4*y).primitive() (2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive() (2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive() (1/3, 2*x + 12.6*y)
不执行术语因子的子处理:
>>> ((2 + 2*x)*x + 2).primitive() (1, x*(2*x + 2) + 2)
递归处理可以用
as_content_primitive()
方法:>>> ((2 + 2*x)*x + 2).as_content_primitive() (2, x*(x + 1) + 1)
另请参见:中的primitive()函数polytools.py
国防部#
- class sympy.core.mod.Mod(p, q)[源代码]#
表示符号表达式上的模运算。
- 参数:
p :表达式
股息。
q :表达式
除数。
笔记
使用的约定与Python的相同:余数始终与除数具有相同的符号。
Many objects can be evaluated modulo
n
much faster than they can be evaluated directly (or at all). For this,evaluate=False
is necessary to prevent eager evaluation:>>> from sympy import binomial, factorial, Mod, Pow >>> Mod(Pow(2, 10**16, evaluate=False), 97) 61 >>> Mod(factorial(10**9, evaluate=False), 10**9 + 9) 712524808 >>> Mod(binomial(10**18, 10**12, evaluate=False), (10**5 + 3)**2) 3744312326
实例
>>> from sympy.abc import x, y >>> x**2 % y Mod(x**2, y) >>> _.subs({x: 5, y: 6}) 1
关系型#
- class sympy.core.relational.Relational(lhs, rhs, rop=None, **assumptions)[源代码]#
所有关系类型的基类。
- 参数:
rop :str或None
指示要实例化的子类。在的键中可以找到有效值Relational.ValidRelationOperator.
解释
Relational的子类通常应该直接实例化,但是Relational可以用有效的
rop
要分派给相应子类的值。实例
>>> from sympy import Rel >>> from sympy.abc import x, y >>> Rel(y, x + x**2, '==') Eq(y, x**2 + x)
A relation's type can be defined upon creation using
rop
. The relation type of an existing expression can be obtained using itsrel_op
property. Here is a table of all the relation types, along with theirrop
andrel_op
values:Relation
rop
rel_op
Equality
==
oreq
orNone
==
Unequality
!=
orne
!=
GreaterThan
>=
orge
>=
LessThan
<=
orle
<=
StrictGreaterThan
>
orgt
>
StrictLessThan
<
orlt
<
For example, setting
rop
to==
produces anEquality
relation,Eq()
. So does settingrop
toeq
, or leavingrop
unspecified. That is, the first threeRel()
below all produce the same result. Using arop
from a different row in the table produces a different relation type. For example, the fourthRel()
below usinglt
forrop
produces aStrictLessThan
inequality:>>> from sympy import Rel >>> from sympy.abc import x, y >>> Rel(y, x + x**2, '==') Eq(y, x**2 + x) >>> Rel(y, x + x**2, 'eq') Eq(y, x**2 + x) >>> Rel(y, x + x**2) Eq(y, x**2 + x) >>> Rel(y, x + x**2, 'lt') y < x**2 + x
To obtain the relation type of an existing expression, get its
rel_op
property. For example,rel_op
is==
for theEquality
relation above, and<
for the strict less than inequality above:>>> from sympy import Rel >>> from sympy.abc import x, y >>> my_equality = Rel(y, x + x**2, '==') >>> my_equality.rel_op '==' >>> my_inequality = Rel(y, x + x**2, 'lt') >>> my_inequality.rel_op '<'
- property canonical#
返回关系的规范形式,方法是在rhs上加一个数字,以规范方式删除一个符号,或者以规范方式对参数进行排序。不尝试其他简化。
实例
>>> from sympy.abc import x, y >>> x < 2 x < 2 >>> _.reversed.canonical x < 2 >>> (-y < x).canonical x > -y >>> (-y > x).canonical x < -y >>> (-y < -x).canonical x < y
The canonicalization is recursively applied:
>>> from sympy import Eq >>> Eq(x < y, y > x).canonical True
- equals(other, failing_expression=False)[源代码]#
如果关系的两边在数学上相同并且关系的类型相同,则返回True。如果失败的表达式为True,则返回truth值未知的表达式。
- property lhs#
关系的左侧。
- property negated#
返回被否定的关系。
实例
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.negated Ne(x, 1) >>> x < 1 x < 1 >>> _.negated x >= 1
笔记
这或多或少与
~
/Not
. 区别在于negated
返回关系,即使evaluate=False
. 因此,这在代码中非常有用,因为它不会受 \(evaluate\) 旗帜。
- property reversed#
返回双方颠倒的关系。
实例
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.reversed Eq(1, x) >>> x < 1 x < 1 >>> _.reversed 1 > x
- property reversedsign#
返回符号颠倒的关系。
实例
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.reversedsign Eq(-x, -1) >>> x < 1 x < 1 >>> _.reversedsign -x > -1
- property rhs#
关系的右侧。
- property strict#
return the strict version of the inequality or self
实例
>>> from sympy.abc import x >>> (x <= 1).strict x < 1 >>> _.strict x < 1
- property weak#
return the non-strict version of the inequality or self
实例
>>> from sympy.abc import x >>> (x < 1).weak x <= 1 >>> _.weak x <= 1
- sympy.core.relational.Rel[源代码]#
Relational
的别名
- sympy.core.relational.Ne[源代码]#
Unequality
的别名
- sympy.core.relational.Lt[源代码]#
StrictLessThan
的别名
- sympy.core.relational.Ge[源代码]#
GreaterThan
的别名
- class sympy.core.relational.Equality(lhs, rhs, **options)[源代码]#
两个物体之间的相等关系。
解释
表示两个对象相等。如果它们可以很容易地被证明是绝对相等的(或不相等的),这将减少为真(或假)。否则,关系将作为未赋值的相等对象进行维护。使用
simplify
函数来实现对等式关系的更重要的求值。像往常一样,关键字参数
evaluate=False
可以用来防止任何评价。实例
>>> from sympy import Eq, simplify, exp, cos >>> from sympy.abc import x, y >>> Eq(y, x + x**2) Eq(y, x**2 + x) >>> Eq(2, 5) False >>> Eq(2, 5, evaluate=False) Eq(2, 5) >>> _.doit() False >>> Eq(exp(x), exp(x).rewrite(cos)) Eq(exp(x), sinh(x) + cosh(x)) >>> simplify(_) True
笔记
Python将1和True(以及0和False)视为相等,而SymPy则不是。整数总是与布尔值进行比较:
>>> Eq(True, 1), True == 1 (False, True)
此类与==运算符不同。==运算符测试两个表达式之间的结构是否完全相等;此类从数学上比较表达式。
If either object defines an
_eval_Eq
method, it can be used in place of the default algorithm. Iflhs._eval_Eq(rhs)
orrhs._eval_Eq(lhs)
returns anything other than None, that return value will be substituted for the Equality. If None is returned by_eval_Eq
, an Equality object will be created as usual.Since this object is already an expression, it does not respond to the method
as_expr
if one tries to create \(x - y\) fromEq(x, y)
. Ifeq = Eq(x, y)
then write \(eq.lhs - eq.rhs\) to getx - y
.自 1.5 版本弃用:
Eq(expr)
with a single argument is a shorthand forEq(expr, 0)
, but this behavior is deprecated and will be removed in a future version of SymPy.参见
sympy.logic.boolalg.Equivalent
用于表示两个布尔表达式之间的相等
- class sympy.core.relational.GreaterThan(lhs, rhs, **options)[源代码]#
不等式的类表示。
解释
这个
*Than
类表示不相等的关系,其中左手边通常比右手边大或小。例如,GreaterThan类表示一种不相等的关系,其中左侧至少与右侧一样大,如果不是更大的话。在数学符号中:lhs \(\ge\) rhs
总共有四个
*Than
类,表示四个不等式:类名
符号
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
所有的类都有两个参数,lhs和rhs。
签名示例
Math Equivalent
GreaterThan(左、右)
lhs \(\ge\) rhs
LessThan(左、右)
lhs \(\le\) rhs
比(左、右)更严格
lhs \(>\) rhs
严格要求(左、右)
lhs \(<\) rhs
除了正常的.lhs和.rhs关系,
*Than
不等式对象还具有.lts和.gts属性,它们表示运算符的“小于边”和“大于边”。在算法中使用.lts和.gts而不是.lhs和.rhs作为不等式方向的假设,将使特定代码段的意图更加明确,并使其对客户端代码更改更为健壮:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
实例
通常不直接实例化这些类,而是使用各种方便的方法:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more "mathematical looking" statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for 'gotcha', below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
但是,实例化
*Than
不太简洁、不方便:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
笔记
在使用Python操作符时,需要注意几个“问题”。
首先,你写的并不总是你得到的:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.对于控制台来说,这是一个很重要的输出方式,如果可以的话:
在比较之前把字面意思“综合化”
>>> S(1) < x 1 < x
(2) 使用上述包装器或不太简洁的方法之一
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
第二个问题是,当测试的一方或双方涉及到字面关系时,在关系之间编写等式测试:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
这种情况下的解决方案是将文字关系括在括号中:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R146], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
虽然也可以使用“&”运算符,但不能使用“and”运算符:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R146]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using "and" logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the --Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x>y>z
(x>y)和(y>z)
(GreaterThanObject)和(y>z)
(GreaterThanObject.uu booluuu())和(y>z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object's__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.在Python中,无法重写
and
或控制它如何短路,所以不可能做出x > y > z
工作。有人想改变这一切, PEP 335 ,但于2012年3月正式关闭。
- class sympy.core.relational.LessThan(lhs, rhs, **options)[源代码]#
不等式的类表示。
解释
这个
*Than
类表示不相等的关系,其中左手边通常比右手边大或小。例如,GreaterThan类表示一种不相等的关系,其中左侧至少与右侧一样大,如果不是更大的话。在数学符号中:lhs \(\ge\) rhs
总共有四个
*Than
类,表示四个不等式:类名
符号
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
所有的类都有两个参数,lhs和rhs。
签名示例
Math Equivalent
GreaterThan(左、右)
lhs \(\ge\) rhs
LessThan(左、右)
lhs \(\le\) rhs
比(左、右)更严格
lhs \(>\) rhs
严格要求(左、右)
lhs \(<\) rhs
除了正常的.lhs和.rhs关系,
*Than
不等式对象还具有.lts和.gts属性,它们表示运算符的“小于边”和“大于边”。在算法中使用.lts和.gts而不是.lhs和.rhs作为不等式方向的假设,将使特定代码段的意图更加明确,并使其对客户端代码更改更为健壮:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
实例
通常不直接实例化这些类,而是使用各种方便的方法:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more "mathematical looking" statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for 'gotcha', below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
但是,实例化
*Than
不太简洁、不方便:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
笔记
在使用Python操作符时,需要注意几个“问题”。
首先,你写的并不总是你得到的:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.对于控制台来说,这是一个很重要的输出方式,如果可以的话:
在比较之前把字面意思“综合化”
>>> S(1) < x 1 < x
(2) 使用上述包装器或不太简洁的方法之一
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
第二个问题是,当测试的一方或双方涉及到字面关系时,在关系之间编写等式测试:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
这种情况下的解决方案是将文字关系括在括号中:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R147], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
虽然也可以使用“&”运算符,但不能使用“and”运算符:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R147]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using "and" logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the --Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x>y>z
(x>y)和(y>z)
(GreaterThanObject)和(y>z)
(GreaterThanObject.uu booluuu())和(y>z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object's__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.在Python中,无法重写
and
或控制它如何短路,所以不可能做出x > y > z
工作。有人想改变这一切, PEP 335 ,但于2012年3月正式关闭。
- class sympy.core.relational.Unequality(lhs, rhs, **options)[源代码]#
两个物体之间不相等的关系。
解释
表示两个对象不相等。如果它们可以被证明是绝对相等的,这将减少为假;如果绝对不相等,这将减少为真。否则,关系将作为不合格对象进行维护。
实例
>>> from sympy import Ne >>> from sympy.abc import x, y >>> Ne(y, x+x**2) Ne(y, x**2 + x)
笔记
这个班和那个班不一样!=操作员。这个!=运算符测试两个表达式之间的结构是否完全相等;此类从数学上比较表达式。
这类实际上是等式的逆。因此,它使用相同的算法,包括任何可用的算法 \(_eval_Eq\) 方法。
参见
- class sympy.core.relational.StrictGreaterThan(lhs, rhs, **options)[源代码]#
不等式的类表示。
解释
这个
*Than
类表示不相等的关系,其中左手边通常比右手边大或小。例如,GreaterThan类表示一种不相等的关系,其中左侧至少与右侧一样大,如果不是更大的话。在数学符号中:lhs \(\ge\) rhs
总共有四个
*Than
类,表示四个不等式:类名
符号
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
所有的类都有两个参数,lhs和rhs。
签名示例
Math Equivalent
GreaterThan(左、右)
lhs \(\ge\) rhs
LessThan(左、右)
lhs \(\le\) rhs
比(左、右)更严格
lhs \(>\) rhs
严格要求(左、右)
lhs \(<\) rhs
除了正常的.lhs和.rhs关系,
*Than
不等式对象还具有.lts和.gts属性,它们表示运算符的“小于边”和“大于边”。在算法中使用.lts和.gts而不是.lhs和.rhs作为不等式方向的假设,将使特定代码段的意图更加明确,并使其对客户端代码更改更为健壮:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
实例
通常不直接实例化这些类,而是使用各种方便的方法:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more "mathematical looking" statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for 'gotcha', below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
但是,实例化
*Than
不太简洁、不方便:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
笔记
在使用Python操作符时,需要注意几个“问题”。
首先,你写的并不总是你得到的:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.对于控制台来说,这是一个很重要的输出方式,如果可以的话:
在比较之前把字面意思“综合化”
>>> S(1) < x 1 < x
(2) 使用上述包装器或不太简洁的方法之一
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
第二个问题是,当测试的一方或双方涉及到字面关系时,在关系之间编写等式测试:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
这种情况下的解决方案是将文字关系括在括号中:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R148], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
虽然也可以使用“&”运算符,但不能使用“and”运算符:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R148]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using "and" logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the --Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x>y>z
(x>y)和(y>z)
(GreaterThanObject)和(y>z)
(GreaterThanObject.uu booluuu())和(y>z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object's__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.在Python中,无法重写
and
或控制它如何短路,所以不可能做出x > y > z
工作。有人想改变这一切, PEP 335 ,但于2012年3月正式关闭。
- class sympy.core.relational.StrictLessThan(lhs, rhs, **options)[源代码]#
不等式的类表示。
解释
这个
*Than
类表示不相等的关系,其中左手边通常比右手边大或小。例如,GreaterThan类表示一种不相等的关系,其中左侧至少与右侧一样大,如果不是更大的话。在数学符号中:lhs \(\ge\) rhs
总共有四个
*Than
类,表示四个不等式:类名
符号
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
所有的类都有两个参数,lhs和rhs。
签名示例
Math Equivalent
GreaterThan(左、右)
lhs \(\ge\) rhs
LessThan(左、右)
lhs \(\le\) rhs
比(左、右)更严格
lhs \(>\) rhs
严格要求(左、右)
lhs \(<\) rhs
除了正常的.lhs和.rhs关系,
*Than
不等式对象还具有.lts和.gts属性,它们表示运算符的“小于边”和“大于边”。在算法中使用.lts和.gts而不是.lhs和.rhs作为不等式方向的假设,将使特定代码段的意图更加明确,并使其对客户端代码更改更为健壮:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
实例
通常不直接实例化这些类,而是使用各种方便的方法:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more "mathematical looking" statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for 'gotcha', below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
但是,实例化
*Than
不太简洁、不方便:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
笔记
在使用Python操作符时,需要注意几个“问题”。
首先,你写的并不总是你得到的:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.对于控制台来说,这是一个很重要的输出方式,如果可以的话:
在比较之前把字面意思“综合化”
>>> S(1) < x 1 < x
(2) 使用上述包装器或不太简洁的方法之一
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
第二个问题是,当测试的一方或双方涉及到字面关系时,在关系之间编写等式测试:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
这种情况下的解决方案是将文字关系括在括号中:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R149], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
虽然也可以使用“&”运算符,但不能使用“and”运算符:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R149]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using "and" logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the --Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x>y>z
(x>y)和(y>z)
(GreaterThanObject)和(y>z)
(GreaterThanObject.uu booluuu())和(y>z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object's__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.在Python中,无法重写
and
或控制它如何短路,所以不可能做出x > y > z
工作。有人想改变这一切, PEP 335 ,但于2012年3月正式关闭。
多维的#
- class sympy.core.multidimensional.vectorize(*mdargs)[源代码]#
泛化接受多维参数的标量函数。
实例
>>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh'))
>>> @vectorize(0) ... def vsin(x): ... return sin(x)
>>> vsin([1, x, y]) [sin(1), sin(x), sin(y)]
>>> @vectorize(0, 1) ... def vdiff(f, y): ... return diff(f, y)
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z]) [[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
功能#
- class sympy.core.function.Lambda(signature, expr)[源代码]#
Lambda(x,expr)表示一个Lambda函数,类似于Python的“Lambda x:expr”。一个由多个变量组成的函数写成Lambda((x,y,…),expr)。
实例
一个简单的例子:
>>> from sympy import Lambda >>> from sympy.abc import x >>> f = Lambda(x, x**2) >>> f(4) 16
对于多元函数,请使用:
>>> from sympy.abc import y, z, t >>> f2 = Lambda((x, y, z, t), x + y**z + t**z) >>> f2(1, 2, 3, 4) 73
还可以解压缩元组参数:
>>> f = Lambda(((x, y), z), x + y + z) >>> f((1, 2), 3) 6
一个方便快捷的方法来处理很多争论:
>>> p = x, y, z >>> f = Lambda(p, x + y*z) >>> f(*p) x + y*z
- property bound_symbols#
函数内部表示中使用的变量
- property expr#
函数的返回值
- property is_identity#
返回
True
如果这样Lambda
是一个恒等函数。
- property signature#
要解压到变量中的参数的预期形式
- property variables#
函数内部表示中使用的变量
- class sympy.core.function.WildFunction(*args)[源代码]#
WildFunction函数匹配任何函数(及其参数)。
实例
>>> from sympy import WildFunction, Function, cos >>> from sympy.abc import x, y >>> F = WildFunction('F') >>> f = Function('f') >>> F.nargs Naturals0 >>> x.match(F) >>> F.match(F) {F_: F_} >>> f(x).match(F) {F_: f(x)} >>> cos(x).match(F) {F_: cos(x)} >>> f(x, y).match(F) {F_: f(x, y)}
要匹配具有给定数量参数的函数,请设置
nargs
实例化时的期望值:>>> F = WildFunction('F', nargs=2) >>> F.nargs {2} >>> f(x).match(F) >>> f(x, y).match(F) {F_: f(x, y)}
要将函数与一系列参数匹配,请设置
nargs
包含所需数量参数的元组,例如ifnargs = (1, 2)
然后将匹配具有1个或2个参数的函数。>>> F = WildFunction('F', nargs=(1, 2)) >>> F.nargs {1, 2} >>> f(x).match(F) {F_: f(x)} >>> f(x, y).match(F) {F_: f(x, y)} >>> f(x, y, 1).match(F)
- class sympy.core.function.Derivative(expr, *variables, **kwargs)[源代码]#
根据符号对给定表达式进行微分。
实例
>>> from sympy import Derivative, Function, symbols, Subs >>> from sympy.abc import x, y >>> f, g = symbols('f g', cls=Function)
>>> Derivative(x**2, x, evaluate=True) 2*x
导数的密度保留了变量的顺序:
>>> Derivative(Derivative(f(x, y), y), x) Derivative(f(x, y), y, x)
连续相同的符号合并到元组中,该元组给出符号和计数:
>>> Derivative(f(x), x, x, y, x) Derivative(f(x), (x, 2), y, x)
如果导数不能执行,且evaluate为真,则微分变量的顺序将成为规范的:
>>> Derivative(f(x, y), y, x, evaluate=True) Derivative(f(x, y), x, y)
关于未定义函数的导数可以计算:
>>> Derivative(f(x)**2, f(x), evaluate=True) 2*f(x)
当使用链式法则计算导数时,会出现这样的导数:
>>> f(g(x)).diff(x) Derivative(f(g(x)), g(x))*Derivative(g(x), x)
替换用于表示函数的导数,参数不是符号或函数:
>>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3) True
笔记
高阶导数的简化:
因为在执行多个微分时可以进行大量的简化,所以结果将以相当保守的方式自动简化,除非关键字
simplify
设置为False。>>> from sympy import sqrt, diff, Function, symbols >>> from sympy.abc import x, y, z >>> f, g = symbols('f,g', cls=Function)
>>> e = sqrt((x + 1)**2 + x) >>> diff(e, (x, 5), simplify=False).count_ops() 136 >>> diff(e, (x, 5)).count_ops() 30
变量排序:
如果evaluate设置为True并且无法计算表达式,则将对微分符号列表进行排序,也就是说,假定表达式具有连续的导数,直到所要求的顺序为止。
导数与非符号:
在大多数情况下,人们可能无法区分非符号。例如,我们不允许区分wrt \(x*y\) 因为在结构上有多种定义x的方法 y出现在表达式中:一个非常严格的定义将使(x Y z) .diff(x y) ==0。不允许使用与定义函数(如cos(x))相关的导数,或者:
>>> (x*y*z).diff(x*y) Traceback (most recent call last): ... ValueError: Can't calculate derivative wrt x*y.
然而,为了使变分计算更容易进行,允许使用导数和导数。例如,在欧拉-拉格朗日方法中,可以写出F(t,u,v),其中u=F(t)和v=F'(t)。这些变量可以显式地写成时间函数:
>>> from sympy.abc import t >>> F = Function('F') >>> U = f(t) >>> V = U.diff(t)
导数wrt f(t)可直接获得:
>>> direct = F(t, U, V).diff(U)
当尝试区分非符号时,在执行微分时,将非符号临时转换为符号,并获得相同的答案:
>>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U) >>> assert direct == indirect
这种非符号替换的含义是,所有函数都被视为独立于其他函数,并且符号独立于包含它们的函数:
>>> x.diff(f(x)) 0 >>> g(x).diff(f(x)) 0
这也意味着导数只依赖于微分的变量,而不依赖于微分表达式中包含的任何内容:
>>> F = f(x) >>> Fx = F.diff(x) >>> Fx.diff(F) # derivative depends on x, not F 0 >>> Fxx = Fx.diff(x) >>> Fxx.diff(Fx) # derivative depends on x, not Fx 0
最后一个示例可以通过显示用y替换Fxx中的Fx来明确说明:
>>> Fxx.subs(Fx, y) Derivative(y, x)
由于其本身的计算结果为零,因此区分wrt Fx也将为零:
>>> _.doit() 0
用具体表达式替换未定义的函数
用含有与函数定义一致的变量的表达式代替未定义的函数,将得到微分变量或不一致的结果。考虑以下示例:
>>> eq = f(x)*g(y) >>> eq.subs(f(x), x*y).diff(x, y).doit() y*Derivative(g(y), y) + g(y) >>> eq.diff(x, y).subs(f(x), x*y).doit() y*Derivative(g(y), y)
结果不同是因为 \(f(x)\) 被替换为包含两个分化变量的表达式。在抽象情况下,区分 \(f(x)\) 通过 \(y\) 为0;在具体情况下,存在 \(y\) 使衍生产品变得不重要并产生额外的 \(g(y)\) 期限。
定义对象的微分
对象必须定义返回微分结果的.u eval_derivative(symbol)方法。此函数只需要考虑expr包含符号的非平凡情况,它应该在内部调用diff()方法(而不是_eval_derivative);derivative应该是唯一调用_eval_derivative的方法。
任何一个类都可以允许对其自身进行求导(同时表明其标量性质)。请参阅Expr.u diffu wrt的docstring。
- property _diff_wrt#
一个表达式如果是初等形式,就可以与导数区别开来。
实例
>>> from sympy import Function, Derivative, cos >>> from sympy.abc import x >>> f = Function('f')
>>> Derivative(f(x), x)._diff_wrt True >>> Derivative(cos(x), x)._diff_wrt False >>> Derivative(x + 1, x)._diff_wrt False
导数可能是一种未经评估的形式,如果对其进行评估,它将不是有效的微分变量。例如,
>>> Derivative(f(f(x)), x).doit() Derivative(f(x), x)*Derivative(f(f(x)), f(x))
这样的表达将呈现出与处理任何其他产品时产生的相同的歧义,例如
2*x
如此_diff_wrt
是假的:>>> Derivative(f(f(x)), x)._diff_wrt False
- classmethod _sort_variable_count(vc)[源代码]#
将(variable,count)对按规范顺序排序,同时保留微分过程中不交换的变量顺序:
符号和功能相互转换
衍生品相互转换
a derivative does not commute with anything it contains
任何其他物体如果与另一物体有共同的自由符号,则不允许通勤
实例
>>> from sympy import Derivative, Function, symbols >>> vsort = Derivative._sort_variable_count >>> x, y, z = symbols('x y z') >>> f, g, h = symbols('f g h', cls=Function)
连续项被折叠为一对:
>>> vsort([(x, 1), (x, 1)]) [(x, 2)] >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) [(y, 2), (f(x), 2)]
排序是规范的。
>>> def vsort0(*v): ... # docstring helper to ... # change vi -> (vi, 0), sort, and return vi vals ... return [i[0] for i in vsort([(i, 0) for i in v])]
>>> vsort0(y, x) [x, y] >>> vsort0(g(y), g(x), f(y)) [f(y), g(x), g(y)]
符号尽可能向左排序,但决不能移到变量中具有相同符号的导数的左边;这同样适用于始终在符号之后排序的AppliedUndef:
>>> dfx = f(x).diff(x) >>> assert vsort0(dfx, y) == [y, dfx] >>> assert vsort0(dfx, x) == [dfx, x]
- as_finite_difference(points=1, x0=None, wrt=None)[源代码]#
将导数实例表示为有限差分。
- 参数:
点 :序列或系数,可选
If序列:用于生成有限差分权重的自变量的离散值(长度>=阶数+1)。如果它是一个系数,它将被用作生成一个以长度顺序+1为中心的等距序列的步长
x0
. 默认值:1(步长1)x0 :数字或符号,可选
自变量的值 (
wrt
)在这里导数将被近似。默认值:与wrt
.wrt :符号,可选
“关于”要对其(偏)导数进行近似计算的变量。如果没有规定,则要求衍生工具是普通的。违约:
None
.
实例
>>> from sympy import symbols, Function, exp, sqrt, Symbol >>> x, h = symbols('x h') >>> f = Function('f') >>> f(x).diff(x).as_finite_difference() -f(x - 1/2) + f(x + 1/2)
默认步长和点数为1和
order + 1
分别。我们可以通过传递符号作为参数来更改步长:>>> f(x).diff(x).as_finite_difference(h) -f(-h/2 + x)/h + f(h/2 + x)/h
我们还可以指定要在序列中使用的离散化值:
>>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h]) -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
该算法不局限于使用等距间距,也不需要进行近似处理
x0
,但我们可以得到一个估计偏移处导数的表达式:>>> e, sq2 = exp(1), sqrt(2) >>> xl = [x-h, x+h, x+e*h] >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...
近似
Derivative
围绕x0
使用非等距间距步长,该算法支持将未定义函数赋值给points
:>>> dx = Function('dx') >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h) -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x)
也支持偏导数:
>>> y = Symbol('y') >>> d2fdxdy=f(x,y).diff(x,y) >>> d2fdxdy.as_finite_difference(wrt=x) -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
我们可以申请
as_finite_difference
到Derivative
复合表达式中的实例使用replace
:>>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative, ... lambda arg: arg.as_finite_difference()) 42**(-f(x - 1/2) + f(x + 1/2)) + 1
- sympy.core.function.diff(f, *symbols, **kwargs)[源代码]#
根据符号区分f。
解释
这只是unify.diff()和派生类的包装器;它的接口类似于integrate()的接口。对于多个变量,可以使用与导数相同的快捷方式。例如,diff(f(x),x,x,x)和diff(f(x),x,3)都返回f(x)的三阶导数。
可以传递evaluate=False以获取未赋值的派生类。注意,如果有0个符号(例如diff(f(x),x,0),那么结果将是函数(第零阶导数),即使evaluate=False。
实例
>>> from sympy import sin, cos, Function, diff >>> from sympy.abc import x, y >>> f = Function('f')
>>> diff(sin(x), x) cos(x) >>> diff(f(x), x, x, x) Derivative(f(x), (x, 3)) >>> diff(f(x), x, 3) Derivative(f(x), (x, 3)) >>> diff(sin(x)*cos(y), x, 2, y, 2) sin(x)*cos(y)
>>> type(diff(sin(x), x)) cos >>> type(diff(sin(x), x, evaluate=False)) <class 'sympy.core.function.Derivative'> >>> type(diff(sin(x), x, 0)) sin >>> type(diff(sin(x), x, 0, evaluate=False)) sin
>>> diff(sin(x)) cos(x) >>> diff(sin(x*y)) Traceback (most recent call last): ... ValueError: specify differentiation variables to differentiate sin(x*y)
注意
diff(sin(x))
语法只是为了方便交互会话,在库代码中应该避免使用。工具书类
- class sympy.core.function.FunctionClass(*args, **kwargs)[源代码]#
函数类的基类。FunctionClass是类型的子类。
使用函数('<Function name>' [,签名] )创建未定义的函数类。
- property nargs#
返回函数的一组允许数量的参数。
实例
>>> from sympy import Function >>> f = Function('f')
如果函数可以接受任意数量的参数,则返回整数集:
>>> Function('f').nargs Naturals0
如果函数初始化为接受一个或多个参数,则将返回相应的集:
>>> Function('f', nargs=1).nargs {1} >>> Function('f', nargs=(2, 1)).nargs {1, 2}
在application之后,未定义函数还具有nargs属性;通过检查
args
属性:>>> f = Function('f') >>> f(1).nargs Naturals0 >>> len(f(1).args) 1
- class sympy.core.function.Function(*args)[源代码]#
应用数学函数的基类。
它还充当未定义函数类的构造函数。
See the Writing Custom Functions guide for details on how to subclass
Function
and what methods can be defined.实例
Undefined Functions
To create an undefined function, pass a string of the function name to
Function
.>>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> g = Function('g')(x) >>> f f >>> f(x) f(x) >>> g g(x) >>> f(x).diff(x) Derivative(f(x), x) >>> g.diff(x) Derivative(g(x), x)
Assumptions can be passed to
Function
the same as with aSymbol
. Alternatively, you can use aSymbol
with assumptions for the function name and the function will inherit the name and assumptions associated with theSymbol
:>>> f_real = Function('f', real=True) >>> f_real(x).is_real True >>> f_real_inherit = Function(Symbol('f', real=True)) >>> f_real_inherit(x).is_real True
Note that assumptions on a function are unrelated to the assumptions on the variables it is called on. If you want to add a relationship, subclass
Function
and define custom assumptions handler methods. See the Assumptions section of the Writing Custom Functions guide for more details.Custom Function Subclasses
The Writing Custom Functions guide has several Complete Examples of how to subclass
Function
to create a custom function.
备注
不是所有的功能都是一样的
SymPy定义了许多函数(比如 cos
和 factorial
). 它还允许用户创建作为参数持有者的泛型函数。这些函数的创建就像符号一样:
>>> from sympy import Function, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> f(2) + f(x)
f(2) + f(x)
如果要查看表达式中出现的函数,可以使用atoms方法:
>>> e = (f(x) + cos(x) + 2)
>>> e.atoms(Function)
{f(x), cos(x)}
如果您只需要定义的函数,而不是SymPy函数,则需要搜索AppliedUndef:
>>> from sympy.core.function import AppliedUndef
>>> e.atoms(AppliedUndef)
{f(x)}
- class sympy.core.function.Subs(expr, variables, point, **assumptions)[源代码]#
表示表达式的未赋值替换。
Subs(expr, x, x0)
表示在表达式中用x0替换x而得到的表达式。- 参数:
expr :表达式
一个表情。
x :元组,变量
变量一个变量或一系列不同的变量。
x0 :元组或元组列表
与这些变量相对应的一个点或一系列评估点。
实例
>>> from sympy import Subs, Function, sin, cos >>> from sympy.abc import x, y, z >>> f = Function('f')
sub是在无法进行特定替换时创建的。导数中的x不能替换为0,因为0不是有效的微分变量:
>>> f(x).diff(x).subs(x, 0) Subs(Derivative(f(x), x), x, 0)
一旦f已知,就可以在0处进行导数和求值:
>>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) True
也可以使用一个或多个变量直接创建SUB:
>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) Subs(z + f(x)*sin(y), (x, y), (0, 1)) >>> _.doit() z + f(0)*sin(1)
笔记
Subs
objects are generally useful to represent unevaluated derivatives calculated at a point.The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity.
There's no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression.
When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()).
为了允许表达式在doit完成之前组合,Subs表达式的表示在内部使用,以使表面上不同的表达式比较相同:
>>> a, b = Subs(x, x, 0), Subs(y, y, 0) >>> a + b 2*Subs(x, x, 0)
当使用以下方法时,这可能会导致意想不到的后果 \(has\) 缓存的:
>>> s = Subs(x, x, 0) >>> s.has(x), s.has(y) (True, False) >>> ss = s.subs(x, y) >>> ss.has(x), ss.has(y) (True, False) >>> s, ss (Subs(x, x, 0), Subs(y, y, 0))
- property bound_symbols#
要评估的变量
- property expr#
替换操作的表达式
- property point#
要替换变量的值
- property variables#
要评估的变量
- sympy.core.function.expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[源代码]#
使用作为提示提供的方法展开表达式。
解释
除非显式设置为False,否则计算的提示包括:
basic
,log
,multinomial
,mul
,power_base
和power_exp
支持以下提示,但除非设置为True,否则不应用:complex
,func
和trig
. 此外,某些或所有其他提示都支持以下元提示:frac
,numer
,denom
,modulus
和force
.deep
由所有提示支持。此外,Expr的子类可以定义它们自己的提示或元提示。这个
basic
hint用于任何应该自动完成的对象的特殊重写(与其他提示一起使用,比如mul
)调用扩展时。这是一个catch all提示,用于处理现有提示名称可能无法描述的任何类型的扩展。要使用此提示,对象应重写_eval_expand_basic
方法。对象还可以定义自己的展开方法,这些方法在默认情况下不运行。请参阅下面的API部分。如果
deep
设置为True
(默认情况下),函数的参数会递归地展开。使用deep=False
只在顶层扩展。如果
force
如果使用提示,则在进行展开时将忽略有关变量的假设。提示
默认情况下运行这些提示
骡子
在加法上分配乘法:
>>> from sympy import cos, exp, sin >>> from sympy.abc import x, y, z >>> (y*(x + z)).expand(mul=True) x*y + y*z
多项式
展开(x+y+…)**n,其中n是正整数。
>>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
Power_exp
将指数的加法展开为乘法基。
>>> exp(x + y).expand(power_exp=True) exp(x)*exp(y) >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y
Power_base
乘法基的分裂幂。
只有在假设允许的情况下,或者
force
使用了元提示:>>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z
注意,在某些情况下,此扩展始终保持不变,Symphy会自动执行:
>>> (x*y)**2 x**2*y**2
日志
把参数的幂作为一个系数,把对数乘积分解成对数的和。
注意,只有当log函数的参数具有正确的假设时,这些参数才有效——参数必须是正的,指数必须是实的——否则
force
提示必须为真:>>> from sympy import log, symbols >>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x,y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y)
基本的
此提示主要用于自定义子类在默认情况下启用扩展。
默认情况下不运行这些提示:
复杂的
把一个表达式分成实部和虚部。
>>> x, y = symbols('x,y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
请注意,这只是一个包装
as_real_imag()
. 大多数希望重新定义的对象_eval_expand_complex()
应该考虑重新定义as_real_imag()
相反。函数
展开其他功能。
>>> from sympy import gamma >>> gamma(x + 1).expand(func=True) x*gamma(x)
触发
做三角展开。
>>> cos(x + y).expand(trig=True) -sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x)
Note that the forms of
sin(n*x)
andcos(n*x)
in terms ofsin(x)
andcos(x)
are not unique, due to the identity \(\sin^2(x) + \cos^2(x) = 1\). The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See this MathWorld article for more information.笔记
您可以关闭不需要的方法:
>>> (exp(x + y)*(x + y)).expand() x*exp(x)*exp(y) + y*exp(x)*exp(y) >>> (exp(x + y)*(x + y)).expand(power_exp=False) x*exp(x + y) + y*exp(x + y) >>> (exp(x + y)*(x + y)).expand(mul=False) (x + y)*exp(x)*exp(y)
使用deep=False仅在顶层展开:
>>> exp(x + exp(x + y)).expand() exp(x)*exp(exp(x)*exp(y)) >>> exp(x + exp(x + y)).expand(deep=False) exp(x)*exp(exp(x + y))
提示以任意但一致的顺序应用(在当前的实现中,它们是按字母顺序应用的,除了mul前面是多项式,但这可能会改变)。因此,如果先应用某些提示,则可能会阻止其他提示的扩展。例如,
mul
可以分配乘法并阻止log
和power_base
从扩大他们。另外,如果mul
应用于multinomial`, the expression might not be fully distributed. The solution is to use the various `` 展开“helper functions”或 ``hint=False
以精确控制应用哪些提示。以下是一些例子:>>> from sympy import expand, expand_mul, expand_power_base >>> x, y, z = symbols('x,y,z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z)
这里,我们看到了
log
以前申请过mul
. 要获得mul扩展表单,以下任一操作都有效:>>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z)
类似的事情也可能发生在
power_base
提示:>>> expand((x*(y + z))**x) (x*y + x*z)**x
为了得到
power_base
展开窗体,以下任一操作都可以:>>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x
一个有理表达式的部分可以是有针对性的:
>>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x)
这个
modulus
元提示可用于在展开后减少表达式的系数:>>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1
要么
expand()
功能或.expand()
这种方法是可行的。两者相当:>>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1
应用程序编程接口
对象可以通过定义
_eval_expand_hint()
. 函数应采用以下形式:def _eval_expand_hint(self, **hints): # Only apply the method to the top-level expression ...
另请参见下面的示例。对象应该定义
_eval_expand_hint()
方法仅当hint
应用于该特定对象。通用的_eval_expand_hint()
Expr中定义的方法将处理no-op情况。每个提示只负责扩展该提示。此外,扩展应该只应用于顶层表达式。
expand()
处理当deep=True
.你应该打电话给我
_eval_expand_hint()
如果您100%确定对象具有该方法,则直接使用方法,否则您可能会遇到意外情况AttributeError
s、 再次注意,您不需要递归地将提示应用于对象的参数:这是由expand()
._eval_expand_hint()
一般不应在_eval_expand_hint()
方法。如果要从另一个方法中应用特定的扩展,请使用publicexpand()
函数、方法或expand_hint()
功能。为了使扩展工作,对象必须由其参数重建,即。,
obj.func(*obj.args) == obj
必须坚持住。扩展方法被传递
**hints
所以扩展提示可以使用“metahints”—控制如何应用不同扩展方法的提示。例如force=True
上面描述的提示expand(log=True)
忽略假设就是这样一个元暗示。这个deep
元提示由独占处理expand()
而不是传递给_eval_expand_hint()
方法。注意,扩展提示通常应该是执行某种“扩展”的方法。对于简单重写表达式的提示,请使用.rewrite()API。
实例
>>> from sympy import Expr, sympify >>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, *, force=False, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
- sympy.core.function.count_ops(expr, visual=False)[源代码]#
返回表达式中操作的表示形式(整数或表达式)。
- 参数:
expr :表达式
如果expr是iterable,则返回项的运算计数之和。
视觉的 :bool,可选
如果
False
(默认)然后返回可视表达式的系数之和。如果True
然后用核心类类型(或它们的虚拟等价物)乘以它们发生的次数来显示每种操作类型的数量。
实例
>>> from sympy.abc import a, b, x, y >>> from sympy import sin, count_ops
Although there is not a SUB object, minus signs are interpreted as either negations or subtractions:
>>> (x - y).count_ops(visual=True) SUB >>> (-x).count_ops(visual=True) NEG
这里有两个加法和一个Pow:
>>> (1 + a + b**2).count_ops(visual=True) 2*ADD + POW
在下面,一个Add、Mul、Pow和两个函数:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=True) ADD + MUL + POW + 2*SIN
总共5个:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 5
请注意,“你输入的”并不总是你得到的。表达式1/x/y由sympy转换为1/(x*y),因此它给出一个DIV和MUL,而不是两个DIV:
>>> (1/x/y).count_ops(visual=True) DIV + MUL
visual选项可用于演示不同形式表达式的操作差异。这里,Horner表示与多项式的展开形式进行了比较:
>>> eq=x*(1 + x*(2 + x*(3 + x))) >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) -MUL + 3*POW
count_ops函数还处理ITerable:
>>> count_ops([x, sin(x), None, True, x + 2], visual=False) 2 >>> count_ops([x, sin(x), None, True, x + 2], visual=True) ADD + SIN >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 2*ADD + SIN
- sympy.core.function.expand_mul(expr, deep=True)[源代码]#
只使用mul提示的包装扩展。有关详细信息,请参见展开docstring。
实例
>>> from sympy import symbols, expand_mul, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
- sympy.core.function.expand_log(expr, deep=True, force=False, factor=False)[源代码]#
只使用日志提示的包装器。有关详细信息,请参见展开docstring。
实例
>>> from sympy import symbols, expand_log, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) (x + y)*(log(x) + 2*log(y))*exp(x + y)
- sympy.core.function.expand_func(expr, deep=True)[源代码]#
只使用func提示的包装器。有关详细信息,请参见展开docstring。
实例
>>> from sympy import expand_func, gamma >>> from sympy.abc import x >>> expand_func(gamma(x + 2)) x*(x + 1)*gamma(x)
- sympy.core.function.expand_trig(expr, deep=True)[源代码]#
只使用trig提示的包装器。有关详细信息,请参见展开docstring。
实例
>>> from sympy import expand_trig, sin >>> from sympy.abc import x, y >>> expand_trig(sin(x+y)*(x+y)) (x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
- sympy.core.function.expand_complex(expr, deep=True)[源代码]#
只使用复杂提示的包装器。有关详细信息,请参见展开docstring。
实例
>>> from sympy import expand_complex, exp, sqrt, I >>> from sympy.abc import z >>> expand_complex(exp(z)) I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) >>> expand_complex(sqrt(I)) sqrt(2)/2 + sqrt(2)*I/2
- sympy.core.function.expand_multinomial(expr, deep=True)[源代码]#
只使用多项式提示的包装器扩展。有关详细信息,请参见展开docstring。
实例
>>> from sympy import symbols, expand_multinomial, exp >>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
- sympy.core.function.expand_power_exp(expr, deep=True)[源代码]#
只使用poweru exp提示的包装器。
有关详细信息,请参见展开docstring。
实例
>>> from sympy import expand_power_exp, Symbol >>> from sympy.abc import x, y >>> expand_power_exp(3**(y + 2)) 9*3**y >>> expand_power_exp(x**(y + 2)) x**(y + 2)
If
x = 0
the value of the expression depends on the value ofy
; if the expression were expanded the result would be 0. So expansion is only done ifx != 0
:>>> expand_power_exp(Symbol('x', zero=False)**(y + 2)) x**2*x**y
- sympy.core.function.expand_power_base(expr, deep=True, force=False)[源代码]#
只使用poweru base提示的扩展包装器。
一种扩展的包装器(power_base=True),它将一个幂与一个Mul的基分离成幂的乘积,而不执行任何其他展开,前提是关于幂的基和指数的假设允许。
deep=False(默认值为True)将仅应用于顶级表达式。
force=True(默认值为False)将导致展开忽略关于基数和指数的假设。只有当基指数为负时,才会发生非整数展开。
>>> from sympy.abc import x, y, z >>> from sympy import expand_power_base, sin, cos, exp, Symbol
>>> (x*y)**2 x**2*y**2
>>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y
>>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x) 2**x*exp(y)**x
>>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y
请注意,金额未被更改。如果这不是所需的行为,请完全应用
expand()
对于表达式:>>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y**(z + 1)
The power that is unexpanded can be expanded safely when
y != 0
, otherwise different values might be obtained for the expression:>>> prev = _
If we indicate that
y
is positive but then replace it with a value of 0 after expansion, the expression becomes 0:>>> p = Symbol('p', positive=True) >>> prev.subs(y, p).expand().subs(p, 0) 0
But if
z = -1
the expression would not be zero:>>> prev.subs(y, 0).subs(z, -1) 1
参见
- sympy.core.function.nfloat(expr, n=15, exponent=False, dkeys=False)[源代码]#
Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True) and those in undefined functions. When processing dictionaries, do not modify the keys unless
dkeys=True
.实例
>>> from sympy import nfloat, cos, pi, sqrt >>> from sympy.abc import x, y >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5
不修改容器类型:
>>> type(nfloat((1, 2))) is tuple True
埃瓦尔#
- class sympy.core.evalf.EvalfMixin[源代码]#
Mixin class adding evalf capability.
- evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)[源代码]#
计算给定公式的精度 n 数字。
- 参数:
subs :dict,可选
用数值代替符号,例如。
subs={{x:3, y:1+pi}}
. 替换词必须作为字典给出。maxn :int,可选
允许最大临时工作精度为maxn位数。
chop :bool或number,可选
指定如何将子结果中的微小实部或虚部替换为精确的零。
什么时候?
True
chop值默认为标准精度。否则,将使用chop值来确定“small”的大小,以便进行切分。
>>> from sympy import N >>> x = 1e-4 >>> N(x, chop=True) 0.000100000000000000 >>> N(x, chop=1e-5) 0.000100000000000000 >>> N(x, chop=1e-4) 0
严格的 :bool,可选
提高
PrecisionExhausted
如果任何子结果不能完全精确地计算,给定可用的maxprec。quad :str,可选
选择数值求积的算法。默认情况下,使用tanh-sinh求积。对于无限区间上的振荡积分,尝试
quad='osc'
.冗长的 :bool,可选
打印调试信息。
笔记
当浮点被天真地替换到表达式中时,精度错误可能会对结果产生不利影响。例如,将1e16(浮点)加到1将截断为1e16;如果再减去1e16,结果将为0。这正是发生在下面的情况:
>>> from sympy.abc import x, y, z >>> values = {x: 1e16, y: 1, z: 1e16} >>> (x + y - z).subs(values) 0
使用evalf的subs参数是计算此类表达式的准确方法:
>>> (x + y - z).evalf(subs=values) 1.00000000000000
- n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)[源代码]#
计算给定公式的精度 n 数字。
- 参数:
subs :dict,可选
用数值代替符号,例如。
subs={{x:3, y:1+pi}}
. 替换词必须作为字典给出。maxn :int,可选
允许最大临时工作精度为maxn位数。
chop :bool或number,可选
指定如何将子结果中的微小实部或虚部替换为精确的零。
什么时候?
True
chop值默认为标准精度。否则,将使用chop值来确定“small”的大小,以便进行切分。
>>> from sympy import N >>> x = 1e-4 >>> N(x, chop=True) 0.000100000000000000 >>> N(x, chop=1e-5) 0.000100000000000000 >>> N(x, chop=1e-4) 0
严格的 :bool,可选
提高
PrecisionExhausted
如果任何子结果不能完全精确地计算,给定可用的maxprec。quad :str,可选
选择数值求积的算法。默认情况下,使用tanh-sinh求积。对于无限区间上的振荡积分,尝试
quad='osc'
.冗长的 :bool,可选
打印调试信息。
笔记
当浮点被天真地替换到表达式中时,精度错误可能会对结果产生不利影响。例如,将1e16(浮点)加到1将截断为1e16;如果再减去1e16,结果将为0。这正是发生在下面的情况:
>>> from sympy.abc import x, y, z >>> values = {x: 1e16, y: 1, z: 1e16} >>> (x + y - z).subs(values) 0
使用evalf的subs参数是计算此类表达式的准确方法:
>>> (x + y - z).evalf(subs=values) 1.00000000000000
容器#
- class sympy.core.containers.Tuple(*args, **kwargs)[源代码]#
包装内置元组对象。
- 参数:
同情 布尔
If
False
,sympify
is not called onargs
. This can be used for speedups for very large tuples where the elements are known to already be SymPy objects.
解释
Tuple是Basic的一个子类,因此它在SymPy框架中工作得很好。包装的元组可用作自身参数,但也可以使用 [:] 语法。
实例
>>> from sympy import Tuple, symbols >>> a, b, c, d = symbols('a b c d') >>> Tuple(a, b, c)[1:] (b, c) >>> Tuple(a, b, c).subs(a, d) (d, b, c)
- property kind#
The kind of a Tuple instance.
The kind of a Tuple is always of
TupleKind
but parametrised by the number of elements and the kind of each element.实例
>>> from sympy import Tuple, Matrix >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(Matrix([1, 2]), 1).kind TupleKind(MatrixKind(NumberKind), NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind)
- class sympy.core.containers.TupleKind(*args)[源代码]#
TupleKind is a subclass of Kind, which is used to define Kind of
Tuple
.Parameters of TupleKind will be kinds of all the arguments in Tuples, for example
- 参数:
args : tuple(element_kind)
element_kind is kind of element. args is tuple of kinds of element
实例
>>> from sympy import Tuple >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind)
- class sympy.core.containers.Dict(*args)[源代码]#
Wrapper around the builtin dict object.
解释
Dict是Basic的一个子类,因此它在SymPy框架中工作得很好。因为它是不可变的,所以它可以包含在集合中,但是它的值必须在实例化时给出,并且以后不能更改。否则它的行为与Python dict相同。
实例
>>> from sympy import Dict, Symbol
>>> D = Dict({1: 'one', 2: 'two'}) >>> for key in D: ... if key == 1: ... print('%s %s' % (key, D[key])) 1 one
参数被联合,因此1和2是整数,值是符号。查询会自动对参数进行语法化,以便执行以下操作:
>>> 1 in D True >>> D.has(Symbol('one')) # searches keys and values True >>> 'one' in D # not in the keys False >>> D[1] one
实验工具#
- sympy.core.exprtools.gcd_terms(terms, isprimitive=False, clear=True, fraction=True)[源代码]#
计算
terms
把它们放在一起。- 参数:
条款 :表达式
可以是一个表达式,也可以是一个非基本的表达式序列,这些表达式将被当作和中的项来处理。
基本的 :bool,可选
如果
isprimitive
为True,u gcd_terms将不会对项运行基元方法。清楚的 :bool,可选
它控制从加法表达式的分母中移除整数。如果为True(默认),则清除所有数字分母;如果为False,则只有当所有术语的数字分母不是1时,才会清除分母。
分数 :bool,可选
如果为True(默认值),则将表达式置于公共分母之上。
实例
>>> from sympy import gcd_terms >>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False) (x**2/2 + 1)/(x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False) (x/2 + 1/x)/y
这个
clear
在这种情况下,标志被忽略,因为返回的表达式是一个有理表达式,而不是一个简单的和。
- sympy.core.exprtools.factor_terms(expr, radical=False, clear=False, fraction=False, sign=True)[源代码]#
在不改变expr的底层结构的情况下,从所有参数的术语中删除公共因子。不执行扩展或简化(以及不可交换的处理)。
- 参数:
字根:布尔,可选
如果radical=True,则所有项的公共根将从表达式的任何Add子表达式中分解出来。
清楚的 :bool,可选
如果clear=False(默认值),则系数将不会从单个加法中分离出来,前提是它们可以分布为一个或多个项与整数系数。
分数 :bool,可选
如果分数=True(默认为False),则将为表达式构造一个公共分母。
sign :bool,可选
如果sign=True(默认值),那么即使唯一的公共因子是-1,它也将被从表达式中分解出来。
实例
>>> from sympy import factor_terms, Symbol >>> from sympy.abc import x, y >>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A)
什么时候?
clear
为假,则只有当加法的所有项都有分数的系数时,有理数才会从加法表达式中分解出来:>>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2
如果-1是唯一可以被分解的因子,则 not 算了吧,旗子
sign
必须为False:>>> factor_terms(-x - y) -(x + y) >>> factor_terms(-x - y, sign=False) -x - y >>> factor_terms(-2*x - 2*y, sign=False) -2*(x + y)
kind#
- class sympy.core.kind.Kind(*args)[源代码]#
Base class for kinds.
Kind of the object represents the mathematical classification that the entity falls into. It is expected that functions and classes recognize and filter the argument by its kind.
Kind of every object must be carefully selected so that it shows the intention of design. Expressions may have different kind according to the kind of its arguments. For example, arguments of
Add
must have common kind since addition is group operator, and the resultingAdd()
has the same kind.For the performance, each kind is as broad as possible and is not based on set theory. For example,
NumberKind
includes not only complex number but expression containingS.Infinity
orS.NaN
which are not strictly number.Kind may have arguments as parameter. For example,
MatrixKind()
may be constructed with one element which represents the kind of its elements.Kind
behaves in singleton-like fashion. Same signature will return the same object.
- sympy.core.kind.NumberKind#
NumberKind 的别名
- sympy.core.kind.UndefinedKind#
UndefinedKind 的别名
- sympy.core.kind.BooleanKind#
BooleanKind 的别名
Sorting#
- sympy.core.sorting.default_sort_key(item, order=None)[源代码]#
Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
item
is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key.The
order
argument is passed along to the sort_key routine and is used to determine how the terms within an expression are ordered. (See examples below)order
options are: 'lex', 'grlex', 'grevlex', and reversed values of the same (e.g. 'rev-lex'). The default order value is None (which translates to 'lex').实例
>>> from sympy import S, I, default_sort_key, sin, cos, sqrt >>> from sympy.core.function import UndefinedFunction >>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x) True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f')) ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key('1') ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key(S.One) ((1, 0, 'Number'), (0, ()), (), 1) >>> default_sort_key(2) ((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 does not have a sort_key method; that's why default_sort_key is used. Note, that it also handles sympification of non-string items likes ints:
>>> a = [2, I, -I] >>> sorted(a, key=default_sort_key) [2, -I, I]
The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key); a[0] 2 >>> min(a, key=default_sort_key) 2
笔记
The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions:
>>> a, b = x, 1/x
Since
a
has only 1 term, its value of sort_key is unaffected byorder
:>>> a.sort_key() == a.sort_key('rev-lex') True
If
a
andb
are combined then the key will differ because there are terms that can be ordered:>>> eq = a + b >>> eq.sort_key() == eq.sort_key('rev-lex') False >>> eq.as_ordered_terms() [x, 1/x] >>> eq.as_ordered_terms('rev-lex') [1/x, x]
But since the keys for each of these terms are independent of
order
's value, they do not sort differently when they appear separately in a list:>>> sorted(eq.args, key=default_sort_key) [1/x, x] >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex')) [1/x, x]
The order of terms obtained when using these keys is the order that would be obtained if those terms were factors in a product.
Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others:
>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key) [sin(x)*cos(x), sin(x)] >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key) [sqrt(x), x, x**2, x**3]
- sympy.core.sorting.ordered(seq, keys=None, default=True, warn=False)[源代码]#
返回一个seq的迭代器,其中使用键以保守的方式断开连接:如果在应用一个键之后,没有连接,则不会计算其他键。
Two default keys will be applied if 1) keys are not provided or 2) the given keys do not resolve all ties (but only if
default
is True). The two keys are_nodes
(which places smaller expressions before large) anddefault_sort_key
which (if thesort_key
for an object is defined properly) should resolve any ties. This strategy is similar to sorting done byBasic.compare
, but differs in thatordered
never makes a decision based on an objects name.如果
warn
为True,则如果没有剩余的密钥来断开连接,则将引发错误。如果预期不完全相同的项之间不应有关联,则可以使用此项。实例
>>> from sympy import ordered, count_ops >>> from sympy.abc import x, y
count_ops不足以打破此列表中的联系,前两项按其原始顺序显示(即排序稳定):
>>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3]
默认的“排序”键允许断开领带:
>>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3]
在这里,序列按长度排序,然后求和:
>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
如果
warn
为True,则如果没有足够的密钥来断开连接,则将引发错误:>>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties
笔记
装饰排序是对需要进行特殊项目比较的序列进行排序的最快方法之一:对序列进行装饰,根据装饰进行排序(例如,将所有字母都小写),然后取消装饰。如果要断开具有相同装饰值的项目的关系,可以使用第二个键。但是,如果第二个键的计算成本很高,那么用两个键装饰所有的项是低效的:只有那些第一个键值相同的项才需要被修饰。此功能仅在需要断开连接时连续应用按键。通过生成一个迭代器,可以尽可能长时间地延迟使用连接中断器。
当第一个键的使用被认为是一个好的散列函数时,最好使用这个函数;如果在应用某个键时没有唯一的散列,则不应该使用该键。如果一个不需要排序的项目在一开始就不需要多个项目,但是如果一个项目不需要在一个小的项目中进行排序,那么就不必浪费时间了。例如,如果在一个列表中查找最小值,并且有多个标准用于定义排序顺序,那么如果第一组候选项相对于正在处理的项的数量而言很小,则此函数将擅长于快速返回。
Random#
When you need to use random numbers in SymPy library code, import from here
so there is only one generator working for SymPy. Imports from here should
behave the same as if they were being imported from Python's random module.
But only the routines currently used in SymPy are included here. To use others
import rng
and access the method directly. For example, to capture the
current state of the generator use rng.getstate()
.
There is intentionally no Random to import from here. If you want
to control the state of the generator, import seed
and call it
with or without an argument to set the state.
实例#
>>> from sympy.core.random import random, seed
>>> assert random() < 1
>>> seed(1); a = random()
>>> b = random()
>>> seed(1); c = random()
>>> assert a == c
>>> assert a != b # remote possibility this will fail
- sympy.core.random.random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None)[源代码]#
返回一个随机复数。
为了减少碰到分支切口或任何东西的机会,我们保证b<=imz<=d,a<=rez<=c
当有理数为真时,在指定的公差(如果有的话)内可以获得对随机数的有理逼近。
- sympy.core.random.verify_numerically(f, g, z=None, tol=1e-06, a=2, b=-1, c=3, d=1)[源代码]#
用数值方法测试f和g在自变量z中求值时是否一致。
如果z为“无”,则将测试所有符号。此例程不测试是否存在精度高于15位的浮点,因此如果存在,则由于舍入错误,结果可能与预期不符。
实例
>>> from sympy import sin, cos >>> from sympy.abc import x >>> from sympy.core.random import verify_numerically as tn >>> tn(sin(x)**2 + cos(x)**2, 1, x) True
- sympy.core.random.test_derivative_numerically(f, z, tol=1e-06, a=2, b=-1, c=3, d=1)[源代码]#
用数值方法测试f相对于z的导数是否正确。
此例程不测试是否存在精度高于15位的浮点,因此如果存在,则由于舍入错误,结果可能与预期不符。
实例
>>> from sympy import sin >>> from sympy.abc import x >>> from sympy.core.random import test_derivative_numerically as td >>> td(sin(x), x) True
- sympy.core.random._randrange(seed=None)[源代码]#
Return a randrange generator.
seed
can beNone - return randomly seeded generator
int - return a generator seeded with the int
list - the values to be returned will be taken from the list in the order given; the provided list is not modified.
实例
>>> from sympy.core.random import _randrange >>> rr = _randrange() >>> rr(1000) 999 >>> rr = _randrange(3) >>> rr(1000) 238 >>> rr = _randrange([0, 5, 1, 3, 4]) >>> rr(3), rr(3) (0, 1)
- sympy.core.random._randint(seed=None)[源代码]#
Return a randint generator.
seed
can beNone - return randomly seeded generator
int - return a generator seeded with the int
list - the values to be returned will be taken from the list in the order given; the provided list is not modified.
实例
>>> from sympy.core.random import _randint >>> ri = _randint() >>> ri(1, 1000) 999 >>> ri = _randint(3) >>> ri(1, 1000) 238 >>> ri = _randint([0, 5, 1, 2, 4]) >>> ri(1, 3), ri(1, 3) (1, 2)
Traversal#
- sympy.core.traversal.bottom_up(rv, F, atoms=False, nonbasic=False)[源代码]#
Apply
F
to all expressions in an expression tree from the bottom up. Ifatoms
is True, applyF
even if there are no args; ifnonbasic
is True, try to applyF
to non-Basic objects.
- sympy.core.traversal.postorder_traversal(node, keys=None)[源代码]#
对树进行后序遍历。
这个生成器递归地生成它以后序方式访问过的节点。也就是说,在生成节点本身之前,它首先通过树的深度下降以生成节点的所有子节点的后序遍历。
- 参数:
node : SymPy expression
要遍历的表达式。
keys :(默认无)排序键
用于对基本对象的参数进行排序的键。如果没有,则以任意顺序处理基本对象的参数。如果定义了key,它将作为惟一用于对参数排序的键传递给ordered();如果
key
,则ordered
将使用(节点计数和默认的“排序”键)。- 产量:
subtree : SymPy expression
树中的所有子树。
实例
>>> from sympy import postorder_traversal >>> from sympy.abc import w, x, y, z
除非给出key,否则将按遇到的顺序返回节点;只要传递key=True就可以保证遍历是唯一的。
>>> list(postorder_traversal(w + (x + y)*z)) [z, y, x, x + y, z*(x + y), w, w + z*(x + y)] >>> list(postorder_traversal(w + (x + y)*z, keys=True)) [w, z, x, y, x + y, z*(x + y), w + z*(x + y)]
- sympy.core.traversal.preorder_traversal(node, keys=None)[源代码]#
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a pre-order fashion. That is, it yields the current node then descends through the tree breadth-first to yield all of a node's children's pre-order traversal.
For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary.
- 参数:
node : SymPy expression
要遍历的表达式。
keys :(默认无)排序键
The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if
key
is simply True then the default keys of ordered will be used.- 产量:
subtree : SymPy expression
树中的所有子树。
实例
>>> from sympy import preorder_traversal, symbols >>> x, y, z = symbols('x y z')
除非给出key,否则将按遇到的顺序返回节点;只要传递key=True就可以保证遍历是唯一的。
>>> list(preorder_traversal((x + y)*z, keys=None)) [z*(x + y), z, x + y, y, x] >>> list(preorder_traversal((x + y)*z, keys=True)) [z*(x + y), z, x + y, x, y]
- sympy.core.traversal.use(expr, func, level=0, args=(), kwargs={})[源代码]#
使用
func
改造expr
在给定的水平上。实例
>>> from sympy import use, expand >>> from sympy.abc import x, y
>>> f = (x + y)**2*x + 1
>>> use(f, expand, level=2) x*(x**2 + 2*x*y + y**2) + 1 >>> expand(f) x**3 + 2*x**2*y + x*y**2 + 1
- sympy.core.traversal.walk(e, *target)[源代码]#
Iterate through the args that are the given types (target) and return a list of the args that were traversed; arguments that are not of the specified types are not traversed.
实例
>>> from sympy.core.traversal import walk >>> from sympy import Min, Max >>> from sympy.abc import x, y, z >>> list(walk(Min(x, Max(y, Min(1, z))), Min)) [Min(x, Max(y, Min(1, z)))] >>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max)) [Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)]
参见