简体   繁体   中英

How to do double sum in sympy?

I'm trying to do the double sum of the following function:

from sympy import Sum, sin, pi
from sympy.abc import i, j

f = i**2*sin(i*(j+1)*pi/4)

where the inner summation sums from i = 1 to i = j and the outer summation sums from j = 1 to j = 5

that way separately

sum1 = Sum(f, (i, 1, j))
sum2 = Sum(sum1, (j, 1, 5)).doit()

or on the same line

doublesum = Sum(f, (i, 1, j), (j, 1, 5)).doit()

but these things give to me:

Sum(i**2*sin(pi*i*(j + 1)/4), (i, 1, j), (j, 1, 5))

instead of giving to me a numeric object as it should be.

What's wrong?

As of SymPy version 1.9, double Sums with cross-referencing indices are something that SymPy is not able to deal with. However, with your example we can use ordinary Python syntax to achieve the same result:

f = i**2*sin(i*(j+1)*pi/4)
s1 = Sum(f, (i, 1, j))

tot = 0
for jn in range(0, 6):
    tot += s1.subs(j, jn)
print(tot)

# Sum(i**2*sin(3*pi*i/2), (i, 1, 5)) + Sum(i**2*sin(3*pi*i/4), (i, 1, 2)) + Sum(i**2*sin(5*pi*i/4), (i, 1, 4)) + Sum(i**2*sin(pi*i), (i, 1, 3)) + Sum(i**2*sin(pi*i/4), (i, 1, 0)) + Sum(i**2*sin(pi*i/2), (i, 1, 1))

This is a long expression, containing multiple Sum objects. To get a purely symbolic result, we can apply the doit() method:

tot.doit()
# -16 - 9*sqrt(2)/2

To get a floating point result, we can call the evalf() method:

r = tot.evalf()
print(r, type(r))
# -22.3639610306789 <class 'sympy.core.numbers.Float'>

Note that the type of this number is Float , still a SymPy object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM