SymPy:交换两个变量 [英] SymPy: Swap two variables

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

问题描述

像这样的表达式

import sympy

a = sympy.Symbol('a')
b = sympy.Symbol('b')

x = a + 2*b

我想交换 ab 来检索 b + 2*a.我试过了

I'd like to swap a and b to retrieve b + 2*a. I tried

y = x.subs([(a, b), (b, a)])
y = x.subs({a: b, b: a})

但两者都不起作用;结果在两种情况下都是 3*a 作为 b,由于某种原因,首先被替换.

but neither works; the result is 3*a in both cases as b, for some reason, gets replaced first.

有什么提示吗?

推荐答案

有一个 simultaneous 参数可以传递给替换,这将确保所有替换同时发生并且不会干扰就像他们现在所做的那样.

There is a simultaneous argument you can pass to the substitution, which will ensure that all substitutions happen simultaneously and don't interfere with one another as they are doing now.

y = x.subs({a:b, b:a}, simultaneous=True)

输出:

2*a + b

<小时>

来自 subs 的文档:

如果关键字 simultaneousTrue,则在完成所有替换之前不会评估子表达式.

If the keyword simultaneous is True, the subexpressions will not be evaluated until all the substitutions have been made.

这篇关于SymPy:交换两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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