Reputation: 149
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?
Upvotes: 0
Views: 3693
Reputation: 149
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.
Upvotes: 1