TypeError:'numpy.float64'对象不支持项目分配-类似的代码,错误引发 [英] TypeError: 'numpy.float64' object does not support item assignment - Similar code, error raises
问题描述
我正在编写分子动力学代码,为此,我有一个函数可以计算粒子之间的力:保守力,随机力和耗散力.保守力是成对的力,这意味着我有一个双循环来计算它们.我想节省一些时间,并在双循环的其中一个循环中包括随机力和耗散力的计算,如下所示:
I am writing a Molecular Dynamics code and for that I have a function that computes forces between particles: conservative, random and dissipative forces. The conservative forces are pairwise forces, which means I have a double loop for to compute them. I wanted to save some time and include the calculation of the random and dissipative forces in one of the loops of the double loop as follows:
fr = np.zeros((npart, dim))
fd = np.zeros((npart, dim))
fc = np.zeros((npart, dim))
for i in range(npart-1):
for d in range(dim):
# dissipative and random forces
fd[i, d] = -gamma * v[i, d]
fr[i, d] = noise/np.sqrt(dt) * np.random.normal()
for j in range(i+1, npart):
# conservative force for particle i
fc[i, 0] = fc[i, 0] + (dX/r2) * fr
fc[i, 1] = fc[i, 1] + (dY/r2) * fr
fc[i, 2] = fc[i, 2] + (dZ/r2) * fr
# conservative force for particle j (action-reaction)
fc[j, 0] = fc[j, 0] - (dX/r2) * fr
fc[j, 1] = fc[j, 1] - (dY/r2) * fr
fc[j, 2] = fc[j, 2] - (dZ/r2) * fr
此处,伽马,噪声和dt是常数.我收到以下错误:
Here gamma, noise and dt are constants. I get the following error:
fr[i, d] = noise/np.sqrt(dt)*np.random.normal()
TypeError: 'numpy.float64' object does not support item assignment
尽管如此,如果我在一个外部的,独立的循环中计算随机力和耗散力,该错误就会消失:
Nevertheless, if I compute the random and dissipative forces in an external, separate loop, the error disappears:
for i in range(npart):
for d in range(dim):
fd[i, d] = -gamma * v[i, d]
fr[i, d] = noise/np.sqrt(dt) * np.random.normal()
两种计算之间有什么区别?在单独的循环中完成计算时,为什么没有错误?
What is the difference between both computations? Why there is no error when the computation is done in a separate loop?
推荐答案
已解决:如@micric所指出,第二个循环内有一个名为"fr"的变量,其类型为float.我犯了为数组使用相同名称的错误.因此,Python的抱怨.
SOLVED: As @micric pointed out, there is a variable inside the second loop called 'fr', which is of type float. I made the mistake of using the same name for an array. Hence Python's complaints.
这篇关于TypeError:'numpy.float64'对象不支持项目分配-类似的代码,错误引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!