Issue
I'm new to SymPy and I'm currently trying to learn how to use this tool in conjunction with Jupyter to create adaptive notebooks for my university.
I'm currently facing an issue related to summations. I would like to write an abstract formula similar to 'formula1
' as shown here:
However, I would like to be able to use arrays in place of the variables x_i
and p_i
, which represent elements of an array within the formula. I want to receive the result of the summation of the product of corresponding elements from these two arrays.
So, my question is: Is there any way to create a well-formatted abstract formula for summation and then pass predefined values as an array?
Here's the code I've tried:
import sympy as sp
datx = [-2, 0, 2, 4]
datp = [0.729, 0.243, 0.027, 0.001]
x_i, p_i, i, n = sp.symbols('x_i p_i i n')
expr = sp.Sum(x_i * p_i, (i, 0, n)) # what I want my formula to look like
expr1 = sp.Sum(datx[i] * datp[i], (i, 0, n)) # working expression, but not the desired format
I hope this provides more clarity. As I mentioned before, I want an abstract-looking formula, like 'formula1'
, and I've tried to create it as 'expr'. However, I'm having trouble using arrays in place of x_1
and p_i
. So, I created 'expr1,' which works fine and returns the correct results, but it doesn't have the desired format in Jupyter:
Solution
IndexedBase
can be used for the indexed summation variables:
x, p = symbols('x p', cls=IndexedBase); var('i n')
>>> expr = Sum(x[i] * p[i], (i, 0, n)); expr
Sum(p[i]*x[i], (i, 0, n))
>>> Subs(expr,(n,p,x),(3,(1,2,3,4),(3,4,5,6))).doit()
50
>>> sum(i*j for i,j in zip(range(1,5),range(3,7)))
50
see also here
Answered By - smichr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.