【问题标题】:Numpy array being rounded? subtraction of small floatsNumpy数组被四舍五入?小浮点数的减法
【发布时间】:2015-07-30 19:46:15
【问题描述】:

我将 numpy 数组的元素分配为等于减去“小”值的 python 浮点型数字。当我这样做并尝试通过打印到命令行来验证结果时,数组被报告为全零。这是我的代码:

import numpy as np
np.set_printoptions(precision=20)

pc1x = float(-0.438765)
pc2x = float(-0.394747)

v1 = np.array([0,0,0]) 

v1[0] = pc1x-pc2x

print pc1x
print pc2x
print v1

输出如下所示:

-0.438765
-0.394747
[0 0 0]

我预计 v1 会这样:

[-0.044018 0 0]

我承认,我是 numpy 的新手,这可能是对 numpy 和 float 如何工作的明显误解。我认为更改 numpy 打印选项会解决问题,但没有运气。任何帮助都很棒!谢谢!

【问题讨论】:

    标签: python arrays numpy rounding pretty-print


    【解决方案1】:

    您使用v1 = np.array([0,0,0]) 声明数组,numpy 假设您需要一个 int 数组。对其进行的任何后续操作都将保持此 int 数组状态,因此在明智地添加少量元素后,它会转换回 int (导致全为零)。用

    声明它
    v1 = np.array([0,0,0],dtype=float)
    

    dtype docs page. 中有详细介绍 numpy 的大量特定于 numpy 的/平台特定的数据类型

    【讨论】:

      【解决方案2】:

      您正在使用整数数据类型创建数组(由于您没有指定它,NumPy 使用您提供的初始数据的类型)。让它成为一个浮点数:

      >>> v1 = np.array([0,0,0], dtype=np.float)
      >>> v1[0] = pc1x-pc2x
      >>> print v1
      [-0.04401800000000000157  0.                      0.                    ]
      

      或者改变传入的数据类型:

      >>> v1 = np.array([0.0, 0.0, 0.0])
      >>> v1[0] = pc1x-pc2x
      >>> print v1
      [-0.04401800000000000157  0.                      0.                    ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 2016-04-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多