Home > OS >  Why does the value of the variable change?
Why does the value of the variable change?

Time:06-21

Here is the minimal version of my code:

SP=np.array([[-0.4,.2,1],[-.34,.31,1],[-.22,-.2,0],[.8,.25,0],[.92,-.42,1]])

dt=0.1

SP0=SP[:,0]
print("SP0 = ",SP0)
SP[:,0]=SP[:,0]*cos(dt) SP[:,1]*sin(dt)
print("SP0 = ", SP0)
SP[:,1]=SP[:,1]*cos(dt)-SP0*sin(dt)

OUTPUT:

SP0 =  [-0.4  -0.34 -0.22  0.8   0.92]
SP0 =  [-0.37803498 -0.30735306 -0.2388676   0.82096169  0.8734738 ]

As can be seen above, I am trying to evolve SP[:,0] and SP[:,1] depending on their previous values but in order to put the previous value of SP[:,0] in SP[:,1] (since it gets changed before moving on to SP[:,1] ) I first store it in SP0.

But this doesn't seem to make any difference because the value of SP0 also changes to the new SP[:,0] after I change SP[:,0] later. But this is weird since SP[:,0] only changes after I store it's value in SP0.

Why is this happening and how do I evolve the SP[:,1] and SP[:,0] correctly?

CodePudding user response:

Numpy slices don't create new arrays; they return views into the original array. Modifying either will affect the other.

To keep the previous value, call .copy() on the view:

SP0=SP[:,0].copy()

CodePudding user response:

Reusing variable names is usually seen as a bad practice in Python.

In your case I would suggest, that you simply assign your manipulated array to a new variable. This should solve your issue, as you can then simply reference your initial values in your next calculation step.

CodePudding user response:

Numpy arrays are referenced when sliced that means modification will update all references, so copy the content

so you can either call np.copy(SP[:,0]) or SP[:,0].copy() whichever you feel easy for you.

Working Example

import numpy as np
import math as m

SP=np.array([[-0.4,.2,1],[-.34,.31,1],[-.22,-.2,0],[.8,.25,0],[.92,-.42,1]])

dt=0.1

SP0 = np.copy(SP[:,0])
print("SP0 = ", SP0)
SP[:,0] = SP[:,0] * m.cos(dt)   SP[:,1] * m.sin(dt)

print("SP0 = ", SP0)
SP[:,1] = SP[:,1] * m.cos(dt) - SP0 * m.sin(dt)

Output

SP0 =  [-0.4  -0.34 -0.22  0.8   0.92]
SP0 =  [-0.4  -0.34 -0.22  0.8   0.92]
  • Related