Jason R
Jason R

Reputation: 11716

Can SymPy understand variables that are indexed by a summation index?

I have an equation that is of the form (in LaTeX syntax):

\sum_{k=0}^{K-1} a_k = 0

a_k is "a subscript k", one of a list of variables that I'm setting up a system of linear equations in. I would like to be able to express this equation to SymPy in as compact of a way as possible. It seems like I would want to use its Sum() function to express the summation, but I'm not sure how to tell it that on term k in the sum, a_k refers to the k-th symbol.

Is this possible, for instance if I set up a list of symbols like this?

a = [sympy.symbols('a' + str(i)) for i in xrange(K)]

Upvotes: 1

Views: 1177

Answers (1)

Francesco Bonazzi
Francesco Bonazzi

Reputation: 1957

Do you mean something like this?

In [1]: a = IndexedBase("a")

In [2]: Sum(a[k], (k, 0, K-1))
Out[2]: 
K - 1     
 ___      
 ╲        
  ╲   a[k]
  ╱       
 ╱        
 ‾‾‾      
k = 0

IndexedBase are supposed to create a variable that needs to specify an index each time it is used. If the indices are different, the variables should be considered different (e.g. a[k] vs a[j]).

In case your summation has known limits (i.e. non literal), you may expand it:

In [3]: Sum(a[k], (k, 0, 10))
Out[3]: 
  10      
 ___      
 ╲        
  ╲   a[k]
  ╱       
 ╱        
 ‾‾‾      
k = 0     

In [4]: Sum(a[k], (k, 0, 10)).doit()
Out[4]: a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6] + a[7] + a[8] + a[9] + a[10]

Unfortunately, not all of SymPy's algorithms support IndexedBase objects completely. Replacement with a Symbol is advised in such cases.

Upvotes: 6

Related Questions