通过引入新的虚拟指数来扩展 sympy 中的总和乘积

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

我想使用 sympy 来简化一些包含和乘积的表达式,这将需要扩展乘积并取消等式。

i, j, k, l = symbols('i, j, k, l', cls=Dummy)
A = IndexedBase('A')
N = symbols('N', integer=True, positive=True)
s = Sum(A[i]*A[j], (i, 1, N), (j, 1, N))
expr = s**2

运行

expr.doit()
expr.expand()
expr.simplify()
将使表达式保持不变。

表达式显示为

Expr1

如何扩展乘积并引入虚拟索引以将表达式变为以下形式?

Expr2

python math sympy symbolic-math
2个回答
0
投票

有趣。我不知道您是否已经解决了这个问题,但执行此操作的一种方法如下。首先,像您一样导入所需的组件:

from sympy import symbols, IndexedBase, Sum, Dummy, simplify

i, j, k, l = symbols('i j k l', cls=Dummy)
A = IndexedBase('A')
N = symbols('N', integer=True, positive=True)

现在,

s = Sum(A[i]*A[j], (i, 1, N), (j, 1, N))
expr = s**2

会给你以下表达式

Sum(A[_i]*A[_j], (_i, 1, N), (_j, 1, N))**2

以下是简化方法:

expanded_expr = Sum(A[i]*A[j]*A[k]*A[l], (i, 1, N), (j, 1, N), (k, 1, N), (l, 1, N))

simplified_expr = simplify(expanded_expr)

这会给你

Sum(A[_i]*A[_j]*A[_k]*A[_l], (_i, 1, N), (_j, 1, N), (_k, 1, N), (_l, 1, N))

enter image description here


0
投票

我有一个类似的问题,我用下面的代码解决了。请注意,我的代码引入了虚拟索引 i' 和 j',而不是原始索引 i 和 j 的 k 和 l,但这可以通过修改分配给

new_ranges
变量的符号来调整。

# Replace sum over old_indices squared by product of sums over old_indices times sum over new_indices

from sympy import *

def matcher(e):
    '''Return True if {e} is the square of a sum.'''
    return isinstance(e, Pow) and isinstance(e.base, Sum) and e.exp == 2

    
def replacer(e):
    '''
    Expand sum over old_indices squared to product of sum over old_indices times
    sum over new_indices.
    '''
    old_ranges = e.base.args[1:]
    new_ranges = [(Symbol(f"{old_range[0]}'"), *old_range[1:]) for old_range in old_ranges]
    
    old_indices = [old_range[0] for old_range in old_ranges]
    new_indices = [new_range[0] for new_range in new_ranges]
    
    new_var = e.base.args[0].xreplace(dict(zip(old_indices, new_indices)))
    
    return Sum(e.base.args[0] * new_var, *list(old_ranges) + list(new_ranges))


A = IndexedBase('A')
N = symbols('N', integer=True, positive=True)
s = Sum(A[i]*A[j], (i, 1, N), (j, 1, N))
expr = s**2

expr.replace(matcher, replacer)

输出:

output

灵感:https://stackoverflow.com/a/64944974/7740977

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.