'SymPy: How to implement summation of indexed coefficients times indexed functons?

Update:

I want to run a generate_function(3) for example to have an output of:

c_0 * F(0) + c_1 * F(1) + c_2 * F(2) + c_3 * F(3)

where c_i is just a symbol, while F(i) is a function or an object that I can use later for the rest of code.


I simply want to use SymPy to implement the summation:

summation (from i = 0 to n) c_i * f(i)

where c_i is indexed constant (symbol) and f is a function with argument of i.

I tried many times and failed.

def generate(n):
    coeff = sym.symbols('c0:{}'.format(n))
    def f(i):
        return i
    return sym.Sum(coeff(i) * f(i),(i,0,n))

I got: 'tuple' object is not callable

Thanks for help



Solution 1:[1]

It's not completely clear what you want but maybe this is it:

In [31]: C = IndexedBase('C')

In [32]: f = Function('f')

In [33]: i, n = symbols('i, n')

In [34]: s = Sum(C[i] * f(i), (i, 0, n))

In [35]: s
Out[35]: 
  n            
 ___           
 ?             
  ?            
  ?   f(i)?C[i]
 ?             
 ???           
i = 0 

Solution 2:[2]

You created a tuple of symbols:

In [8]: coeff = symbols("c0:{}".format(n))

In [9]: coeff
Out[9]: (c0a, c0b, c0c, c0d, c0e, c0f, c0g, c0h, c0i, c0j, c0k, c0l, c0m, c0n)

Treating such a tuple as though it were a function, as in f(i), does not work. That's basic Python! While the indexing is a nice short to making many symbols, the result is no different from doing symbols('x y z')

In [10]: coeff(0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [10], in <module>
----> 1 coeff(0)

TypeError: 'tuple' object is not callable

You can index the tuple

In [11]: coeff[0]
Out[11]: c0a

You could use a list comprehension to make a list of expressions:

In [14]: [coeff[i] * f(i) for i in range(5)]
Out[14]: [0, c0b, 2?c0c, 3?c0d, 4?c0e]

and even apply the base sum function to create a sympy.Add expression:

In [16]: sum([coeff[i] * f(i) for i in range(5)])
Out[16]: c0b + 2?c0c + 3?c0d + 4?c0e

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oscar Benjamin
Solution 2