python - 如何在 Sympy Sum 中索引 Python 列表?

标签 python sympy

我想使用 Sympy 在 Python 中计算以下总和(代码的最后一行):

# Theta Functions, n = 0, 1, ... , x
theta_n = [0]*(x+1)
sig = sy.symbols('sigma^2', real=True)
j = sy.symbols('j', integer=True)
theta_n[0] = 1
theta_n[1] = 1 
for n in range(2,x+1):
   theta_n[n] = sy.Sum( sig**j * theta_n[n-2*j], (j,1,int(n/2))).doit()

但我得到以下错误

TypeError: list indices must be integers or slices, not Add

我是一个完全的 Sympy 新手,想知道如何以正确的方式做到这一点。一种解决方法是使用 for 循环计算总和,这很好用,但我认为这不是正确的方法。也许我需要 thetan 的其他表示形式,或者我可以以某种方式将 j 转换为总和中的整数以访问 python 列表的元素。

最佳答案

不要使用 Sum,而是使用 j 上的循环

for j in range(1, n//2 + 1):
    theta_n[n] += theta_n[n-2*j]*sig**j

这两行用 Sum 替换你的单行。

查看得到的结果后,您可能会注意到其中的模式并将第 n 项重写为

>>> theta_n = lambda x: 2**max(0, x//2-1)*sig**(x//2)
>>> theta_n(100)
562949953421312*sigma^2**50

关于python - 如何在 Sympy Sum 中索引 Python 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60412420/

相关文章:

Python 套件测试不运行测试

python - Pytest: ModuleNotFoundError: 没有名为 'src' 的模块

python - 在二维数组上使用贝叶斯统计分析进行音频过滤的笨拙建议

python - 简化使用 sympy codegen 生成的表达式

python - 为什么 sympy.init_printing 会更改集合表示法?

python - 计算/可视化 Tensorflow Keras Dense 模型层与输出类的相对连接权重

Python 监视文件夹 - 询问文件大小列表

python - 如何计算 SymPy 中函数比率的形式幂级数? [属性错误: 'Mul' object has no attribute 'truncate' ]

python - sympy 中的占位符函数

python - 在同一图中绘制 2 个或更多函数