I try to create a sympy expression with a Sum with an indexed variable as previous explain here However, I can not do lambdify of this expression and give an array to get the sum calculated. Is this impossible?
Asked
Active
Viewed 1.9k times
2 Answers
4
Perhaps like this?
s = Sum(Indexed('x',i),(i,1,3))
f = lambda x: Subs(s.doit(), [s.function.subs(s.variables[0], j)
for j in range(s.limits[0][1], s.limits[0][2] + 1)], x).doit()
>>> f((30,10,2))
42

smichr
- 16,948
- 2
- 27
- 34
-
Thanks!! Although your solution works perfectly fine, for completion sake, what I was looking for was not exactly that. In your example you limit the sum from 1 to 3, while I want to have from 0 to n (basically for an array with variable size). I think I know now how to do it but I don´t know how to correctly add code to a comment! – Diogo Santos Oct 17 '14 at 13:32
-
Would be nice to add some explanation since it's not straightforward (s.limits is not mentioned in Sum doc). I've just started using sympy; it seems to me that the [s.function.subs(s.variables[0], j) ... for j in range(s.limits[0][1], s.limits[0][2] + 1)] replace Indexed elements with their equivalent integer and only then substitute. this step seems mandatory. – mattator Apr 28 '16 at 13:58
-
I'd upvote another post with the same solution but where the code can be copy-pasted more easily. – mins Nov 07 '22 at 09:49
-
code is updated – smichr Nov 07 '22 at 16:05
4
You can use lambdify. Just make sure the limits of the sum match the iterables of a numpy array.
from sympy import Sum, symbols, Indexed, lambdify
import numpy as np
x, i = symbols("x i")
s = Sum(Indexed('x',i),(i,0,3))
f = lambdify(x, s)
b = np.array([1, 2, 3, 4])
f(b)

Peterhack
- 941
- 4
- 15
- 34