Sympy bug?即使使用“evaluate=False”,也会自动处理公式

2024-09-27 19:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下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的方法是有效的,但是没有这些术语的原始答案是无效的。唉,就我的具体情况而言,甚至使用sp.UnevaluatedExpr都不管用。)


Tags: 答案代码fromimportadd顺序sp术语
1条回答
网友
1楼 · 发布于 2024-09-27 19:23:30

这不是虫子

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

这里是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)

至于现在,似乎不存在非交换加法

相关问题 更多 >

    热门问题