Python Matrix Manipulation

I use numpy operations in Python and came across an interesting observation.

If I have the following code:

x=matrix([[1,2],[3,4]]) y=matrix([[1.1,2.1],[3.1,4.1]]) x=y print x 

then it prints [[1.1,2.1],[3.1,4.1]]

However, if I do

  x=matrix([[1,2],[3,4]]) y=matrix([[1.1,2.1],[3.1,4.1]]) x[:,:]=y[:,:] print x 

then it prints only the integer part ie [[1,2],[3,4]]

Can someone tell me the reason for this?

+4
source share
3 answers

The names x and y are just labels that you can use for asisgn objects. They are not "variables", as in other languages, and they do not have a type assigned to them.

Line execution

 x = y 

it simply binds the label x to the object y that it currently points to, and discards the reference to the object that it was pointing to earlier (it is possible that the old object would be garbage collected if that was the only Help). After executing this line, x is y returns True , indicating that they both point to the same object.

Line

 x[:] = y 

on the other hand, it doesnโ€™t just attach a new label to the object, but rather modifies the existing one, the one pointed to by x . Since this existing object has an int32 element int32 , all values โ€‹โ€‹must be converted to integers. After executing this line, x is y returns False , indicating that they point to different objects.

+5
source

your x matrix has dtype int32

Edit: More interesting result:

 >>> x = np.matrix([[1,2],[3,4]],dtype='f') >>> y = np.matrix([[1.1,2.1],[3.1,4.1]],dtype='f') >>> x[:,:] = y[:,:] >>> x matrix([[ 1.10000002, 2.0999999 ], [ 3.0999999 , 4.0999999 ]], dtype=float32) 

But this is caused by pyat float error.

0
source

In the first case, when you use the assignment x = y , you set the memory cell x to the memory cell y , so basically x now just a redundant variable pointing to the same place in the memory that y points to. This way, it looks like you are creating a copy of your y matrix, but actually it is not. If after this job you had to work y and then print x and print y , you will see that they both change.

In the second case, since x initialized as an integer matrix, some automatic type casting is used so that the new values โ€‹โ€‹of each element of x are integer. In fact, you copy the values โ€‹โ€‹of your matrix y when using the assignment x[:,:] = y[:,:] , but since x is an integer matrix, Python basically does x[:,:] = int(y[:,:])

Instead, you can initialize x as follows:

 x = matrix([[1.0, 2.0], [3.0, 4.0]]) 

or how:

 x = matrix([[1, 2], [3, 4]], dtype='f') 

and you will see the result expected after executing x[:,:] = y[:,:] .

0
source

Source: https://habr.com/ru/post/1493284/


All Articles