英文:
sympy.Sum error: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
问题
以下是您要翻译的代码部分:
def draw_fourier(a, n):
if len(a) < 2*n + 1:
return NotImplemented
else:
return (1/n) * sy.Sum(a[y] * np.exp(1j * y * t), (y, -n, n))
错误信息如下:
line 91, in draw_fourier
return (1/n) * sy.Sum(a[y] * np.exp(1j * y * t), (y, -n, n))
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
希望这可以帮助您解决问题。如果您有任何其他疑问,请随时提出。
英文:
I am programming the following function (in python):
def draw_fourier(a, n):
if len(a) < 2*n + 1:
return NotImplemented
else:
return (1/n) * sy.Sum(a[y] * np.exp(1j * y * t), (y, -n, n))
(sy. signifies sympy and np. signifies numpy)
And I get the following error:
line 91, in draw_fourier
return (1/n) * sy.Sum(a[y] * np.exp(1j * y * t), (y, -n, n))
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
I previously also got similar errors with sympy.Sum - I have yet to actually successfully use it, so I am curious as to what I am doing wrong, or understanding wrong about the function. I would like it to evaluate the sum for $y$ from $-n$ to $n$. a is a list and n is an (positive) integer. The reason I am using sympy is that 't' is a symbol, which I would like to assign a value to later.
Many thanks,
Hugo
答案1
得分: 1
当您使用 sy.Sum(expression, (dummy_variable, start, end))
时,您的 dummy_variable
(在这种情况下为 y
)是一个符号。错误在于 y
不能作为列表 a
的索引,因为它不是有效的索引类型,而是一个符号。
一个简单的方式来编写具有符号求和的表达式,其中 a
中的系数在每一项中都发生变化,可以是:
summation = 0 # 一些初始化
for i in range(-n, n):
summation += a[i] * sy.exp(1j * i * t)
summation = (1 / n) * summation # 最终表达式
英文:
When you use sy.Sum(expression, (dummy_variable, start, end))
your dummy_variable
(in this case y
) is a symbol. The error is that y
cannot be an index of the list a
because it is not a valid type for an index, as it is a symbol.
A simple way to write that symbolic summation where the coefficient in a
changes in every term could be:
summation=0 #some initialization
for i in range(-n,n):
summation+=a[i]*sy.exp(1j*i*t)
summation=(1/n)*summation #final expression
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论