避免在Python模块Sympy中对args进行排序 [英] Avoid sorting args in Python module Sympy

查看:109
本文介绍了避免在Python模块Sympy中对args进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为sympy开发差分运算符可以以矩阵形式放置. 在这种情况下,创建Mul对象时args列表的顺序对于确保仅在需要时进行区分非常重要.

I am currently developing a differential operator for sympy that can be placed in matricial form. In this case the order of the args list when creating a Mul object is very important to guarantee that the differentiation is performed where it is required only.

问题在于,完成以下操作后:

The issue is that, when the following is done:

input = (t,z,x)
Mul(*input).args

它返回(t, x, z),因为args中发生了一些重新排列.如何避免args进行排序?

It returns (t, x, z) because some rearrangement in args took place. How to avoid args to be sorted?

推荐答案

为什么arg排序对它正确才重要?

Why is the arg ordering important for it to be correct?

防止这种情况的唯一方法是将符号设置为不可交换的(x = Symbol('x', commutative=False)). SymPy对象通过比较args进行比较,因此,要使x*y*z == y*x*z起作用,必须对args进行规范排序.已经进行了一些尝试,使其无需显式排序即可工作(主要是出于性能方面的考虑),但是请注意,即使我们这样做,也无法保证arg顺序,尤其是对表达式执行任何类型的操作时.函数在SymPy中重建表达式是非常普遍的,通常会使用与原始表达式不相关的其他顺序.

The only way to prevent this is to set your symbols to be non-commutative (x = Symbol('x', commutative=False)). SymPy objects compare by comparing the args, so for x*y*z == y*x*z to work, the args have to be sorted canonically. There have been some attempts to get this working without explicit sorting (mainly for performance reasons), but note that even if we did that, there would be no guarantee at all about the arg order, especially if you perform any kind of operation on the expression. It is very common for functions to rebuild expressions in SymPy, which would in general use some other unrelated order from the original.

这篇关于避免在Python模块Sympy中对args进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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