在下面的脚本中,我想将旋转矩阵应用于 (Nx3)
数组的前两列。
rotate_mat = lambda theta: np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])
rot_mat = rotate_mat(np.deg2rad(90))
basis1 = np.array([[i+1,j+1,k+1] for k in range(3) for j in range(3) for i in range(3)])
basis2 = basis1.copy()
rot = basis2[:,0:2] @ rot_mat
print('rot','\n',rot[:3],'\n')
print('basis2','\n',basis2[:3],'\n')
basis2[:,0:2] = rot
print('basis2 after','\n',basis2[:3])
运行此脚本后,我获得了此输出
rot
[[ 1. -1.]
[ 1. -2.]
[ 1. -3.]]
basis2
[[1 1 1]
[2 1 1]
[3 1 1]]
basis2 after
[[ 1 0 1]
[ 1 -2 1]
[ 1 -3 1]]
通过basis2[:,0:2] = rot
可以看到,basis2
的第一行是[1,0,1]
,但是,rot
第一行明明是[1,-1]
,这个0
是从哪里来的呢?
最佳答案
如果您查看 rot
的条目,您会发现 rot[0,1]
是 -0.9999999999999999
。此外basis2.dtype == dtype('int32')
。因此,在分配过程中,新条目将转换为 int32
并将其四舍五入为零。您可以验证一下
np.int32(rot[0, 1]) == 0
和
np.int32(rot[0, 1] - 1e-16) == -1
这是由于四舍五入所致,如 np.cos(np.deg2rad(90)) == 6.123233995736766e-17
,而您可能希望它恰好为 0。
关于python - 设置 numpy 数组的列值的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64384556/