0

I am making a simulation where I have a number of particles, and they each have a position and a velocity. For each time step i calculate a new position based on the velocity, and add that position to a list, so that I get list of previous positions. I want to use this to check which path the particles took. The issue is that every time the program calculates the new position, all entries in the path list change to the newly calculated array. For example the code

pos = array([0,0,0])
vel = array([1,1,1])
time_step = 1
path = []
path.append(pos)
for i in range(3):
    pos += vel*time_step
    path.append(pos)
    print path

generate the output

[array([1, 1, 1]), array([1, 1, 1])]
[array([2, 2, 2]), array([2, 2, 2]), array([2, 2, 2])]
[array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3]), array([3, 3, 3])]

The weirdest thing is that they don't seem to change when using append, but when calculating the new position. For example, writing

pos = array([0,0,0])
vel = array([1,1,1])
time_step = 1
path = []
path.append(pos)
pos += vel*time_step
print path

without appending the new position still generates

[array([1,1,1])]

instead of the expected

[array([0,0,0])].

Does anyone know why this happens and how I can avoid it?

JSorngard
  • 153
  • 1
  • 5

1 Answers1

1

use path.append(np.copy(pos)) instead. All the elements in your array are pointing to the same space in the memory so if you change the values in this memory space all those pointers will point to these new values. To avoid that you just need to copy the values of the numpy array to a new space in the memory using np.copy.

EDIT: Since you did from numpy import * you may just use copy().

João Abrantes
  • 4,772
  • 4
  • 35
  • 71