Home > Enterprise >  plug np.array into sympy expression
plug np.array into sympy expression

Time:07-22

I need to subs a numpy.array into an indexed symbol of Sympy expression to numerically calculate the sum. (1 2 3 4 5=15). My below code still produce symbolic expression. Please help~

from sympy import *
import numpy as np
i = Symbol("i")
y = Symbol("y")
y_ = np.array([1,2,3,4,5])
h = Sum(Indexed("y","i"),(i,0,4))
h.subs([(y,y_)])

CodePudding user response:

smichr answer is solid, however considering that the numerical values of h_ are going to be converted by SymPy to symbolic numbers, the easiest and fastest way is to do this:

new_h = h.subs(y, Array(y_))
# out: Sum([1, 2, 3, 4, 5][i], (i, 0, 4))
# alternatively:
# new_h = h.subs(y, sympify(y_))
new_h.doit()
# out: 15

Another alternative is to convert your symbolic expression to a numerical function with lambdify. However, this approach works as long as the there is not infinity on the bounds of the summation:

f = lambdify([y], h)
f(y_)
# out: 15

CodePudding user response:

Perhaps something like this will work?

>>> y = IndexedBase("y")
>>> h = Sum(y[i],(i,0,4));h.doit()
y[0]   y[1]   y[2]   y[3]   y[4]
>>> _.subs(dict(zip([y[i] for i in range(len(y_))],y_)))
15
  • Related