同情错误?即使使用“evaluate=False”,方程式也会自动处理

Sympy bug? Even with `evaluate=False` equations are automatically processed

考虑以下 sympy 代码:

from sympy import Add
from sympy.abc import x

t1 = 2+2*x
t2 = x
myeq = sp.UnevaluatedExpr(Add(sp.UnevaluatedExpr(t1), sp.UnevaluatedExpr(t2), evaluate=False))

# BUG! Will print: x + 2*x + 2
# Yet it should print: 2+2*x+x
print(myeq)

此代码片段改编自 this 答案。那里的术语更简单,所以 Add 保留了顺序。但是在这种情况下,我怎样才能让 Add 保持顺序呢?

(备注:如果我们将条款更改为 t1=xt2=x**2 我使用 sp.UnevaluatedExpr 的方法有效,但没有这些条款的原始答案没有。 las,对于我的具体情况,甚至使用 sp.UnevaluatedExpr 都行不通。)

这不是错误...

...但更多的是缺失的功能。所有这些都被记录在案。

SymPy 的意思是 unevaluated

By unevaluated it is meant that the value inside of it will not interact with the expressions outside of it to give simplified outputs.

在您的示例中,术语 2*xx 没有像预期的那样被简化。

输入顺序

您看到的是 SymPy 没有保留您输入条款的顺序。这是 documented under the expression tree section.

The arguments of the commutative operations Add and Mul are stored in an arbitrary (but consistent!) order, which is independent of the order inputted.

这应该不是问题,因为 AddMul 是可交换的。

虽然,如果由于某种原因你想保留输入的顺序,因为乘法的非交换性,你可以这样做。

In SymPy, you can create noncommutative Symbols using Symbol('A', commutative=False), and the order of multiplication for noncommutative Symbols is kept the same as the input)

至于现在,似乎没有非交换加法。