Home > front end >  A very simple but odd bug of Python when a variable assigned with a matrix
A very simple but odd bug of Python when a variable assigned with a matrix

Time:12-06

It bothered me for a long while, the code is as below, you may directly run it:

x = [1,2,3]
y = [1,2,3]
z = [1,2,3]

theta_x = 20*np.pi/180
theta_y = 70*np.pi/180

# rotation matrix
rot_x = np.array([[1, 0, 0],
                 [0, np.cos(theta_x), -np.sin(theta_x)],
                 [0, np.sin(theta_x), np.cos(theta_x)]])

rot_y = np.array([[np.cos(theta_y), 0, np.sin(theta_y)],
                  [0, 1, 0],
                  [-np.sin(theta_y), 0, np.cos(theta_y)]])

print('Print 1, rotated x: ', (rot_y@rot_x@(np.array([x , y , z ])))[0])
print('Print 1, rotated y: ', (rot_y@rot_x@(np.array([x , y , z ])))[1])
print('Print 1, rotated z: ', (rot_y@rot_x@(np.array([x , y , z ])))[2])
print('\n')

# Assign the rotated variables to the original variables
x = (rot_y@rot_x@(np.array([x, y , z ])))[0]
y = (rot_y@rot_x@(np.array([x, y , z ])))[1]
z = (rot_y@rot_x@(np.array([x , y , z ])))[2]

print('Print 2, rotated x: ', x)
print('Print 2, rotated y: ', y)
print('Print 2, rotated z: ', z)

What is really odd is that the results of the first print and the second print should be identical, but they do not. The first two lines are fine but the last is not. I do not know why.

====

P.S. The output is as follows:

Print 1, rotated x:  [1.54643617 3.09287234 4.63930851]
Print 1, rotated y:  [0.59767248 1.19534495 1.79301743]
Print 1, rotated z:  [-0.50132104 -1.00264208 -1.50396311]


Print 2, rotated x:  [1.54643617 3.09287234 4.63930851]
Print 2, rotated y:  [0.59767248 1.19534495 1.79301743]
Print 2, rotated z:  [-1.06186645 -2.12373291 -3.18559936]

CodePudding user response:

In this part of your code, you're assigning new values to x and then to y, so you're not evaluating the same function anymore.

# Assign the rotated variables to the original variables
x = (rot_y@rot_x@(np.array([x, y , z ])))[0]
y = (rot_y@rot_x@(np.array([x, y , z ])))[1]
z = (rot_y@rot_x@(np.array([x , y , z ])))[2]

If you do:

x,y,z = (rot_y@rot_x@(np.array([x, y , z ])))

instead, z will match your printed version.

  • Related