问题
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
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)
=> []
my question is
- what is wrong with the example given?
- how can i keep expressions not-evaluated/not-simplified?
回答1:
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)
This prints 1/x * x
instead of 1
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.
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]
来源:https://stackoverflow.com/questions/48839611/disabling-automatic-simplification-in-sympy