How can I use sympy sum over elements of a list in python?
Question:
I am just trying to use a sympy sum over a list of elements, for example:
x = [1,2,3,4,5]
expression = sympy.sum(x[i], (i,0,2)) * sympy.sum(x[j], (j,1,3))
and I just want it to numerically evaluate this. I always get index out of range, although it’s clearly not out of range. Any ideas?
Answers:
You’d have to build a symbolic expression representing your summation:
from sympy import *
x = IndexedBase("x")
i, j = symbols("i, j")
expr = Sum(x[i], (i,0,2)) * Sum(x[j], (j,1,3))
Then, you can substitute x
with your "array":
xv = [1,2,3,4,5]
expr.subs(x, Array(xv)).doit()
Note that I converted xv
into a SymPy’s Array, otherwise the procedure won’t work.
EDIT: added clarification
If your list is composed of hundres, or thousands or millions of entries, then it’s better to convert the symbolic expression to a lambda function in order to improve evaluation speed:
f = lambdify(x, expr)
import inspect
print(inspect.getsource(f))
# def _lambdifygenerated(Dummy_26):
# return (builtins.sum(Dummy_26[i] for i in range(0, 2+1)))*(builtins.sum(Dummy_26[j] for j in range(1, 3+1)))
f(xv)
# 54
I am just trying to use a sympy sum over a list of elements, for example:
x = [1,2,3,4,5]
expression = sympy.sum(x[i], (i,0,2)) * sympy.sum(x[j], (j,1,3))
and I just want it to numerically evaluate this. I always get index out of range, although it’s clearly not out of range. Any ideas?
You’d have to build a symbolic expression representing your summation:
from sympy import *
x = IndexedBase("x")
i, j = symbols("i, j")
expr = Sum(x[i], (i,0,2)) * Sum(x[j], (j,1,3))
Then, you can substitute x
with your "array":
xv = [1,2,3,4,5]
expr.subs(x, Array(xv)).doit()
Note that I converted xv
into a SymPy’s Array, otherwise the procedure won’t work.
EDIT: added clarification
If your list is composed of hundres, or thousands or millions of entries, then it’s better to convert the symbolic expression to a lambda function in order to improve evaluation speed:
f = lambdify(x, expr)
import inspect
print(inspect.getsource(f))
# def _lambdifygenerated(Dummy_26):
# return (builtins.sum(Dummy_26[i] for i in range(0, 2+1)))*(builtins.sum(Dummy_26[j] for j in range(1, 3+1)))
f(xv)
# 54