zkytony
zkytony

Reputation: 1498

SymPy: Expression for Summation of Symbols in a List

I'm writing a program that evaluates the power series sum_{m=0}{oo} a[m]x^m, where a[m] is recursively defined: a[m]=f(a[m-1]). I am generating symbols as follows:

a = list(sympy.symbols(' '.join([('a%d' % i) for i in range(10)])))
for i in range(1, LIMIT):
   a[i] = f_recur(a[i-1], i-1)

This lets me refer to the symbols a0,a1,...,a9 using a[0],a[1],...,a[9], and a[m] is a function of a[m-1] given by f_recur.

Now, I hope code up the summation as follows:

m, x, y = sympy.symbols('m x y')
y = sympy.Sum(a[m]*x**m, (m, 0, 10))

But, m is not an integer so a[m] throws an Exception.

In this situation, where symbols are stored in a list, how would you code the summation? Thanks for any help!

Upvotes: 2

Views: 2761

Answers (3)

smichr
smichr

Reputation: 19037

Use IndexedBase instead of Symbol:

>>> a = IndexedBase('a')
>>> Sum(x**m*a[m],(m,1,3))
Sum(a[m]*x**m, (m, 1, 3))
>>> _.doit()
a[1]*x + a[2]*x**2 + a[3]*x**3

Upvotes: 0

user6655984
user6655984

Reputation:

SymPy's Sum is designed as a sum with a symbolic index. You want a sum with a concrete index running through 0, ... 9. This could be Python's sum

y = sum([a[m]*x**m for m in range(10)])

or, which is preferable from the performance point of view (relevant issue)

y = sympy.Add(*[a[m]*x**m for m in range(10)])

In either case, m is not a symbol but an integer.

Upvotes: 6

zkytony
zkytony

Reputation: 1498

I have a work-around that does not use sympy.Sum:

x = sympy.symbols('x')
y = a[0]*x**0
for i in range(1, LIMIT):
    y += a[i]*x**i

This does the job, but sympy.Sum is not used.

Upvotes: 1

Related Questions