Sympy 简明教程
SymPy - sympify() function
sympify() 函数用于转换任何任意表达式,这样它就可以用作 SymPy 表达式。整数对象等常规 Python 对象在 SymPy 中得到转换。整数等字符串也会转换为 SymPy 表达式。
The sympify() function is used to convert any arbitrary expression such that it can be used as a SymPy expression. Normal Python objects such as integer objects are converted in SymPy. Integer, etc.., strings are also converted to SymPy expressions.
>>> expr="x**2+3*x+2"
>>> expr1=sympify(expr)
>>> expr1
>>> expr1.subs(x,2)
上面的代码段给出了以下输出:
The above code snippet gives the following output −
12
12
任何 Python 对象都可以转换为 SymPy 对象。然而,由于转换在内部使用 eval() 函数,因此不应使用未经清理的表达式,否则会引发 SympifyError。
Any Python object can be converted in SymPy object. However, since the conversion internally uses eval() function, unsanitized expression should not be used, else SympifyError is raised.
>>> sympify("x***2")
---------------------------------------------------------------------------
SympifyError:表达式“无法解析’x***2'”的 Sympify 失败,因为引发了异常。
SympifyError: Sympify of expression 'could not parse 'x***2'' failed, because of exception being raised.
sympify() 函数采用如下参数:* strict:默认值为 False。如果设置为 True,则仅转换已为其定义显式转换的类型。否则,会引发 SympifyError。* evaluate:如果设置为 False,算术和运算符将转换为其 SymPy 等效项,而不会求值表达式。
The sympify() function takes following arguments: * strict: default is False. If set to True, only the types for which an explicit conversion has been defined are converted. Otherwise, SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be converted into their SymPy equivalents without evaluating expression.
>>> sympify("10/5+4/2")
上面的代码段给出了以下输出:
The above code snippet gives the following output −
4
4
>>> sympify("10/5+4/2", evaluate=False)
上面的代码段给出了以下输出:
The above code snippet gives the following output −
$\frac{10}{5}+\frac{4}{2}$
$\frac{10}{5}+\frac{4}{2}$