i具有包含关系运算符,符号和常数的表达式。我想重新排列表达式,以便(尽可能)所有恒定项都在关系操作员的一侧,而其余项则位于另一侧。例如,我想重新排列:
x -5> y -z
to:
x -y z> 5
是否有一种现有的Sympy方法可以执行此操作?如果没有,我应该从哪里开始扩展sympy?
有些令人惊讶的是,我找不到一种"开箱即用"的方法。您可以在此问题中使用该方法将任何一个变量成为不平等的左侧(LHS)的唯一主题,但我似乎无法使恒定的术语成为主题。
所以,我写了自己的版本并在下面复制它。我已经在给出的示例和其他几个示例上对其进行了测试。它试图使右侧(RHS)由基于可选参数的零或常数项组成。很可能有一个拐角处失败 - 谨慎使用/修改。
代码:
import sympy
from sympy.core.relational import Relational
mult_by_minus_one_map = {
None: '==',
'==': '==',
'eq': '==',
'!=': '!=',
'<>': '!=',
'ne': '!=',
'>=': '<=',
'ge': '<=',
'<=': '>=',
'le': '>=',
'>': '<',
'gt': '<',
'<': '>',
'lt': '>',
}
def move_inequality_constants(ineq, zero_on_right=False):
l = ineq.lhs
r = ineq.rhs
op = ineq.rel_op
all_on_left = l - r
if zero_on_right:
return Relational(all_on_left, sympy.sympify(0), op)
else:
coeff_dict = all_on_left.as_coefficients_dict()
var_types = coeff_dict.keys()
new_rhs = sympy.sympify(0)
for s in var_types:
if s == 1:
all_on_left = all_on_left - coeff_dict[s]
new_rhs = new_rhs - coeff_dict[s]
if new_rhs < 0:
all_on_left = all_on_left * -1
new_rhs = new_rhs * -1
op = mult_by_minus_one_map[op]
return Relational(all_on_left,new_rhs,op)
# test code to demo function below
from sympy.abc import x,y,z
test_ineqs = [ x - 5 > y - z,
x**2 + x - 5 > y + x**2 - z,
x + 5 > y - z,
x**3 + y**2 >= x + 5*y - z - 15]
for k in test_ineqs:
print('Re-arranging '+ str(k))
kn = move_inequality_constants(k)
print('Gives '+str(kn))
print('Or equivalently ' + str(move_inequality_constants(k, True)))
print('====')
输出:
Re-arranging x - 5 > y - z
Gives x - y + z > 5
Or equivalently x - y + z - 5 > 0
====
Re-arranging x**2 + x - 5 > x**2 + y - z
Gives x - y + z > 5
Or equivalently x - y + z - 5 > 0
====
Re-arranging x + 5 > y - z
Gives -x + y - z < 5
Or equivalently x - y + z + 5 > 0
====
Re-arranging x**3 + y**2 >= x + 5*y - z - 15
Gives -x**3 + x - y**2 + 5*y - z <= 15
Or equivalently x**3 - x + y**2 - 5*y + z + 15 >= 0
从 canonical
方法中省略此方法可能是一个监督。
也许以下适用于您的else
子句
r, l = (ineq.lhs - ineq.rhs).as_coeff_Add()
if r < 0:
l, r = -r, -l
return Relational(l, r, ineq.rel_op).canonical
人们可能会想象,规范也可以消除常见因素,因此2x<4y
将成为x<2*y
。Sympy将对实施此类更改的拉请求开放。