简体   繁体   English

如何在 sympy 中做双重总和?

[英]How to do double sum in sympy?

I'm trying to do the double sum of the following function:我正在尝试对以下 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其中内部求和从 i = 1 到 i = j,外部求和从 j = 1 到 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.而不是给我一个应该是数字的 object。

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.从 SymPy 1.9 版开始,SymPy 无法处理带有交叉引用索引的双和。 However, with your example we can use ordinary Python syntax to achieve the same result:但是,对于您的示例,我们可以使用普通的 Python 语法来获得相同的结果:

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.这是一个长表达式,包含多个Sum对象。 To get a purely symbolic result, we can apply the doit() method:要获得纯符号结果,我们可以应用doit()方法:

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

To get a floating point result, we can call the evalf() method:要获得浮点结果,我们可以调用evalf()方法:

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.请注意,此数字的类型是Float ,仍然是 SymPy object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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