gpt4 book ai didi

python - 同情错误?即使使用 `evaluate=False` 方程也会自动处理

转载 作者:行者123 更新时间:2023-12-01 08:18:04 25 4
gpt4 key购买 nike

考虑以下 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 都不起作用。)

最佳答案

这不是一个错误...

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

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

就目前而言,似乎不存在非交换加法。

关于python - 同情错误?即使使用 `evaluate=False` 方程也会自动处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54866180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com