Programming 55
Programming 55

Reputation: 19

SymPy - Is there a way to write a summation, that has a variable with an incrementing subscript?

I wanted to write this expression, in code:

x1 + x2 + x3 + x4 + x5

I can currently do this via:

import sympy as sp
x1, x2, x3, x4, x5 = sp.symbols('x1 x2 x3 x4 x5')
x1 + x2 + x3 + x4 + x5

But unfortunately, this doesn't scale very well, incase I wanted to go from x1 to say, x10,000

Any help would be sincerely appreciated.

I tried using SymPy's summation function, like this:

summation(x(i), (i, 0, n))

But unfortunately got a TypeError, stating:

'Symbol' object is not callable

Upvotes: 0

Views: 375

Answers (1)

smichr
smichr

Reputation: 19057

You can use a generic IndexedBase symbol with a summation:

>>> i = Symbol('i'); x = IndexedBase('x')
>>> Sum(x[i],(i,1,10))
Sum(x[i], (i, 1, 10))
>>> _.doit()
x[10] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] + x[7] + x[8] + x[9]

Upvotes: 1

Related Questions