Summation over a sympy Array

断了今生、忘了曾经 提交于 2021-02-10 08:44:05

问题


I want to sum over a sympy Array (called arr) using the two indices i and j. Summing over arr[i] results in an integer as In [4] below shows. However, summing over arr[j] does not give a number as result (see In [5] below). Why is that?

In [1]: from sympy import *

In [2]: i, j = symbols("i j", integer=True)

In [3]: arr = Array([1, 2])

In [4]: summation(
   ...:     arr[i],
   ...:     (j, 0, i), (i, 0, len(arr)-1)
   ...: )
Out[4]: 5

In [5]: summation(
   ...:     arr[j],
   ...:     (j, 0, i), (i, 0, len(arr)-1)
   ...: )
Out[5]: Sum([1, 2][j], (j, 0, i), (i, 0, 1))

回答1:


SymPy will evaluate summation if either

  1. Both the summand and the limits for summation are explicit; or
  2. It can find a symbolic expression for the sum, based on the formula for the summand.

Nested summation is performed from left to right. In the first version,

summation(arr[i], (j, 0, i))

falls under item 2: since the summand does not depend on the index j, the sum evaluates to symbolically to (i + 1)*arr[i]. Then the outer sum becomes

summation((i + 1)*arr[i], (i, 0, len(arr)-1))

and this falls under item 1: both the summand and the limits are explicit.

But in the second version,

summation(arr[j], (j, 0, i))

fits neither 1 nor 2. The summand depends on j, we don't have any formula for it (it's just some numbers [1, 2]), and the upper limit of summation is symbolic. There is nothing for SymPy to do with such a sum, so it remains undone. Subsequently, the outer sum is not going anywhere since the inner was not done.

Workaround

In the second case, replacing the outer sum with Python sum makes the inner one explicit, so it gets evaluated.

>>> sum([summation(arr[j], (j, 0, i)) for i in range(len(arr))])
4

Of course, this does not really use symbolic capabilities of SymPy: the inner sum could be Python's sum as well.



来源:https://stackoverflow.com/questions/51723550/summation-over-a-sympy-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!