python - 设置 numpy 数组的列值的奇怪结果

标签 python numpy numpy-ndarray numpy-slicing

在下面的脚本中,我想将旋转矩阵应用于 (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/

相关文章:

python - MaskRCnn 适合什么图像尺寸?

python - Numpy 使用值列表

python - 如何计算数组中相邻的重复元素?

python - 在Windows中使用Python脚本检查程序是否挂起/崩溃?另外,管道

python - 将一行代码从 Numpy Python 转换为 Julia,涉及将一个 2D 数组映射到另一个 2D 数组

Python:快速循环np.array

python - 逐行比较二维数组

numpy - numpy中的frombuffer和fromiter有什么区别?为什么以及何时使用这些

python - 这些替代的 numpy `uniform` 与 `random` 结构可能有何不同?

python - 稀疏矩阵减法