TypeError: 'numpy.float64' object does not support item assignment - Similar code, error raises

半腔热情 提交于 2021-02-05 11:27:13

问题


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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/56883357/typeerror-numpy-float64-object-does-not-support-item-assignment-similar-cod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!