【问题标题】:Weird result in setting column values of a numpy array设置 numpy 数组的列值的奇怪结果
【发布时间】:2021-01-30 16:54:03
【问题描述】:

在下面的脚本中,我想对(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是哪里来的?

【问题讨论】:

    标签: python numpy numpy-ndarray numpy-slicing


    【解决方案1】:

    如果您查看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 时。

    【讨论】:

    • 奇怪的是,接近 -1 的数字会四舍五入为 0。不是吗?
    • @fountainhead,混合floatint 数据类型时经常会发生奇怪的事情。如果你在旋转,你总是希望所有的 dtype 都是浮动的。
    • @fountainhead 从浮点类型转换为整数类型(类型转换)总是通过使用输入的整数部分来完成,在几乎所有常见的语言中。如果您想要其他内容,则需要明确指定。
    • 截断比舍入更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多