I am using SymPy 1.0 and Python 2.7. I want to calculate the sum of the first 100 integers:
This code is working successfully
import sympy as sy
from sympy.tensor import IndexedBase, Idx
import numpy as np
x = sy.IndexedBase('x')
i = sy.symbols('i', cls=Idx)
s = sy.Sum(x[i], (i, 0, 100))
s_lambda = sy.lambdify(sy.DeferredVector('x'), s, 'numpy')
s_lambda(np.arange(101))
And gives 5050, as expected. But when I try to do the same with Productinstead Sum:
import sympy as sy
from sympy.tensor import IndexedBase, Idx
import numpy as np
x = sy.IndexedBase('x')
i = sy.symbols('i', cls=Idx)
s = sy.Product(x[i], (i, 0, 100))
s_lambda = sy.lambdify(sy.DeferredVector('x'), s, 'numpy')
s_lambda(np.arange(101))
I got NameError: global name 'Product' is not defined
What am I doing wrong? Is there a workaround to get what I want?
Edit 1: What if I don't know the limit in advance Product. Let me say something like
import sympy as sy
from sympy.tensor import IndexedBase, Idx
import numpy as np
x = sy.IndexedBase('x')
i = sy.symbols('i', cls=Idx)
n = sy.symbols('n', integer=True, positive=True)
s = sy.Product(x[i], (i, 0, n))
s_lambda = sy.lambdify((sy.DeferredVector('x'), n) s.doit(), 'numpy')
s_lambda(np.arange(101), 5)
Edit 2: I am trying to find a workaround. Because of this, an error occurs NameError: global name 'Product' is not defined:
lambdastr((sy.DeferredVector('x'), n), p)
This gives:
lambda x,n: (Product(x[i], (i, 0, n)))
While for Sumwe got a working lambda function:
lambda x,n: ((builtins.sum(x[i] for i in range(0, n+1))))
At this point, the problem revolves around the definition of a function Product. According to the manual, I can enter through dictmy function definition
def my_prod(a, b):
pass
my_fun = {"Product" : my_prod}
f = sy.lambdify((sy.DeferredVector('x'), n), p, modules=['numpy', my_fun])
f([1,2,3,4,5], 2)
, list indices must be integers, not Symbol , lambdified f. , i, , . , integer, my_prod, Sum.