SymPy: evaluate sum of sum

Viewed 1520

I need to evaluate the expression using SymPy:

enter image description here

I expect to obtain something like

enter image description here

The problem is the code

import sympy as sy

n,i,j = sy.symbols('n i j', integer=True)
a = sy.Function('a')

print sy.Sum(sy.Sum(a(j), (j,1,i)), (i, 1, n)).doit()

prints just the double sum

Sum(a(j), (j, 1, i), (i, 1, n))
1 Answers

The answer you are trying to obtain is not correct. The inner summation variable is j, which is used in a(j), so the inner sum can't be computed further, and, i is the upper limit of the inner sum, so the outer sum can't be computed further either.

The summation that gives the answer you want is Sum(a(i), (j,i,n), (i, 1, n)), i.e.,

  n     n
 ___   ___
 ╲     ╲
  ╲     ╲   a(i)
  ╱     ╱
 ╱     ╱
 ‾‾‾   ‾‾‾
i = 1 j = i

which SymPy computes if you call doit(). By the way, note that you can create a double sum with a single call to Sum, by passing the outer limits as further arguments.

Related