SymPy中的非顺序替换 [英] Non-sequential substitution in SymPy

查看:99
本文介绍了SymPy中的非顺序替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用[SymPy] [1]同时替换表达式中的多个术语.我尝试使用字典作为参数的[subs function] [2],但发现它是按顺序替换的.

I'm trying to use [SymPy][1] to substitute multiple terms in an expression at the same time. I tried the [subs function][2] with a dictionary as parameter, but found out that it substitutes sequentially.

In : a.subs({a:b, b:c})
Out: c

问题是第一次替换导致一个可以被第二次替换替换的术语,但不应(出于我的原因).

The problem is the first substitution resulted in a term that can be substituted by the second substitution, but it should not (for my cause).

关于如何在不相互干扰的情况下同时执行替换的任何想法?

Any idea on how to perform the substitutions simultaneously, without them interfering with each other?

这是一个真实的例子

This is a real example

In [1]: I_x, I_y, I_z = Symbol("I_x"), Symbol("I_y"), Symbol("I_z")

In [2]: S_x, S_y, S_z = Symbol("S_x"), Symbol("S_y"), Symbol("S_z")

In [3]: J_is = Symbol("J_IS")

In [4]: t = Symbol("t")

In [5]: substitutions = (
(2 * I_x * S_z, 2 * I_x * S_z * cos(2 * pi * J_is * t) + I_y * sin(2 * pi * J_is * t)),
(I_x,  I_x * cos(2 * pi * J_is * t) + 2 * I_x * S_z * sin(2 * pi * J_is * t)),
(I_y,  I_y * cos(2 * pi * J_is * t) - 2 * I_x * S_z * sin(2 * pi * J_is * t))
)

In [6]: (2 * I_x * S_z).subs(substitutions)
Out[7]: (I_y*cos(2*pi*J_IS*t) - 2*I_x*S_z*sin(2*pi*J_IS*t))*sin(2*pi*J_IS*t) + 2*S_z*(I_x*cos(2*pi*J_IS*t) + 2*I_x*S_z*sin(2*pi*J_IS*t))*cos(2*pi*J_IS*t)

仅应进行适当的替换,在这种情况下,仅第一个替换.因此,预期的输出应为以下内容:

Only the appropriate substitution should happen, in this case only the first one. So the expected output should be the following:

In [6]: (2 * I_x * S_z).subs(substitutions)
Out[7]: I_y*sin(2*pi*J_IS*t) + 2*I_x*S_z*cos(2*pi*J_IS*t)

推荐答案

sympy的当前版本同时提供关键字.不再需要前面的答案中的复杂操作:

The current version of sympy provides the keyword simultaneous. The complicated operations in the previous answers are no more necessary:

In [1]: (x*sin(y)).subs([(x,y),(y,x)],simultaneous=True)
Out[1]: y⋅sin(x)

这篇关于SymPy中的非顺序替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆