考虑以下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=x
和t2=x**2
,我使用sp.UnevaluatedExpr
的方法是有效的,但是没有这些术语的原始答案是无效的。唉,就我的具体情况而言,甚至使用sp.UnevaluatedExpr
都不管用。)
这不是虫子
。。。但更多的是一个缺失的功能。所有这些都被记录在案
这里是SymPy所指的unevaluated
在您的示例中,术语
2*x
和x
没有像预期的那样简化输入顺序
你看到的是SymPy没有保持你输入术语的顺序。这是documented under the expression tree section
这应该不是问题,因为
Add
和Mul
是可交换的但是,如果出于某种原因,由于乘法的非交换性,您希望保持输入的顺序,那么您可以这样做
至于现在,似乎不存在非交换加法
相关问题 更多 >
编程相关推荐