简体   繁体   中英

disabling automatic simplification in sympy

i want to disable automatic simplification in sympy, for example solving the equation x*yx 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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM