使所有符号在 sympy 表达式中可交换 [英] Make all symbols commutative in a sympy expression

查看:28
本文介绍了使所有符号在 sympy 表达式中可交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你在一个 sympy 表达式中有许多非交换符号,比如

a, c = sympy.symbols('a c', 可交换=假)b = sympy.Symbol('b')expr = a * c + b * c

使表达式中的所有符号都可交换的首选方法是什么,例如,sympy.simplify(allcommutative(expr)) = c * (a + b)?>

this answer 中指出,如果不替换符号,但也许有一种简单的方法可以像这样在块中更改表达式的所有符号?

解决方案

如果你想让 Eq(expr, c * (a + b)) 计算为 True,你需要替换通勤的其他符号的符号.例如:

replacements = {s: sympy.Dummy(s.name) for s in expr.free_symbols}sympy.Eq(expr, c * (a + b)).xreplace(replacements).simplify()

这将返回 True.

Say you have a number of non commutative symbols within a sympy expression, something like

a, c = sympy.symbols('a c', commutative=False)
b = sympy.Symbol('b')
expr = a * c + b * c

What is the preferred way to make all symbols in the expression commutative, so that, for example, sympy.simplify(allcommutative(expr)) = c * (a + b)?

In this answer it is stated that there is no way to change the commutativity of a symbol after creation without replacing a symbol, but maybe there is an easy way to change in blocks all symbols of an expression like this?

解决方案

If you want Eq(expr, c * (a + b)) to evaluate to True, you'll need to replace symbols by other symbols that commute. For example:

replacements = {s: sympy.Dummy(s.name) for s in expr.free_symbols}
sympy.Eq(expr, c * (a + b)).xreplace(replacements).simplify()

This returns True.

这篇关于使所有符号在 sympy 表达式中可交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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