问题描述
我想在sympy中禁用自动简化,例如求解方程式x*y-x
我想获得x/x
而不是1
i want to disable automatic simplification in sympy, for example solving the equation x*y-x
i want to get x/x
instead of 1
import sympy
from sympy.abc import x,y,z
expr = x*y-x
sympy.solve(expr,y)
=> 1 # i want unsimplified x/x instead of 1
从sympy手册中,我为此找到了UnevaluatedExpr,但是对于给定的示例,它返回了空列表
From the sympy manual, i found UnevaluatedExpr for this purpose, but it returns empty list for the example given
from sympy import UnevaluatedExpr
expr1 = UnevaluatedExpr(x)*UnevaluatedExpr(y)-UnevaluatedExpr(x)
sympy.solve(expr1,y)
=> []
我的问题是
- 给出的示例出了什么问题?
- 如何保持表达式不被评估/不被简化?
推荐答案
一种禁用自动评估的更简单方法是使用上下文管理器评估.例如
A simpler way to disable automatic evaluation is to use context manager evaluate. For example,
from sympy.core.evaluate import evaluate
from sympy.abc import x,y,z
with evaluate(False):
print(x/x)
这将打印1/x * x
而不是1
但是,正如上下文管理器的文档字符串所述,大多数SymPy代码都希望自动评估.禁用自动评估后,除简单计算之外的所有操作都有可能崩溃.即使对于简单的方程式,对于solve
也会发生这种情况.您可以禁用评估(使用evaluate(False)
或使用UnevaluatedExpr
),但是可能无法获得解决方案.
However, as the docstring of the context manager says, most of SymPy code expects automatic evaluation. Anything beyond straightforward calculations is likely to break down when automatic evaluation is disabled. This happens for solve
, even for simple equations. You can disable evaluation (either with evaluate(False)
or by using UnevaluatedExpr
), but you probably will not get a solution.
特定方程式的部分解决方法是使用Dummy("x")
而不是UnevaluateExpr(x)
.即使虚拟符号具有不同的名称,它们也会被视为不同的,因此它们不会被抵消.
A partial workaround for the specific equation is to use Dummy("x")
instead of UnevaluateExpr(x)
. The dummy symbols are treated as distinct even if they have distinct names, so they will not cancel out.
>>> expr = Dummy("x")*y - Dummy("x")
>>> solve(expr, y)
[_x/_x]
这篇关于禁用sympy中的自动简化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!