定义点(a,b)函数+属性并简化/扩展

问题描述 投票:0回答:1

我想定义一个函数+规则,让sympy使用规则来简化:

a,b,c = symbols("a b c")
dot = function("dot")
rule1 = Eq( dot(a+b,c) , dot(a,c)+dot(b,c))
rule2 = Eq( dot(a,b) , dot(b,a) )

现在,将上述内容用于

expand
simplify
表达式。

如何做到这一点?有没有 sympy 的替代品可以做到这一点?

python sympy symbolic-math
1个回答
0
投票
from sympy import *
from sympy.abc import x, y

def dot(a,b):
    A, B = ordered((a, b))
    if A != a:
        return dot(b, a)
    if b.is_Add and not a.is_Add:
        a, b = b, a
    if a.is_Add:
        a0, a1 = list(ordered(a.as_two_terms()))
        return dot(a0, b) + dot(a1, b)
    return Function('dot')(a, b)

例如:

>>> dot(y,x)
dot(x, y)
>>> dot(x+1,y)
dot(1, y) + dot(x, y)
>>> dot(x+1,y+2)
dot(1, 2) + dot(1, y) + dot(2, x) + dot(x, y)

但实际上,您所做的只是返回项的规范有序笛卡尔积:

def dot2(a,b):
    from sympy.utilities.iterables import cartes
    pairs = cartes(Add.make_args(a), Add.make_args(b))
    return sum(Function('dot')(*ordered(p)) for p in pairs)
© www.soinside.com 2019 - 2024. All rights reserved.